From 81870d2989c985a8cbf889ca5ca4488cdfeb8971 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 23:08:36 +0000 Subject: [PATCH 01/84] Text: stop COLR outline work past the budget and cap one outline's path elements --- crates/text/src/colr.rs | 12 +++++-- crates/text/src/fontdb/glyph_pen.rs | 53 ++++++++++++++++++++++++++++- crates/text/src/fontdb/lookup.rs | 2 +- crates/text/src/tests/colr.rs | 22 ++++++++++++ 4 files changed, 85 insertions(+), 4 deletions(-) diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 9045a4f550..a4be3b2160 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -114,7 +114,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) if let Some(g) = font.outline_glyphs().get(gid) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen); } - let mut path = pen.0; + let mut path = pen.finish(); path.apply_affine(FLIP); path } @@ -359,7 +359,9 @@ impl ColorPainter for Tree<'_> { } fn push_clip_glyph(&mut self, glyph_id: GlyphId) { - let mut clip = outline(self.font, self.location, glyph_id); + // Past the budget the glyph is drawn as its outline anyway: later layers are not drawn, + // only opened and closed so the callbacks stay balanced. + let mut clip = if self.too_large { BezPath::new() } else { outline(self.font, self.location, glyph_id) }; clip.apply_affine(self.transform()); self.charge(&clip); self.open(Open { clip: Some(clip), blend: None, children: vec![], flooded: false }); @@ -381,6 +383,9 @@ impl ColorPainter for Tree<'_> { self.unsupported.get_or_insert("a fill outside any glyph"); return; }; + if self.too_large { + return; + } let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; if at + 1 == self.groups.len() && let Some(g) = self.groups.last_mut() @@ -392,6 +397,9 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { + if self.too_large { + return; + } let mut path = outline(self.font, self.location, glyph_id); path.apply_affine(self.transform()); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index 7f02517037..504503b70f 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,23 +7,74 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } -/// A pen drawing outlines y down, as text space has them. +/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's +/// composite glyph repeating a large component many times) is drawn as nothing, not kept. +pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; + +/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path +/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path. pub(crate) struct FlipPen(pub(crate) BezPath); +impl FlipPen { + /// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`]. + pub(crate) fn finish(self) -> BezPath { + if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 } + } + + fn full(&self) -> bool { + self.0.elements().len() >= MAX_OUTLINE_ELEMENTS + } +} + impl OutlinePen for FlipPen { fn move_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.move_to((x as f64, -y as f64)); } fn line_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.line_to((x as f64, -y as f64)); } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); } fn close(&mut self) { + if self.full() { + return; + } self.0.close_path(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pen_past_the_cap_gives_nothing() { + let mut pen = FlipPen(BezPath::new()); + pen.move_to(0.0, 0.0); + for i in 0..MAX_OUTLINE_ELEMENTS + 10 { + pen.line_to(i as f32, 1.0); + } + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments"); + assert!(pen.finish().elements().is_empty()); + let mut small = FlipPen(BezPath::new()); + small.move_to(0.0, 0.0); + small.line_to(1.0, 1.0); + assert_eq!(small.finish().elements().len(), 2); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 71e8e7ab88..30b4b8229c 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -535,7 +535,7 @@ impl FontDb { { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); } - let p = Arc::new(pen.0); + let p = Arc::new(pen.finish()); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index 212882ce7a..43c833406c 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -411,3 +411,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() { assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}"); assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}"); } + +/// A layer list that reuses one run of layers many times grows the tree past its node cap: the +/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn. +#[test] +fn layers_repeating_a_run_of_layers_pass_the_cap() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32(); + let o = GlyphId16::new(u16::try_from(o).unwrap()); + let font = |runs: u8| { + // 255 glyph layers, then `runs` layers that each repeat all of them. + let mut layers: Vec = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect(); + layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0))); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into(); + colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into(); + crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap() + }; + assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit"); + assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not"); +} From b314df82cfece3aa27f01e32133290fe776effb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 06:54:51 -0800 Subject: [PATCH 02/84] Color: FOGRA51 and FOGRA52 CMYK working spaces computed from Fogra's data Two new built-in CMYK working spaces, VectorCraft Coated CMYK (FOGRA51) and VectorCraft Uncoated CMYK (FOGRA52), follow Generic CMYK in every profile list. Generic CMYK stays the default. Fogra publishes the measured colors of these printing conditions and allows the data to be redistributed unmodified with Fogra named as the source. The two files ship byte for byte in crates/color/data/, with a test that pins their SHA-256. The press model is computed from them the first time a space is used: the paper, solids and overprints are the measured patches, each ink's tone curve is fitted to its ramp, and a smoothed Lab correction lattice is fitted to all 1,617 patches. The 300% ink limit and the black generation are VectorCraft's own values. A PDF/X output intent made with one of them names FOGRA51 or FOGRA52 in the http://www.color.org registry and embeds the profile, unless the settings give an identifier or registry. The profile's copyright tag names Fogra as the data source. Part of #3790 --- ASSETS.md | 9 + Cargo.lock | 1 + NOTICE | 11 + crates/color/Cargo.toml | 1 + crates/color/data/.gitattributes | 2 + crates/color/data/FOGRA51.txt | 1641 ++++++++++++++++++++++++ crates/color/data/FOGRA52.txt | 1641 ++++++++++++++++++++++++ crates/color/src/cms.rs | 42 +- crates/color/src/cms/generic.rs | 32 +- crates/color/src/cms/icc.rs | 16 +- crates/color/src/cms/measured.rs | 362 ++++++ crates/color/src/cms/tests_measured.rs | 186 +++ crates/engine/src/cmd/colormgmt.rs | 2 +- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/output.rs | 16 +- crates/pdf/src/tests/pdfx.rs | 68 + 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/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/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/nl.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/zh-hans.tsv | 2 + docs/mcp.md | 12 + docs/target-app-parity.md | 1 + 37 files changed, 4064 insertions(+), 19 deletions(-) create mode 100644 crates/color/data/.gitattributes create mode 100644 crates/color/data/FOGRA51.txt create mode 100644 crates/color/data/FOGRA52.txt create mode 100644 crates/color/src/cms/measured.rs create mode 100644 crates/color/src/cms/tests_measured.rs diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..c557d30c24 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -16,6 +16,15 @@ | `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file | | `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file | +## Printing-condition characterization data + +Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed. + +| Asset | Author | Source | Licence | Notes | +|---|---|---|---|---| +| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) | +| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) | + Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table. **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). diff --git a/Cargo.lock b/Cargo.lock index 8a06417e08..c9c8322e9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6773,6 +6773,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2", "thiserror 2.0.21", ] diff --git a/NOTICE b/NOTICE index a6a1299cde..3d8a1ba3de 100644 --- a/NOTICE +++ b/NOTICE @@ -147,6 +147,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option. Original copyright and full license notices are preserved in each hyph-*.tex file. Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5. +FOGRA51 and FOGRA52 characterization data (crates/color/data/): +Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org, +https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed +unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is +permitted, including redistribution as part of commercial and non-commercial software, provided +that the data are distributed unmodified and Fogra is identified as the source. The designation +FOGRAxx may be used solely to identify the respective reference data. Such use does not imply +certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and +Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code; +they are not Fogra profiles. + JPEG encoder dependency notices diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..58244835f8 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -18,3 +18,4 @@ moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } serde_json = { workspace = true } +sha2 = { version = "0.10", default-features = false } diff --git a/crates/color/data/.gitattributes b/crates/color/data/.gitattributes new file mode 100644 index 0000000000..05b9b7ef3c --- /dev/null +++ b/crates/color/data/.gitattributes @@ -0,0 +1,2 @@ +# The characterization data files are kept byte for byte as published (CRLF line endings). +*.txt -text diff --git a/crates/color/data/FOGRA51.txt b/crates/color/data/FOGRA51.txt new file mode 100644 index 0000000000..1bf721cbbd --- /dev/null +++ b/crates/color/data/FOGRA51.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA51" +ORIGINATOR "Fogra, www.fogra.org, developed by GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 1 = premium coated, fluorescence moderate (8-14 DeltaB according to ISO 15397), 115 g/m2, tone value increase curves A (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 95.00 1.50 -6.00 +2 0 10 0 0 90.08 8.15 -7.42 +3 0 20 0 0 85.20 14.67 -8.29 +4 0 30 0 0 80.33 21.39 -8.87 +5 0 40 0 0 75.43 28.45 -9.24 +6 0 55 0 0 67.98 40.01 -9.56 +7 0 70 0 0 60.42 52.69 -9.17 +8 0 85 0 0 53.32 65.54 -7.71 +9 0 100 0 0 48.06 75.29 -5.18 +10 10 0 0 0 91.19 -2.28 -10.93 +11 10 10 0 0 86.47 4.14 -11.97 +12 10 20 0 0 81.74 10.48 -12.69 +13 10 30 0 0 77.05 17.05 -13.20 +14 10 40 0 0 72.39 23.71 -13.36 +15 10 55 0 0 65.04 35.29 -13.80 +16 10 70 0 0 57.69 47.54 -13.21 +17 10 85 0 0 50.64 60.42 -12.20 +18 10 100 0 0 45.36 70.44 -10.15 +19 20 0 0 0 87.20 -5.64 -15.58 +20 20 10 0 0 82.71 0.55 -16.41 +21 20 20 0 0 78.13 6.82 -17.10 +22 20 30 0 0 73.63 12.96 -17.21 +23 20 40 0 0 69.00 19.75 -17.58 +24 20 55 0 0 61.92 30.79 -17.90 +25 20 70 0 0 54.67 43.07 -17.59 +26 20 85 0 0 47.85 55.48 -16.64 +27 20 100 0 0 42.75 65.36 -14.76 +28 30 0 0 0 83.19 -9.04 -20.26 +29 30 10 0 0 78.86 -3.06 -21.03 +30 30 20 0 0 74.49 3.06 -21.47 +31 30 30 0 0 70.10 9.12 -21.61 +32 30 40 0 0 65.63 15.55 -21.84 +33 30 55 0 0 58.82 26.25 -21.96 +34 30 70 0 0 51.79 38.09 -21.59 +35 30 85 0 0 45.06 50.62 -20.96 +36 30 100 0 0 40.08 60.48 -19.61 +37 40 0 0 0 79.15 -12.57 -24.94 +38 40 10 0 0 74.98 -6.71 -25.60 +39 40 20 0 0 70.80 -0.81 -25.82 +40 40 30 0 0 66.54 5.13 -25.91 +41 40 40 0 0 62.24 11.37 -26.06 +42 40 55 0 0 55.70 21.88 -26.29 +43 40 70 0 0 48.86 33.45 -25.85 +44 40 85 0 0 42.31 45.45 -25.15 +45 40 100 0 0 37.42 55.26 -24.13 +46 55 0 0 0 72.95 -18.09 -32.32 +47 55 10 0 0 69.08 -12.46 -32.61 +48 55 20 0 0 65.15 -6.92 -32.53 +49 55 30 0 0 61.16 -1.28 -32.51 +50 55 40 0 0 57.13 4.79 -32.58 +51 55 55 0 0 50.88 15.11 -32.86 +52 55 70 0 0 44.47 25.94 -32.21 +53 55 85 0 0 38.22 37.55 -31.73 +54 55 100 0 0 33.61 47.12 -31.03 +55 70 0 0 0 66.57 -24.03 -39.84 +56 70 10 0 0 63.02 -18.76 -39.93 +57 70 20 0 0 59.38 -13.26 -39.73 +58 70 30 0 0 55.73 -8.01 -39.46 +59 70 40 0 0 51.98 -2.30 -39.36 +60 70 55 0 0 46.09 7.47 -39.17 +61 70 70 0 0 40.13 17.91 -38.49 +62 70 85 0 0 34.29 29.43 -38.42 +63 70 100 0 0 30.05 38.27 -37.82 +64 85 0 0 0 60.62 -30.20 -47.07 +65 85 10 0 0 57.34 -25.34 -47.00 +66 85 20 0 0 54.05 -20.11 -46.39 +67 85 30 0 0 50.67 -14.86 -46.05 +68 85 40 0 0 47.21 -9.60 -45.78 +69 85 55 0 0 41.82 -0.52 -45.22 +70 85 70 0 0 36.22 9.96 -44.61 +71 85 85 0 0 30.93 20.56 -44.00 +72 85 100 0 0 26.93 28.85 -43.51 +73 100 0 0 0 56.12 -34.90 -52.52 +74 100 10 0 0 53.12 -30.18 -52.18 +75 100 20 0 0 49.98 -25.20 -51.65 +76 100 30 0 0 46.82 -20.29 -51.01 +77 100 40 0 0 43.67 -14.81 -50.35 +78 100 55 0 0 38.75 -6.19 -49.58 +79 100 70 0 0 33.65 3.36 -48.78 +80 100 85 0 0 28.60 13.42 -48.00 +81 100 100 0 0 24.74 21.12 -47.45 +82 0 0 10 0 94.39 -0.05 3.02 +83 0 10 10 0 89.49 6.73 1.30 +84 0 20 10 0 84.62 13.27 0.10 +85 0 30 10 0 79.82 20.14 -0.92 +86 0 40 10 0 75.00 27.19 -1.77 +87 0 55 10 0 67.58 39.10 -2.81 +88 0 70 10 0 60.05 51.73 -2.96 +89 0 85 10 0 53.14 64.72 -2.17 +90 0 100 10 0 48.16 74.50 -0.60 +91 10 0 10 0 90.49 -4.02 -1.77 +92 10 10 10 0 85.82 2.56 -3.46 +93 10 20 10 0 81.12 9.05 -4.50 +94 10 30 10 0 76.46 15.71 -5.46 +95 10 40 10 0 71.79 22.68 -6.25 +96 10 55 10 0 64.57 34.21 -7.17 +97 10 70 10 0 57.26 46.86 -7.31 +98 10 85 10 0 50.43 59.66 -6.79 +99 10 100 10 0 45.39 69.49 -5.43 +100 20 0 10 0 86.44 -7.45 -6.60 +101 20 10 10 0 82.01 -1.17 -8.02 +102 20 20 10 0 77.49 5.15 -8.92 +103 20 30 10 0 72.97 11.64 -9.73 +104 20 40 10 0 68.44 18.44 -10.47 +105 20 55 10 0 61.44 29.71 -11.32 +106 20 70 10 0 54.31 42.07 -11.62 +107 20 85 10 0 47.62 54.54 -11.26 +108 20 100 10 0 42.65 64.50 -10.16 +109 30 0 10 0 82.42 -11.08 -11.48 +110 30 10 10 0 78.15 -5.00 -12.67 +111 30 20 10 0 73.82 1.16 -13.49 +112 30 30 10 0 69.44 7.49 -14.18 +113 30 40 10 0 65.05 14.11 -14.78 +114 30 55 10 0 58.30 25.08 -15.56 +115 30 70 10 0 51.40 37.07 -15.81 +116 30 85 10 0 44.85 49.58 -15.76 +117 30 100 10 0 40.03 59.14 -14.92 +118 40 0 10 0 78.34 -14.91 -16.35 +119 40 10 10 0 74.24 -8.90 -17.42 +120 40 20 10 0 70.09 -2.91 -17.98 +121 40 30 10 0 65.91 3.27 -18.54 +122 40 40 10 0 61.68 9.69 -19.12 +123 40 55 10 0 55.18 20.32 -19.84 +124 40 70 10 0 48.45 32.09 -20.21 +125 40 85 10 0 42.11 44.34 -20.15 +126 40 100 10 0 37.43 53.85 -19.55 +127 55 0 10 0 72.13 -20.88 -23.94 +128 55 10 10 0 68.33 -15.07 -24.69 +129 55 20 10 0 64.46 -9.33 -25.04 +130 55 30 10 0 60.56 -3.46 -25.47 +131 55 40 10 0 56.60 2.73 -25.84 +132 55 55 10 0 50.46 12.95 -26.33 +133 55 70 10 0 44.07 24.26 -26.67 +134 55 85 10 0 37.99 36.05 -26.83 +135 55 100 10 0 33.49 45.40 -26.61 +136 70 0 10 0 65.70 -27.36 -31.85 +137 70 10 10 0 62.29 -21.91 -32.17 +138 70 20 10 0 58.73 -16.35 -32.31 +139 70 30 10 0 55.11 -10.78 -32.46 +140 70 40 10 0 51.44 -4.87 -32.68 +141 70 55 10 0 45.66 4.96 -33.04 +142 70 70 10 0 39.72 15.80 -33.20 +143 70 85 10 0 34.08 27.07 -33.31 +144 70 100 10 0 29.85 36.13 -33.10 +145 85 0 10 0 59.68 -34.68 -39.35 +146 85 10 10 0 56.58 -29.13 -39.40 +147 85 20 10 0 53.35 -23.81 -39.27 +148 85 30 10 0 50.01 -18.41 -39.22 +149 85 40 10 0 46.60 -12.87 -39.27 +150 85 55 10 0 41.29 -3.48 -39.33 +151 85 70 10 0 35.80 6.88 -39.36 +152 85 85 10 0 30.60 17.60 -39.25 +153 85 100 10 0 26.69 26.51 -39.05 +154 100 0 10 0 55.09 -39.46 -45.04 +155 100 10 10 0 52.33 -34.67 -44.86 +156 100 20 10 0 49.27 -29.55 -44.55 +157 100 30 10 0 46.18 -24.31 -44.32 +158 100 40 10 0 43.11 -18.79 -44.05 +159 100 55 10 0 38.18 -9.90 -43.86 +160 100 70 10 0 33.15 -0.14 -43.50 +161 100 85 10 0 28.30 10.01 -43.28 +162 100 100 10 0 24.62 18.19 -43.14 +163 0 0 20 0 93.66 -1.17 11.88 +164 0 10 20 0 88.80 5.61 9.82 +165 0 20 20 0 83.99 12.38 8.29 +166 0 30 20 0 79.22 19.33 6.84 +167 0 40 20 0 74.45 26.49 5.48 +168 0 55 20 0 67.16 38.37 3.96 +169 0 70 20 0 59.71 51.18 3.25 +170 0 85 20 0 52.90 63.96 3.39 +171 0 100 20 0 48.12 73.47 4.61 +172 10 0 20 0 89.71 -5.18 6.94 +173 10 10 20 0 85.11 1.37 4.94 +174 10 20 20 0 80.48 7.98 3.55 +175 10 30 20 0 75.86 14.70 2.17 +176 10 40 20 0 71.22 21.76 0.95 +177 10 55 20 0 64.07 33.39 -0.52 +178 10 70 20 0 56.85 46.17 -1.38 +179 10 85 20 0 50.19 58.88 -1.37 +180 10 100 20 0 45.29 68.63 -0.38 +181 20 0 20 0 85.72 -8.99 2.17 +182 20 10 20 0 81.30 -2.54 0.32 +183 20 20 20 0 76.83 3.86 -1.11 +184 20 30 20 0 72.35 10.44 -2.33 +185 20 40 20 0 67.84 17.35 -3.39 +186 20 55 20 0 60.91 28.74 -4.79 +187 20 70 20 0 53.93 41.13 -5.60 +188 20 85 20 0 47.39 53.82 -5.87 +189 20 100 20 0 42.55 63.34 -5.04 +190 30 0 20 0 81.66 -12.79 -2.89 +191 30 10 20 0 77.44 -6.52 -4.62 +192 30 20 20 0 73.13 -0.29 -5.75 +193 30 30 20 0 68.80 6.12 -6.82 +194 30 40 20 0 64.43 12.85 -7.84 +195 30 55 20 0 57.77 23.97 -9.14 +196 30 70 20 0 50.99 36.22 -10.04 +197 30 85 20 0 44.59 48.53 -10.43 +198 30 100 20 0 39.88 58.18 -9.88 +199 40 0 20 0 77.55 -16.73 -7.99 +200 40 10 20 0 73.52 -10.68 -9.43 +201 40 20 20 0 69.39 -4.59 -10.41 +202 40 30 20 0 65.23 1.69 -11.32 +203 40 40 20 0 61.04 8.29 -12.27 +204 40 55 20 0 54.63 19.05 -13.50 +205 40 70 20 0 48.07 30.94 -14.39 +206 40 85 20 0 41.81 43.21 -15.01 +207 40 100 20 0 37.28 52.69 -14.60 +208 55 0 20 0 71.31 -23.09 -15.80 +209 55 10 20 0 67.58 -17.25 -16.84 +210 55 20 20 0 63.73 -11.42 -17.58 +211 55 30 20 0 59.85 -5.38 -18.43 +212 55 40 20 0 55.97 0.93 -19.08 +213 55 55 20 0 49.94 11.27 -20.01 +214 55 70 20 0 43.68 22.77 -20.85 +215 55 85 20 0 37.73 34.62 -21.62 +216 55 100 20 0 33.31 43.89 -21.69 +217 70 0 20 0 64.93 -30.24 -23.83 +218 70 10 20 0 61.50 -24.61 -24.57 +219 70 20 20 0 57.98 -18.95 -25.00 +220 70 30 20 0 54.40 -13.10 -25.57 +221 70 40 20 0 50.79 -7.11 -26.06 +222 70 55 20 0 45.17 2.77 -26.82 +223 70 70 20 0 39.33 13.82 -27.50 +224 70 85 20 0 33.74 25.26 -28.26 +225 70 100 20 0 29.61 34.33 -28.32 +226 85 0 20 0 58.88 -38.00 -31.58 +227 85 10 20 0 55.83 -32.55 -31.96 +228 85 20 20 0 52.62 -27.03 -32.09 +229 85 30 20 0 49.31 -21.43 -32.36 +230 85 40 20 0 45.93 -15.65 -32.81 +231 85 55 20 0 40.74 -6.29 -33.32 +232 85 70 20 0 35.38 4.26 -33.81 +233 85 85 20 0 30.26 15.11 -34.30 +234 85 100 20 0 26.54 23.88 -34.29 +235 100 0 20 0 54.45 -43.84 -37.25 +236 100 10 20 0 51.62 -38.86 -37.54 +237 100 20 20 0 48.62 -33.48 -37.55 +238 100 30 20 0 45.58 -28.05 -37.59 +239 100 40 20 0 42.45 -22.44 -37.78 +240 100 55 20 0 37.59 -13.09 -37.99 +241 100 70 20 0 32.60 -3.11 -38.23 +242 100 85 20 0 27.97 7.02 -38.33 +243 100 100 20 0 24.56 15.08 -38.49 +244 0 0 30 0 92.93 -2.11 20.82 +245 0 10 30 0 88.12 4.83 18.28 +246 0 20 30 0 83.36 11.75 16.24 +247 0 30 30 0 78.60 18.51 14.37 +248 0 40 30 0 73.91 25.86 12.81 +249 0 55 30 0 66.79 37.74 10.67 +250 0 70 30 0 59.48 50.64 9.35 +251 0 85 30 0 52.78 63.42 8.80 +252 0 100 30 0 48.13 72.82 9.76 +253 10 0 30 0 88.96 -6.25 15.64 +254 10 10 30 0 84.38 0.40 13.34 +255 10 20 30 0 79.79 7.05 11.44 +256 10 30 30 0 75.22 13.84 9.77 +257 10 40 30 0 70.66 20.96 8.20 +258 10 55 30 0 63.65 32.73 6.16 +259 10 70 30 0 56.56 45.35 4.71 +260 10 85 30 0 50.04 58.07 4.09 +261 10 100 30 0 45.28 67.61 4.74 +262 20 0 30 0 84.94 -10.13 10.68 +263 20 10 30 0 80.55 -3.72 8.48 +264 20 20 30 0 76.13 2.80 6.78 +265 20 30 30 0 71.71 9.46 5.24 +266 20 40 30 0 67.28 16.43 3.81 +267 20 55 30 0 60.45 27.89 1.78 +268 20 70 30 0 53.60 40.27 0.33 +269 20 85 30 0 47.22 53.05 -0.46 +270 20 100 30 0 42.46 62.48 0.00 +271 30 0 30 0 80.90 -14.17 5.54 +272 30 10 30 0 76.69 -7.84 3.48 +273 30 20 30 0 72.44 -1.53 1.92 +274 30 30 30 0 68.15 4.97 0.52 +275 30 40 30 0 63.83 11.80 -0.74 +276 30 55 30 0 57.26 22.97 -2.61 +277 30 70 30 0 50.59 35.16 -4.16 +278 30 85 30 0 44.35 47.52 -5.07 +279 30 100 30 0 39.76 57.01 -4.74 +280 40 0 30 0 76.82 -18.46 0.41 +281 40 10 30 0 72.77 -12.19 -1.43 +282 40 20 30 0 68.68 -6.06 -2.83 +283 40 30 30 0 64.56 0.33 -4.14 +284 40 40 30 0 60.43 6.99 -5.30 +285 40 55 30 0 54.10 17.91 -7.03 +286 40 70 30 0 47.63 29.88 -8.51 +287 40 85 30 0 41.55 42.11 -9.54 +288 40 100 30 0 37.11 51.53 -9.65 +289 55 0 30 0 70.50 -25.13 -7.66 +290 55 10 30 0 66.84 -19.26 -9.16 +291 55 20 30 0 62.99 -13.24 -10.21 +292 55 30 30 0 59.14 -7.08 -11.30 +293 55 40 30 0 55.33 -0.69 -12.30 +294 55 55 30 0 49.41 9.81 -13.81 +295 55 70 30 0 43.25 21.40 -15.18 +296 55 85 30 0 37.44 33.28 -16.35 +297 55 100 30 0 33.22 42.37 -16.72 +298 70 0 30 0 64.19 -32.83 -15.78 +299 70 10 30 0 60.75 -27.06 -16.96 +300 70 20 30 0 57.25 -21.23 -17.84 +301 70 30 30 0 53.69 -15.28 -18.64 +302 70 40 30 0 50.13 -9.20 -19.42 +303 70 55 30 0 44.66 0.84 -20.69 +304 70 70 30 0 38.92 12.02 -21.93 +305 70 85 30 0 33.50 23.44 -22.97 +306 70 100 30 0 29.46 32.47 -23.51 +307 85 0 30 0 58.20 -40.80 -23.80 +308 85 10 30 0 55.08 -35.60 -24.55 +309 85 20 30 0 51.91 -29.96 -25.06 +310 85 30 30 0 48.63 -24.28 -25.64 +311 85 40 30 0 45.31 -18.47 -26.30 +312 85 55 30 0 40.24 -8.71 -27.30 +313 85 70 30 0 34.98 1.95 -28.25 +314 85 85 30 0 29.96 12.75 -29.23 +315 85 100 30 0 26.31 21.41 -29.66 +316 100 0 30 0 53.75 -47.89 -29.55 +317 100 10 30 0 50.87 -42.60 -30.25 +318 100 20 30 0 47.88 -37.15 -30.69 +319 100 30 30 0 44.86 -31.58 -31.07 +320 100 40 30 0 41.80 -25.81 -31.46 +321 100 55 30 0 37.06 -16.36 -32.11 +322 100 70 30 0 32.17 -6.06 -32.78 +323 100 85 30 0 27.64 4.24 -33.30 +324 100 100 30 0 24.42 12.12 -33.86 +325 0 0 40 0 92.30 -2.85 30.21 +326 0 10 40 0 87.51 4.01 27.25 +327 0 20 40 0 82.77 11.08 24.69 +328 0 30 40 0 78.05 17.89 22.50 +329 0 40 40 0 73.41 25.29 20.43 +330 0 55 40 0 66.38 37.19 17.71 +331 0 70 40 0 59.22 49.87 15.87 +332 0 85 40 0 52.68 62.69 14.60 +333 0 100 40 0 48.17 72.08 14.73 +334 10 0 40 0 88.35 -7.18 24.87 +335 10 10 40 0 83.73 -0.45 22.05 +336 10 20 40 0 79.16 6.30 19.75 +337 10 30 40 0 74.64 13.16 17.72 +338 10 40 40 0 70.14 20.29 15.78 +339 10 55 40 0 63.25 32.11 13.18 +340 10 70 40 0 56.28 44.74 11.11 +341 10 85 40 0 49.91 57.53 9.88 +342 10 100 40 0 45.28 67.03 9.82 +343 20 0 40 0 84.26 -11.13 19.59 +344 20 10 40 0 79.86 -4.64 17.06 +345 20 20 40 0 75.48 1.93 14.90 +346 20 30 40 0 71.13 8.64 13.02 +347 20 40 40 0 66.77 15.64 11.23 +348 20 55 40 0 60.06 27.12 8.66 +349 20 70 40 0 53.30 39.52 6.57 +350 20 85 40 0 47.08 52.15 5.20 +351 20 100 40 0 42.48 61.62 5.11 +352 30 0 40 0 80.13 -15.20 14.20 +353 30 10 40 0 75.98 -9.00 11.91 +354 30 20 40 0 71.79 -2.59 9.96 +355 30 30 40 0 67.57 3.98 8.28 +356 30 40 40 0 63.34 10.85 6.55 +357 30 55 40 0 56.85 22.07 4.10 +358 30 70 40 0 50.28 34.34 2.00 +359 30 85 40 0 44.20 46.84 0.51 +360 30 100 40 0 39.73 56.15 0.27 +361 40 0 40 0 76.04 -19.68 8.86 +362 40 10 40 0 72.08 -13.55 6.80 +363 40 20 40 0 68.03 -7.37 5.09 +364 40 30 40 0 63.97 -0.88 3.41 +365 40 40 40 0 59.91 5.85 1.87 +366 40 55 40 0 53.66 16.87 -0.44 +367 40 70 40 0 47.28 28.91 -2.48 +368 40 85 40 0 41.35 41.02 -4.11 +369 40 100 40 0 37.09 50.34 -4.61 +370 55 0 40 0 69.75 -26.88 0.64 +371 55 10 40 0 66.15 -20.98 -1.12 +372 55 20 40 0 62.33 -14.93 -2.61 +373 55 30 40 0 58.52 -8.70 -3.96 +374 55 40 40 0 54.78 -2.19 -5.29 +375 55 55 40 0 48.96 8.44 -7.30 +376 55 70 40 0 42.92 20.09 -9.21 +377 55 85 40 0 37.27 31.98 -10.90 +378 55 100 40 0 33.15 41.15 -11.72 +379 70 0 40 0 63.35 -34.69 -7.90 +380 70 10 40 0 60.09 -29.24 -9.16 +381 70 20 40 0 56.60 -23.38 -10.36 +382 70 30 40 0 53.08 -17.39 -11.47 +383 70 40 40 0 49.63 -11.13 -12.58 +384 70 55 40 0 44.24 -0.96 -14.34 +385 70 70 40 0 38.63 10.30 -16.10 +386 70 85 40 0 33.31 21.83 -17.72 +387 70 100 40 0 29.38 30.77 -18.60 +388 85 0 40 0 57.58 -44.64 -15.60 +389 85 10 40 0 54.39 -38.45 -16.91 +390 85 20 40 0 51.21 -32.80 -17.83 +391 85 30 40 0 48.02 -26.95 -18.78 +392 85 40 40 0 44.78 -20.99 -19.67 +393 85 55 40 0 39.81 -11.13 -21.12 +394 85 70 40 0 34.65 -0.40 -22.60 +395 85 85 40 0 29.74 10.62 -24.04 +396 85 100 40 0 26.08 19.22 -25.01 +397 100 0 40 0 52.96 -51.61 -21.76 +398 100 10 40 0 50.06 -46.17 -22.89 +399 100 20 40 0 47.12 -40.58 -23.70 +400 100 30 40 0 44.18 -34.82 -24.39 +401 100 40 40 0 41.16 -29.04 -25.13 +402 100 55 40 0 36.59 -19.17 -26.07 +403 100 70 40 0 31.81 -8.79 -27.14 +404 100 85 40 0 27.38 1.57 -28.22 +405 100 100 40 0 24.35 9.47 -29.16 +406 0 0 55 0 91.32 -3.67 45.02 +407 0 10 55 0 86.60 3.32 41.44 +408 0 20 55 0 81.91 10.35 38.27 +409 0 30 55 0 77.28 17.36 35.23 +410 0 40 55 0 72.69 24.78 32.53 +411 0 55 55 0 65.75 36.53 28.96 +412 0 70 55 0 58.79 49.47 25.89 +413 0 85 55 0 52.49 61.80 23.63 +414 0 100 55 0 48.17 71.02 22.53 +415 10 0 55 0 87.33 -8.13 39.05 +416 10 10 55 0 82.76 -1.44 35.92 +417 10 20 55 0 78.26 5.40 32.96 +418 10 30 55 0 73.82 12.35 30.24 +419 10 40 55 0 69.36 19.58 27.72 +420 10 55 55 0 62.58 31.42 24.17 +421 10 70 55 0 55.80 44.02 21.11 +422 10 85 55 0 49.64 56.62 18.78 +423 10 100 55 0 45.26 65.78 17.66 +424 20 0 55 0 83.17 -12.28 33.49 +425 20 10 55 0 78.82 -5.81 30.49 +426 20 20 55 0 74.53 0.85 27.86 +427 20 30 55 0 70.27 7.62 25.37 +428 20 40 55 0 65.98 14.73 22.98 +429 20 55 55 0 59.38 26.33 19.51 +430 20 70 55 0 52.79 38.78 16.47 +431 20 85 55 0 46.77 51.10 14.01 +432 20 100 55 0 42.46 60.41 12.84 +433 30 0 55 0 79.08 -16.83 27.95 +434 30 10 55 0 74.93 -10.40 25.19 +435 30 20 55 0 70.84 -3.93 22.75 +436 30 30 55 0 66.74 2.75 20.39 +437 30 40 55 0 62.57 9.68 18.12 +438 30 55 55 0 56.19 21.01 14.74 +439 30 70 55 0 49.77 33.34 11.67 +440 30 85 55 0 43.92 45.47 9.21 +441 30 100 55 0 39.74 54.78 7.73 +442 40 0 55 0 74.94 -21.38 22.21 +443 40 10 55 0 71.05 -15.28 19.78 +444 40 20 55 0 67.11 -8.96 17.52 +445 40 30 55 0 63.13 -2.38 15.35 +446 40 40 55 0 59.14 4.42 13.19 +447 40 55 55 0 53.03 15.57 10.01 +448 40 70 55 0 46.84 27.72 7.05 +449 40 85 55 0 41.11 39.71 4.39 +450 40 100 55 0 37.05 48.72 2.84 +451 55 0 55 0 68.69 -29.37 13.83 +452 55 10 55 0 65.11 -23.16 11.48 +453 55 20 55 0 61.40 -17.05 9.50 +454 55 30 55 0 57.67 -10.69 7.59 +455 55 40 55 0 53.99 -4.11 5.73 +456 55 55 55 0 48.34 6.63 2.83 +457 55 70 55 0 42.50 18.45 -0.02 +458 55 85 55 0 37.02 30.29 -2.59 +459 55 100 55 0 33.06 39.36 -4.19 +460 70 0 55 0 62.29 -38.07 5.01 +461 70 10 55 0 59.01 -32.13 3.09 +462 70 20 55 0 55.59 -26.22 1.37 +463 70 30 55 0 52.17 -20.09 -0.28 +464 70 40 55 0 48.82 -13.71 -1.90 +465 70 55 55 0 43.60 -3.37 -4.48 +466 70 70 55 0 38.16 8.07 -7.13 +467 70 85 55 0 32.99 19.73 -9.60 +468 70 100 55 0 29.27 28.50 -11.05 +469 85 0 55 0 56.30 -48.22 -3.54 +470 85 10 55 0 53.32 -42.47 -5.11 +471 85 20 55 0 50.17 -36.82 -6.61 +472 85 30 55 0 47.07 -30.67 -8.01 +473 85 40 55 0 44.00 -24.40 -9.30 +474 85 55 55 0 39.12 -14.36 -11.59 +475 85 70 55 0 34.10 -3.35 -13.90 +476 85 85 55 0 29.38 7.83 -16.08 +477 85 100 55 0 25.90 16.32 -17.55 +478 100 0 55 0 51.74 -56.78 -9.82 +479 100 10 55 0 49.04 -51.08 -11.37 +480 100 20 55 0 46.18 -45.42 -12.66 +481 100 30 55 0 43.31 -39.42 -13.93 +482 100 40 55 0 40.36 -33.37 -15.04 +483 100 55 55 0 35.87 -23.24 -16.72 +484 100 70 55 0 31.27 -12.66 -18.78 +485 100 85 55 0 27.09 -2.18 -20.46 +486 100 100 55 0 24.21 5.65 -21.76 +487 0 0 70 0 90.44 -4.21 61.28 +488 0 10 70 0 85.77 2.80 56.87 +489 0 20 70 0 81.09 9.84 53.00 +490 0 30 70 0 76.48 16.91 49.31 +491 0 40 70 0 71.94 24.41 45.95 +492 0 55 70 0 65.15 36.37 41.18 +493 0 70 70 0 58.43 49.19 36.75 +494 0 85 70 0 52.34 61.38 33.02 +495 0 100 70 0 48.12 70.32 31.23 +496 10 0 70 0 86.46 -9.05 54.87 +497 10 10 70 0 81.91 -2.16 50.99 +498 10 20 70 0 77.44 4.73 47.51 +499 10 30 70 0 73.02 11.72 44.05 +500 10 40 70 0 68.62 19.03 40.88 +501 10 55 70 0 61.95 30.97 36.27 +502 10 70 70 0 55.36 43.55 31.94 +503 10 85 70 0 49.42 55.97 28.39 +504 10 100 70 0 45.20 65.01 26.02 +505 20 0 70 0 82.24 -13.32 48.89 +506 20 10 70 0 77.92 -6.70 45.51 +507 20 20 70 0 73.66 -0.06 42.17 +508 20 30 70 0 69.44 6.82 38.88 +509 20 40 70 0 65.21 14.02 35.84 +510 20 55 70 0 58.74 25.68 31.39 +511 20 70 70 0 52.33 38.11 27.14 +512 20 85 70 0 46.51 50.27 23.44 +513 20 100 70 0 42.41 59.29 21.01 +514 30 0 70 0 78.07 -17.87 43.09 +515 30 10 70 0 73.98 -11.48 39.78 +516 30 20 70 0 69.92 -4.97 36.83 +517 30 30 70 0 65.90 1.75 33.70 +518 30 40 70 0 61.82 8.78 30.68 +519 30 55 70 0 55.56 20.17 26.31 +520 30 70 70 0 49.35 32.36 22.15 +521 30 85 70 0 43.69 44.38 18.44 +522 30 100 70 0 39.68 53.47 15.90 +523 40 0 70 0 73.98 -22.90 37.12 +524 40 10 70 0 70.07 -16.58 34.00 +525 40 20 70 0 66.20 -10.17 31.17 +526 40 30 70 0 62.32 -3.58 28.33 +527 40 40 70 0 58.41 3.28 25.48 +528 40 55 70 0 52.40 14.45 21.22 +529 40 70 70 0 46.41 26.53 17.14 +530 40 85 70 0 40.89 38.51 13.44 +531 40 100 70 0 36.92 47.37 10.71 +532 55 0 70 0 67.60 -30.86 27.73 +533 55 10 70 0 64.09 -25.02 25.24 +534 55 20 70 0 60.47 -18.80 22.65 +535 55 30 70 0 56.83 -12.32 20.18 +536 55 40 70 0 53.21 -5.67 17.61 +537 55 55 70 0 47.69 5.15 13.72 +538 55 70 70 0 42.01 17.01 9.78 +539 55 85 70 0 36.68 28.82 6.07 +540 55 100 70 0 32.90 37.72 3.54 +541 70 0 70 0 61.29 -40.43 18.62 +542 70 10 70 0 58.04 -34.62 16.20 +543 70 20 70 0 54.66 -28.67 13.93 +544 70 30 70 0 51.30 -22.40 11.72 +545 70 40 70 0 48.01 -15.87 9.54 +546 70 55 70 0 42.93 -5.37 6.00 +547 70 70 70 0 37.56 6.18 2.28 +548 70 85 70 0 32.58 17.77 -1.13 +549 70 100 70 0 29.06 26.58 -3.37 +550 85 0 70 0 55.28 -51.54 9.65 +551 85 10 70 0 52.34 -46.03 7.48 +552 85 20 70 0 49.26 -40.18 5.39 +553 85 30 70 0 46.20 -33.94 3.49 +554 85 40 70 0 43.20 -27.44 1.61 +555 85 55 70 0 38.43 -17.14 -1.50 +556 85 70 70 0 33.50 -6.00 -4.84 +557 85 85 70 0 28.95 5.31 -7.80 +558 85 100 70 0 25.67 13.88 -9.72 +559 100 0 70 0 50.73 -61.02 2.60 +560 100 10 70 0 48.21 -55.39 0.72 +561 100 20 70 0 45.44 -49.63 -1.00 +562 100 30 70 0 42.62 -43.53 -2.73 +563 100 40 70 0 39.70 -37.18 -4.35 +564 100 55 70 0 35.23 -27.11 -7.09 +565 100 70 70 0 30.83 -16.11 -9.93 +566 100 85 70 0 26.73 -5.47 -12.46 +567 100 100 70 0 23.72 2.46 -14.35 +568 0 0 85 0 89.59 -4.30 78.11 +569 0 10 85 0 84.95 2.54 73.06 +570 0 20 85 0 80.31 9.68 68.63 +571 0 30 85 0 75.68 16.89 64.42 +572 0 40 85 0 71.16 24.60 60.45 +573 0 55 85 0 64.45 36.51 54.18 +574 0 70 85 0 57.96 49.04 48.36 +575 0 85 85 0 52.13 61.07 43.19 +576 0 100 85 0 47.99 69.68 39.86 +577 10 0 85 0 85.55 -9.23 71.49 +578 10 10 85 0 81.09 -2.42 66.99 +579 10 20 85 0 76.64 4.44 62.82 +580 10 30 85 0 72.24 11.56 58.76 +581 10 40 85 0 67.88 18.92 54.75 +582 10 55 85 0 61.33 30.85 48.95 +583 10 70 85 0 54.90 43.36 43.26 +584 10 85 85 0 49.13 55.47 38.08 +585 10 100 85 0 45.14 64.10 34.49 +586 20 0 85 0 81.36 -13.65 65.14 +587 20 10 85 0 77.09 -7.16 61.17 +588 20 20 85 0 72.84 -0.43 57.17 +589 20 30 85 0 68.64 6.47 53.13 +590 20 40 85 0 64.48 13.65 49.28 +591 20 55 85 0 58.18 25.27 43.67 +592 20 70 85 0 51.93 37.62 38.17 +593 20 85 85 0 46.26 49.68 33.02 +594 20 100 85 0 42.33 58.32 29.28 +595 30 0 85 0 77.18 -18.38 59.03 +596 30 10 85 0 73.12 -12.09 55.20 +597 30 20 85 0 69.08 -5.53 51.31 +598 30 30 85 0 65.10 1.21 47.44 +599 30 40 85 0 61.10 8.24 43.80 +600 30 55 85 0 55.02 19.58 38.24 +601 30 70 85 0 48.98 31.85 32.80 +602 30 85 85 0 43.45 43.87 27.73 +603 30 100 85 0 39.54 52.37 24.01 +604 40 0 85 0 73.06 -23.79 52.82 +605 40 10 85 0 69.17 -17.36 48.97 +606 40 20 85 0 65.31 -10.95 45.45 +607 40 30 85 0 61.54 -4.31 41.81 +608 40 40 85 0 57.71 2.53 38.22 +609 40 55 85 0 51.83 13.72 32.78 +610 40 70 85 0 45.95 25.74 27.38 +611 40 85 85 0 40.57 37.63 22.38 +612 40 100 85 0 36.75 46.47 18.73 +613 55 0 85 0 66.74 -32.47 42.68 +614 55 10 85 0 63.21 -26.14 39.43 +615 55 20 85 0 59.65 -19.87 36.28 +616 55 30 85 0 56.09 -13.45 33.04 +617 55 40 85 0 52.53 -6.79 29.71 +618 55 55 85 0 47.04 4.10 24.69 +619 55 70 85 0 41.46 16.00 19.59 +620 55 85 85 0 36.31 27.79 14.79 +621 55 100 85 0 32.71 36.31 11.24 +622 70 0 85 0 60.47 -42.45 32.73 +623 70 10 85 0 57.21 -36.32 29.79 +624 70 20 85 0 53.91 -30.40 26.81 +625 70 30 85 0 50.58 -24.08 23.94 +626 70 40 85 0 47.32 -17.50 21.06 +627 70 55 85 0 42.29 -6.82 16.47 +628 70 70 85 0 37.07 4.81 11.72 +629 70 85 85 0 32.23 16.31 7.26 +630 70 100 85 0 28.82 24.87 4.19 +631 85 0 85 0 54.46 -54.22 23.01 +632 85 10 85 0 51.57 -48.37 20.27 +633 85 20 85 0 48.53 -42.64 17.57 +634 85 30 85 0 45.48 -36.40 14.93 +635 85 40 85 0 42.49 -29.85 12.53 +636 85 55 85 0 37.83 -19.39 8.47 +637 85 70 85 0 33.00 -8.08 4.12 +638 85 85 85 0 28.57 3.18 0.18 +639 85 100 85 0 25.43 11.63 -2.39 +640 100 0 85 0 49.96 -64.51 15.36 +641 100 10 85 0 47.41 -58.78 12.75 +642 100 20 85 0 44.65 -52.99 10.45 +643 100 30 85 0 41.89 -46.75 8.26 +644 100 40 85 0 39.07 -40.33 6.10 +645 100 55 85 0 34.71 -30.16 2.55 +646 100 70 85 0 30.39 -18.98 -1.03 +647 100 85 85 0 26.30 -8.17 -4.54 +648 100 100 85 0 23.41 -0.06 -6.91 +649 0 0 100 0 88.94 -4.04 92.37 +650 0 10 100 0 84.35 2.93 87.22 +651 0 20 100 0 79.78 9.93 81.60 +652 0 30 100 0 75.21 17.28 76.85 +653 0 40 100 0 70.62 24.83 71.77 +654 0 55 100 0 63.88 36.93 64.40 +655 0 70 100 0 57.59 49.26 57.55 +656 0 85 100 0 52.01 61.00 50.67 +657 0 100 100 0 47.99 69.33 45.87 +658 10 0 100 0 84.88 -9.03 85.57 +659 10 10 100 0 80.46 -2.31 80.34 +660 10 20 100 0 76.04 4.64 75.42 +661 10 30 100 0 71.67 11.72 70.79 +662 10 40 100 0 67.35 19.15 65.96 +663 10 55 100 0 60.90 30.93 59.02 +664 10 70 100 0 54.64 43.31 51.96 +665 10 85 100 0 48.99 55.24 45.19 +666 10 100 100 0 45.04 63.72 40.42 +667 20 0 100 0 80.77 -13.83 78.87 +668 20 10 100 0 76.46 -7.14 74.05 +669 20 20 100 0 72.22 -0.38 69.36 +670 20 30 100 0 68.04 6.52 64.80 +671 20 40 100 0 63.93 13.74 60.16 +672 20 55 100 0 57.77 25.26 53.24 +673 20 70 100 0 51.60 37.64 46.37 +674 20 85 100 0 46.02 49.50 39.93 +675 20 100 100 0 42.23 57.82 34.97 +676 30 0 100 0 76.59 -18.60 71.99 +677 30 10 100 0 72.50 -12.16 67.57 +678 30 20 100 0 68.46 -5.64 63.14 +679 30 30 100 0 64.48 1.16 58.73 +680 30 40 100 0 60.55 8.16 54.27 +681 30 55 100 0 54.62 19.50 47.44 +682 30 70 100 0 48.58 31.69 40.86 +683 30 85 100 0 43.13 43.66 34.41 +684 30 100 100 0 39.46 52.01 29.54 +685 40 0 100 0 72.38 -23.80 65.39 +686 40 10 100 0 68.53 -17.53 60.92 +687 40 20 100 0 64.71 -11.10 56.67 +688 40 30 100 0 60.89 -4.52 52.46 +689 40 40 100 0 57.14 2.33 48.24 +690 40 55 100 0 51.41 13.38 41.88 +691 40 70 100 0 45.56 25.66 35.24 +692 40 85 100 0 40.29 37.45 29.13 +693 40 100 100 0 36.70 45.88 24.52 +694 55 0 100 0 65.91 -32.53 54.58 +695 55 10 100 0 62.59 -26.47 50.75 +696 55 20 100 0 59.11 -20.23 46.81 +697 55 30 100 0 55.54 -13.83 42.95 +698 55 40 100 0 52.01 -7.26 39.19 +699 55 55 100 0 46.59 3.64 32.94 +700 55 70 100 0 41.08 15.58 26.86 +701 55 85 100 0 36.08 27.28 21.06 +702 55 100 100 0 32.70 35.56 16.76 +703 70 0 100 0 59.63 -42.60 43.88 +704 70 10 100 0 56.60 -36.95 40.31 +705 70 20 100 0 53.43 -30.88 36.45 +706 70 30 100 0 50.19 -24.60 33.23 +707 70 40 100 0 46.91 -18.05 29.57 +708 70 55 100 0 41.84 -7.51 24.01 +709 70 70 100 0 36.68 4.08 18.30 +710 70 85 100 0 31.95 15.53 13.05 +711 70 100 100 0 28.80 23.72 9.51 +712 85 0 100 0 53.87 -54.67 33.22 +713 85 10 100 0 51.03 -49.29 29.89 +714 85 20 100 0 48.04 -43.53 26.60 +715 85 30 100 0 45.06 -37.12 23.67 +716 85 40 100 0 42.07 -30.62 20.53 +717 85 55 100 0 37.41 -20.56 15.59 +718 85 70 100 0 32.65 -9.17 10.53 +719 85 85 100 0 28.24 2.04 5.75 +720 85 100 100 0 25.19 10.15 2.41 +721 100 0 100 0 49.45 -65.93 24.34 +722 100 10 100 0 46.96 -60.39 21.27 +723 100 20 100 0 44.05 -54.48 18.55 +724 100 30 100 0 41.15 -48.29 15.72 +725 100 40 100 0 38.48 -41.98 13.33 +726 100 55 100 0 34.36 -31.57 9.17 +727 100 70 100 0 30.07 -20.37 4.97 +728 100 85 100 0 26.03 -9.33 0.89 +729 100 100 100 0 23.26 -1.43 -1.68 +730 0 0 0 20 82.71 0.94 -5.62 +731 0 10 0 20 78.45 6.47 -6.68 +732 0 20 0 20 74.25 12.01 -7.43 +733 0 40 0 20 65.83 23.80 -8.37 +734 0 70 0 20 52.56 45.08 -8.58 +735 0 100 0 20 41.55 65.30 -5.71 +736 10 0 0 20 79.36 -2.33 -9.67 +737 10 10 0 20 75.31 3.17 -10.70 +738 10 20 0 20 71.30 8.58 -11.24 +739 10 40 0 20 63.19 20.12 -11.99 +740 10 70 0 20 50.27 40.99 -12.23 +741 10 100 0 20 39.26 61.11 -9.78 +742 20 0 0 20 75.95 -5.23 -13.49 +743 20 10 0 20 72.11 0.09 -14.35 +744 20 20 0 20 68.25 5.43 -14.78 +745 20 40 0 20 60.40 16.65 -15.36 +746 20 70 0 20 47.87 36.80 -15.52 +747 20 100 0 20 37.04 57.03 -13.72 +748 40 0 0 20 69.10 -11.23 -21.56 +749 40 10 0 20 65.58 -6.21 -22.07 +750 40 20 0 20 62.05 -1.20 -22.23 +751 40 40 0 20 54.78 9.46 -22.46 +752 40 70 0 20 43.04 28.63 -22.45 +753 40 100 0 20 32.63 47.99 -21.35 +754 70 0 0 20 58.12 -21.50 -34.42 +755 70 10 0 20 55.16 -16.81 -34.55 +756 70 20 0 20 52.10 -12.14 -34.34 +757 70 40 0 20 45.77 -2.39 -34.02 +758 70 70 0 20 35.49 15.40 -33.51 +759 70 100 0 20 26.51 32.84 -32.87 +760 100 0 0 20 48.98 -31.63 -45.54 +761 100 10 0 20 46.34 -27.12 -45.42 +762 100 20 0 20 43.61 -22.59 -44.94 +763 100 40 0 20 38.05 -13.31 -44.04 +764 100 70 0 20 29.66 2.59 -42.50 +765 100 100 0 20 22.32 17.88 -41.00 +766 0 0 10 20 82.08 -0.43 2.12 +767 0 10 10 20 77.87 5.25 0.62 +768 0 20 10 20 73.70 10.89 -0.32 +769 0 40 10 20 65.36 22.88 -2.09 +770 0 70 10 20 52.24 44.24 -3.18 +771 0 100 10 20 41.50 64.41 -1.47 +772 10 0 10 20 78.75 -3.78 -2.02 +773 10 10 10 20 74.75 1.74 -3.29 +774 10 20 10 20 70.75 7.32 -4.27 +775 10 40 10 20 62.70 19.02 -5.73 +776 10 70 10 20 49.95 40.01 -6.79 +777 10 100 10 20 39.21 60.16 -5.49 +778 20 0 10 20 75.33 -6.75 -5.99 +779 20 10 10 20 71.53 -1.40 -7.15 +780 20 20 10 20 67.69 3.99 -7.90 +781 20 40 10 20 59.92 15.38 -9.14 +782 20 70 10 20 47.54 35.82 -10.26 +783 20 100 10 20 36.98 55.83 -9.42 +784 40 0 10 20 68.40 -13.14 -14.26 +785 40 10 10 20 64.96 -8.07 -15.10 +786 40 20 10 20 61.47 -2.98 -15.54 +787 40 40 10 20 54.32 7.85 -16.39 +788 40 70 10 20 42.71 27.36 -17.38 +789 40 100 10 20 32.59 46.75 -17.33 +790 70 0 10 20 57.44 -24.20 -27.58 +791 70 10 10 20 54.53 -19.46 -27.93 +792 70 20 10 20 51.55 -14.66 -28.01 +793 70 40 10 20 45.33 -4.69 -28.22 +794 70 70 10 20 35.23 13.33 -28.64 +795 70 100 10 20 26.30 31.00 -28.75 +796 100 0 10 20 48.23 -35.34 -39.06 +797 100 10 10 20 45.63 -30.85 -39.21 +798 100 20 10 20 43.02 -26.27 -38.96 +799 100 40 10 20 37.66 -16.66 -38.52 +800 100 70 10 20 29.27 -0.20 -37.91 +801 100 100 10 20 22.22 15.10 -37.07 +802 0 0 20 20 81.45 -1.38 9.64 +803 0 10 20 20 77.25 4.34 7.86 +804 0 20 20 20 73.12 10.06 6.49 +805 0 40 20 20 64.84 22.12 4.16 +806 0 70 20 20 51.91 43.69 2.07 +807 0 100 20 20 41.41 63.64 2.97 +808 10 0 20 20 78.11 -4.87 5.45 +809 10 10 20 20 74.12 0.73 3.79 +810 10 20 20 20 70.15 6.30 2.57 +811 10 40 20 20 62.16 18.17 0.46 +812 10 70 20 20 49.61 39.24 -1.60 +813 10 100 20 20 39.15 59.40 -1.24 +814 20 0 20 20 74.68 -8.04 1.44 +815 20 10 20 20 70.90 -2.56 -0.16 +816 20 20 20 20 67.10 2.82 -1.15 +817 20 40 20 20 59.38 14.41 -3.05 +818 20 70 20 20 47.21 35.03 -5.08 +819 20 100 20 20 36.90 54.86 -5.04 +820 40 0 20 20 67.71 -14.77 -7.13 +821 40 10 20 20 64.30 -9.60 -8.30 +822 40 20 20 20 60.84 -4.43 -9.06 +823 40 40 20 20 53.77 6.59 -10.44 +824 40 70 20 20 42.34 26.28 -12.30 +825 40 100 20 20 32.49 45.57 -12.97 +826 70 0 20 20 56.75 -26.54 -20.75 +827 70 10 20 20 53.86 -21.79 -21.34 +828 70 20 20 20 50.93 -16.89 -21.75 +829 70 40 20 20 44.78 -6.62 -22.48 +830 70 70 20 20 34.86 11.61 -23.78 +831 70 100 20 20 26.20 29.16 -24.51 +832 100 0 20 20 47.59 -38.93 -32.48 +833 100 10 20 20 45.04 -34.21 -32.90 +834 100 20 20 20 42.44 -29.59 -32.99 +835 100 40 20 20 37.19 -19.80 -33.02 +836 100 70 20 20 28.88 -2.84 -33.18 +837 100 100 20 20 22.16 12.41 -33.00 +838 0 0 40 20 80.14 -3.01 25.29 +839 0 10 40 20 76.01 2.86 22.83 +840 0 20 40 20 71.91 8.72 20.88 +841 0 40 40 20 63.81 21.02 17.21 +842 0 70 40 20 51.28 42.65 13.10 +843 0 100 40 20 41.30 61.99 12.09 +844 10 0 40 20 76.77 -6.66 20.81 +845 10 10 40 20 72.86 -0.97 18.54 +846 10 20 40 20 68.95 4.71 16.71 +847 10 40 40 20 61.17 16.76 13.44 +848 10 70 40 20 49.02 38.03 9.25 +849 10 100 40 20 39.06 57.64 7.80 +850 20 0 40 20 73.30 -10.02 16.38 +851 20 10 40 20 69.58 -4.54 14.35 +852 20 20 40 20 65.88 0.98 12.67 +853 20 40 40 20 58.41 12.76 9.72 +854 20 70 40 20 46.62 33.55 5.61 +855 20 100 40 20 36.79 53.11 3.81 +856 40 0 40 20 66.37 -17.46 7.35 +857 40 10 40 20 62.99 -12.21 5.73 +858 40 20 40 20 59.61 -6.95 4.41 +859 40 40 40 20 52.68 4.36 1.85 +860 40 70 40 20 41.62 24.36 -1.85 +861 40 100 40 20 32.33 43.36 -4.12 +862 70 0 40 20 55.45 -30.66 -6.92 +863 70 10 40 20 52.60 -25.78 -7.99 +864 70 20 40 20 49.69 -20.75 -8.84 +865 70 40 40 20 43.73 -10.19 -10.64 +866 70 70 40 20 34.11 8.50 -13.67 +867 70 100 40 20 25.99 26.13 -15.97 +868 100 0 40 20 46.29 -45.35 -19.06 +869 100 10 40 20 43.77 -40.52 -20.15 +870 100 20 40 20 41.27 -35.59 -20.78 +871 100 40 40 20 36.13 -25.27 -21.82 +872 100 70 40 20 28.13 -7.69 -23.54 +873 100 100 40 20 21.98 7.77 -24.64 +874 0 0 70 20 78.33 -4.36 52.11 +875 0 10 70 20 74.31 1.50 48.49 +876 0 20 70 20 70.31 7.50 45.34 +877 0 40 70 20 62.38 20.05 39.65 +878 0 70 70 20 50.42 41.66 31.53 +879 0 100 70 20 41.27 60.30 26.02 +880 10 0 70 20 74.92 -8.37 46.88 +881 10 10 70 20 71.08 -2.62 43.77 +882 10 20 70 20 67.27 3.20 40.93 +883 10 40 70 20 59.70 15.50 35.44 +884 10 70 70 20 48.08 36.88 27.54 +885 10 100 70 20 38.99 55.74 21.69 +886 20 0 70 20 71.38 -12.08 42.09 +887 20 10 70 20 67.75 -6.50 39.17 +888 20 20 70 20 64.15 -0.83 36.48 +889 20 40 70 20 56.91 11.18 31.35 +890 20 70 70 20 45.67 32.09 23.49 +891 20 100 70 20 36.72 50.81 17.58 +892 40 0 70 20 64.39 -20.27 32.26 +893 40 10 70 20 61.14 -14.96 29.58 +894 40 20 70 20 57.87 -9.56 27.24 +895 40 40 70 20 51.18 2.00 22.70 +896 40 70 70 20 40.75 22.13 15.28 +897 40 100 70 20 32.17 40.58 9.35 +898 70 0 70 20 53.50 -35.51 16.03 +899 70 10 70 20 50.76 -30.50 14.14 +900 70 20 70 20 47.97 -25.36 12.38 +901 70 40 70 20 42.28 -14.37 8.75 +902 70 70 70 20 33.17 4.78 2.36 +903 70 100 70 20 25.77 22.27 -2.65 +904 100 0 70 20 44.46 -53.40 1.85 +905 100 10 70 20 42.18 -48.36 0.30 +906 100 20 70 20 39.74 -43.26 -1.04 +907 100 40 70 20 34.83 -32.31 -3.86 +908 100 70 70 20 27.27 -13.76 -8.52 +909 100 100 70 20 21.35 1.97 -11.63 +910 0 0 100 20 76.87 -4.54 79.60 +911 0 10 100 20 72.83 1.43 74.97 +912 0 20 100 20 68.92 7.44 70.62 +913 0 40 100 20 61.20 20.10 61.93 +914 0 70 100 20 49.71 41.31 48.84 +915 0 100 100 20 41.18 59.22 38.07 +916 10 0 100 20 73.45 -8.73 74.00 +917 10 10 100 20 69.65 -2.93 69.64 +918 10 20 100 20 65.91 2.91 65.50 +919 10 40 100 20 58.54 15.23 57.36 +920 10 70 100 20 47.42 36.32 44.40 +921 10 100 100 20 38.84 54.38 33.77 +922 20 0 100 20 69.96 -12.68 68.26 +923 20 10 100 20 66.33 -7.02 64.24 +924 20 20 100 20 62.79 -1.30 60.34 +925 20 40 100 20 55.81 10.68 52.70 +926 20 70 100 20 45.00 31.40 40.12 +927 20 100 100 20 36.57 49.59 29.43 +928 40 0 100 20 62.91 -21.30 56.40 +929 40 10 100 20 59.71 -15.94 52.97 +930 40 20 100 20 56.52 -10.45 49.55 +931 40 40 100 20 50.09 0.97 42.51 +932 40 70 100 20 40.01 21.17 30.74 +933 40 100 100 20 32.07 39.11 20.63 +934 70 0 100 20 51.96 -37.71 37.64 +935 70 10 100 20 49.37 -32.65 34.74 +936 70 20 100 20 46.70 -27.43 31.79 +937 70 40 100 20 41.15 -16.27 25.96 +938 70 70 100 20 32.42 2.80 16.16 +939 70 100 100 20 25.44 19.59 8.23 +940 100 0 100 20 43.29 -57.56 20.62 +941 100 10 100 20 40.94 -52.67 18.23 +942 100 20 100 20 38.56 -47.34 15.65 +943 100 40 100 20 33.86 -36.19 11.18 +944 100 70 100 20 26.63 -17.39 4.15 +945 100 100 100 20 20.99 -1.62 -0.77 +946 0 0 0 40 69.76 0.49 -4.90 +947 0 20 0 40 62.52 9.75 -6.42 +948 0 40 0 40 55.49 19.69 -7.37 +949 0 70 0 40 44.14 37.55 -7.50 +950 0 100 0 40 34.72 54.79 -5.39 +951 20 0 0 40 63.98 -4.58 -11.33 +952 20 20 0 40 57.76 4.18 -12.29 +953 20 40 0 40 51.20 13.57 -12.79 +954 20 70 0 40 40.49 30.70 -12.92 +955 20 100 0 40 31.10 47.69 -11.55 +956 40 0 0 40 58.32 -9.67 -17.98 +957 40 20 0 40 52.62 -1.32 -18.41 +958 40 40 0 40 46.55 7.66 -18.54 +959 40 70 0 40 36.62 23.92 -18.55 +960 40 100 0 40 27.63 40.22 -17.89 +961 70 0 0 40 49.03 -18.54 -28.83 +962 70 20 0 40 44.15 -10.67 -28.60 +963 70 40 0 40 38.98 -2.29 -28.34 +964 70 70 0 40 30.42 12.73 -27.73 +965 70 100 0 40 22.75 27.22 -27.19 +966 100 0 0 40 41.19 -27.41 -38.38 +967 100 20 0 40 36.82 -19.61 -37.84 +968 100 40 0 40 32.22 -11.48 -37.07 +969 100 70 0 40 25.31 2.23 -35.53 +970 100 100 0 40 19.62 14.55 -33.73 +971 0 0 20 40 68.48 -1.48 7.70 +972 0 20 20 40 61.60 7.93 5.17 +973 0 40 20 40 54.61 18.06 3.27 +974 0 70 20 40 43.64 36.12 1.49 +975 0 100 20 40 34.63 53.16 2.14 +976 20 0 20 40 62.92 -7.02 0.95 +977 20 20 20 40 56.68 2.01 -1.02 +978 20 40 20 40 50.25 11.62 -2.51 +979 20 70 20 40 39.95 28.97 -4.21 +980 20 100 20 40 31.08 45.77 -4.40 +981 40 0 20 40 57.13 -12.61 -6.09 +982 40 20 20 40 51.60 -4.11 -7.49 +983 40 40 20 40 45.74 5.11 -8.49 +984 40 70 20 40 36.05 21.59 -10.01 +985 40 100 20 40 27.54 37.87 -10.67 +986 70 0 20 40 47.88 -22.76 -17.42 +987 70 20 20 40 43.15 -14.56 -18.18 +988 70 40 20 40 38.11 -5.86 -18.70 +989 70 70 20 40 29.84 9.42 -19.58 +990 70 100 20 40 22.58 23.94 -20.09 +991 100 0 20 40 40.09 -33.23 -27.46 +992 100 20 20 40 35.84 -25.12 -27.85 +993 100 40 20 40 31.60 -16.66 -27.78 +994 100 70 20 40 24.95 -2.44 -27.50 +995 100 100 20 40 19.60 9.81 -26.69 +996 0 0 40 40 67.34 -2.97 20.70 +997 0 20 40 40 60.49 6.72 17.16 +998 0 40 40 40 53.65 17.00 14.18 +999 0 70 40 40 43.08 35.13 10.76 +1000 0 100 40 40 34.42 51.63 9.58 +1001 20 0 40 40 61.72 -8.83 13.51 +1002 20 20 40 40 55.59 0.33 10.60 +1003 20 40 40 40 49.39 10.16 8.24 +1004 20 70 40 40 39.43 27.57 4.85 +1005 20 100 40 40 30.97 44.02 3.01 +1006 40 0 40 40 55.94 -14.96 6.09 +1007 40 20 40 40 50.51 -6.27 3.84 +1008 40 40 40 40 44.79 3.13 1.87 +1009 40 70 40 40 35.43 19.91 -1.18 +1010 40 100 40 40 27.45 35.74 -3.21 +1011 70 0 40 40 46.81 -26.12 -5.92 +1012 70 20 40 40 42.13 -17.78 -7.34 +1013 70 40 40 40 37.20 -8.87 -8.67 +1014 70 70 40 40 29.18 6.90 -10.97 +1015 70 100 40 40 22.53 21.10 -12.82 +1016 100 0 40 40 39.03 -38.48 -16.29 +1017 100 20 40 40 34.93 -30.04 -17.54 +1018 100 40 40 40 30.74 -21.21 -18.24 +1019 100 70 40 40 24.32 -6.31 -19.35 +1020 100 100 40 40 19.38 6.17 -19.49 +1021 0 0 70 40 65.58 -4.34 43.22 +1022 0 20 70 40 59.01 5.50 37.69 +1023 0 40 70 40 52.35 15.95 33.01 +1024 0 70 70 40 42.19 34.08 26.08 +1025 0 100 70 40 34.49 49.62 21.24 +1026 20 0 70 40 59.97 -10.70 35.00 +1027 20 20 70 40 54.07 -1.36 30.56 +1028 20 40 70 40 48.05 8.63 26.41 +1029 20 70 70 40 38.58 26.14 19.73 +1030 20 100 70 40 30.92 41.83 14.44 +1031 40 0 70 40 54.25 -17.46 26.83 +1032 40 20 70 40 48.93 -8.59 23.01 +1033 40 40 70 40 43.38 0.94 19.38 +1034 40 70 70 40 34.64 17.81 13.15 +1035 40 100 70 40 27.34 33.21 7.92 +1036 70 0 70 40 45.12 -30.22 13.41 +1037 70 20 70 40 40.64 -21.71 10.48 +1038 70 40 70 40 35.97 -12.44 7.61 +1039 70 70 70 40 28.46 3.51 2.52 +1040 70 100 70 40 22.34 17.67 -1.78 +1041 100 0 70 40 37.66 -44.89 1.47 +1042 100 20 70 40 33.71 -36.24 -1.01 +1043 100 40 70 40 29.67 -26.80 -3.12 +1044 100 70 70 40 23.55 -11.20 -6.77 +1045 100 100 70 40 18.98 1.43 -8.62 +1046 0 0 100 40 64.34 -4.61 66.28 +1047 0 20 100 40 57.63 5.32 58.83 +1048 0 40 100 40 51.26 15.71 51.46 +1049 0 70 100 40 41.55 33.60 39.83 +1050 0 100 100 40 34.41 48.54 30.21 +1051 20 0 100 40 58.63 -11.29 56.88 +1052 20 20 100 40 52.81 -1.95 50.58 +1053 20 40 100 40 47.05 8.03 44.11 +1054 20 70 100 40 37.96 25.36 33.13 +1055 20 100 100 40 30.81 40.60 23.75 +1056 40 0 100 40 52.92 -18.48 47.26 +1057 40 20 100 40 47.71 -9.52 41.60 +1058 40 40 100 40 42.45 0.10 35.78 +1059 40 70 100 40 33.93 16.86 25.64 +1060 40 100 100 40 27.31 31.57 16.97 +1061 70 0 100 40 43.72 -32.23 31.03 +1062 70 20 100 40 39.54 -23.58 26.64 +1063 70 40 100 40 35.03 -14.28 21.85 +1064 70 70 100 40 27.87 1.79 13.74 +1065 70 100 100 40 22.08 15.59 7.09 +1066 100 0 100 40 36.61 -48.49 16.76 +1067 100 20 100 40 32.70 -39.49 12.87 +1068 100 40 100 40 28.94 -29.96 8.97 +1069 100 70 100 40 23.06 -14.02 3.66 +1070 100 100 100 40 18.84 -1.48 0.17 +1071 0 0 0 60 55.11 0.16 -3.90 +1072 0 20 0 60 49.23 7.50 -5.02 +1073 0 40 0 60 43.70 15.24 -5.67 +1074 0 70 0 60 34.64 29.50 -5.70 +1075 0 100 0 60 27.25 42.69 -3.97 +1076 20 0 0 60 50.37 -3.85 -8.86 +1077 20 20 0 60 45.68 3.01 -9.52 +1078 20 40 0 60 40.52 10.45 -9.77 +1079 20 70 0 60 31.99 24.00 -9.64 +1080 20 100 0 60 24.71 36.96 -8.33 +1081 40 0 0 60 45.88 -7.92 -14.06 +1082 40 20 0 60 41.69 -1.34 -14.21 +1083 40 40 0 60 37.05 5.92 -14.19 +1084 40 70 0 60 29.25 18.74 -13.96 +1085 40 100 0 60 22.30 31.03 -13.17 +1086 70 0 0 60 38.53 -15.13 -22.51 +1087 70 20 0 60 34.83 -8.72 -22.31 +1088 70 40 0 60 31.15 -1.90 -21.87 +1089 70 70 0 60 24.56 9.92 -21.11 +1090 70 100 0 60 18.99 20.53 -20.02 +1091 100 0 0 60 32.32 -22.10 -30.18 +1092 100 20 0 60 29.16 -15.54 -29.66 +1093 100 40 0 60 25.87 -8.89 -28.81 +1094 100 70 0 60 20.64 2.09 -26.98 +1095 100 100 0 60 16.87 10.72 -24.84 +1096 0 0 20 60 53.73 -1.52 5.86 +1097 0 20 20 60 48.47 6.03 3.92 +1098 0 40 20 60 42.94 14.05 2.55 +1099 0 70 20 60 34.35 28.20 1.31 +1100 0 100 20 60 27.39 41.04 1.93 +1101 20 0 20 60 49.43 -5.78 0.64 +1102 20 20 20 60 44.77 1.35 -0.70 +1103 20 40 20 60 39.78 8.90 -1.76 +1104 20 70 20 60 31.68 22.45 -2.88 +1105 20 100 20 60 24.82 35.20 -2.86 +1106 40 0 20 60 44.94 -10.16 -4.74 +1107 40 20 20 60 40.87 -3.51 -5.71 +1108 40 40 20 60 36.39 3.73 -6.30 +1109 40 70 20 60 28.83 16.68 -7.24 +1110 40 100 20 60 22.27 28.94 -7.50 +1111 70 0 20 60 37.72 -18.19 -13.72 +1112 70 20 20 60 34.14 -11.65 -14.11 +1113 70 40 20 60 30.36 -4.71 -14.34 +1114 70 70 20 60 24.09 7.36 -14.52 +1115 70 100 20 60 18.86 17.97 -14.34 +1116 100 0 20 60 31.60 -26.33 -21.61 +1117 100 20 20 60 28.46 -19.57 -21.70 +1118 100 40 20 60 25.25 -12.54 -21.49 +1119 100 70 20 60 20.49 -1.37 -20.68 +1120 100 100 20 60 16.88 7.38 -19.20 +1121 0 0 40 60 52.68 -2.67 15.85 +1122 0 20 40 60 47.36 4.88 13.13 +1123 0 40 40 60 42.12 12.95 11.02 +1124 0 70 40 60 33.95 27.10 8.41 +1125 0 100 40 60 27.18 39.42 7.54 +1126 20 0 40 60 48.50 -7.28 10.40 +1127 20 20 40 60 43.81 -0.10 8.37 +1128 20 40 40 60 39.03 7.63 6.71 +1129 20 70 40 60 31.26 21.24 4.17 +1130 20 100 40 60 24.70 33.40 2.83 +1131 40 0 40 60 44.02 -12.08 4.67 +1132 40 20 40 60 39.95 -5.27 3.17 +1133 40 40 40 60 35.64 2.13 1.88 +1134 40 70 40 60 28.35 15.13 -0.31 +1135 40 100 40 60 22.18 26.92 -1.83 +1136 70 0 40 60 36.90 -20.87 -4.66 +1137 70 20 40 60 33.37 -14.28 -5.60 +1138 70 40 40 60 29.67 -6.99 -6.41 +1139 70 70 40 60 23.62 5.21 -7.78 +1140 70 100 40 60 18.91 15.47 -8.68 +1141 100 0 40 60 30.78 -30.24 -12.90 +1142 100 20 40 60 27.78 -23.12 -13.56 +1143 100 40 40 60 24.77 -15.96 -13.91 +1144 100 70 40 60 20.15 -4.47 -14.11 +1145 100 100 40 60 16.68 4.82 -13.41 +1146 0 0 70 60 51.15 -4.04 33.32 +1147 0 20 70 60 46.21 3.70 29.16 +1148 0 40 70 60 41.10 11.85 25.54 +1149 0 70 70 60 33.12 25.82 20.00 +1150 0 100 70 60 27.29 37.43 16.11 +1151 20 0 70 60 46.98 -8.95 27.14 +1152 20 20 70 60 42.58 -1.61 23.88 +1153 20 40 70 60 37.93 6.17 20.61 +1154 20 70 70 60 30.59 19.79 15.51 +1155 20 100 70 60 24.72 31.23 11.25 +1156 40 0 70 60 42.69 -14.23 20.77 +1157 40 20 70 60 38.67 -7.26 18.07 +1158 40 40 70 60 34.49 0.25 15.33 +1159 40 70 70 60 27.76 13.33 10.62 +1160 40 100 70 60 22.27 24.45 6.60 +1161 70 0 70 60 35.60 -24.15 10.44 +1162 70 20 70 60 32.21 -17.35 8.27 +1163 70 40 70 60 28.76 -9.97 6.18 +1164 70 70 70 60 23.18 2.47 2.77 +1165 70 100 70 60 18.79 12.57 -0.31 +1166 100 0 70 60 29.84 -34.93 1.13 +1167 100 20 70 60 26.91 -27.69 -0.65 +1168 100 40 70 60 23.97 -20.18 -2.17 +1169 100 70 70 60 19.64 -8.07 -4.26 +1170 100 100 70 60 16.55 1.20 -5.07 +1171 0 0 100 60 50.25 -4.33 50.82 +1172 0 20 100 60 45.01 3.42 44.96 +1173 0 40 100 60 40.03 11.41 39.03 +1174 0 70 100 60 32.56 25.13 29.69 +1175 0 100 100 60 27.15 36.15 22.32 +1176 20 0 100 60 45.86 -9.57 43.71 +1177 20 20 100 60 41.49 -2.22 38.85 +1178 20 40 100 60 37.06 5.50 33.68 +1179 20 70 100 60 30.07 18.85 25.03 +1180 20 100 100 60 24.72 30.00 17.63 +1181 40 0 100 60 41.53 -15.21 36.44 +1182 40 20 100 60 37.56 -8.14 31.96 +1183 40 40 100 60 33.65 -0.54 27.58 +1184 40 70 100 60 27.21 12.41 19.43 +1185 40 100 100 60 22.13 22.96 12.95 +1186 70 0 100 60 34.38 -25.71 23.46 +1187 70 20 100 60 31.39 -18.85 20.31 +1188 70 40 100 60 28.15 -11.44 16.90 +1189 70 70 100 60 22.81 0.83 10.97 +1190 70 100 100 60 18.77 10.78 6.27 +1191 100 0 100 60 29.06 -37.41 12.37 +1192 100 20 100 60 26.18 -29.92 9.60 +1193 100 40 100 60 23.44 -22.34 6.91 +1194 100 70 100 60 19.37 -10.23 3.34 +1195 100 100 100 60 16.60 -1.05 1.33 +1196 0 0 0 80 37.53 -0.06 -2.55 +1197 0 40 0 80 29.92 10.36 -3.35 +1198 0 70 0 80 24.18 19.69 -2.63 +1199 0 100 0 80 19.71 27.26 -0.61 +1200 40 0 0 80 31.21 -5.53 -9.39 +1201 40 40 0 80 25.70 3.89 -8.72 +1202 40 70 0 80 20.81 12.60 -7.88 +1203 40 100 0 80 16.94 19.73 -6.36 +1204 70 0 0 80 26.43 -10.25 -15.17 +1205 70 40 0 80 21.93 -0.93 -13.86 +1206 70 70 0 80 18.12 7.02 -12.31 +1207 70 100 0 80 15.10 13.10 -10.62 +1208 100 0 0 80 22.35 -14.40 -20.14 +1209 100 40 0 80 18.57 -4.80 -18.53 +1210 100 70 0 80 15.78 2.53 -16.01 +1211 100 100 0 80 14.02 7.64 -13.62 +1212 0 0 40 80 35.69 -2.21 10.26 +1213 0 40 40 80 28.86 8.37 7.46 +1214 0 70 40 80 23.82 17.54 6.14 +1215 0 100 40 80 19.89 24.54 5.88 +1216 40 0 40 80 30.03 -8.47 2.93 +1217 40 40 40 80 24.87 1.18 1.98 +1218 40 70 40 80 20.40 9.52 0.93 +1219 40 100 40 80 17.01 16.13 0.53 +1220 70 0 40 80 25.39 -14.08 -3.15 +1221 70 40 40 80 21.09 -4.40 -3.40 +1222 70 70 40 80 17.71 3.56 -3.40 +1223 70 100 40 80 15.25 9.27 -3.33 +1224 100 0 40 80 21.63 -19.32 -8.44 +1225 100 40 40 80 18.18 -9.24 -8.20 +1226 100 70 40 80 15.76 -1.62 -7.35 +1227 100 100 40 80 14.15 3.69 -6.09 +1228 0 0 70 80 34.66 -3.35 21.33 +1229 0 40 70 80 28.30 7.22 16.41 +1230 0 70 70 80 23.37 16.02 12.92 +1231 0 100 70 80 20.10 22.62 10.78 +1232 40 0 70 80 29.20 -10.17 13.43 +1233 40 40 70 80 24.18 -0.45 10.29 +1234 40 70 70 80 20.17 7.85 7.65 +1235 40 100 70 80 17.21 14.02 5.52 +1236 70 0 70 80 24.64 -16.37 6.71 +1237 70 40 70 80 20.69 -6.51 4.67 +1238 70 70 70 80 17.54 1.42 2.92 +1239 70 100 70 80 15.35 7.13 1.69 +1240 100 0 70 80 21.23 -22.25 0.82 +1241 100 40 70 80 17.92 -11.69 -0.54 +1242 100 70 70 80 15.68 -4.13 -1.03 +1243 100 100 70 80 14.29 1.16 -0.78 +1244 0 0 100 80 34.00 -3.83 31.57 +1245 0 40 100 80 27.55 6.53 23.99 +1246 0 70 100 80 23.10 15.17 18.22 +1247 0 100 100 80 20.01 21.33 14.10 +1248 40 0 100 80 28.36 -10.98 22.26 +1249 40 40 100 80 23.69 -1.21 17.17 +1250 40 70 100 80 19.95 6.78 12.47 +1251 40 100 100 80 17.19 12.64 9.00 +1252 70 0 100 80 23.93 -17.55 14.31 +1253 70 40 100 80 20.38 -7.77 10.86 +1254 70 70 100 80 17.44 -0.03 7.75 +1255 70 100 100 80 15.48 5.45 5.62 +1256 100 0 100 80 20.74 -23.54 7.57 +1257 100 40 100 80 17.65 -13.21 4.98 +1258 100 70 100 80 15.64 -5.73 3.47 +1259 100 100 100 80 14.42 -0.52 2.89 +1260 0 0 0 100 16.00 0.07 -0.33 +1261 0 40 0 100 14.59 3.91 1.23 +1262 0 100 0 100 13.30 8.89 4.27 +1263 40 0 0 100 14.54 -1.51 -2.60 +1264 40 40 0 100 13.68 2.52 -0.92 +1265 40 100 0 100 12.53 7.53 2.57 +1266 100 0 0 100 12.18 -3.46 -6.20 +1267 100 40 0 100 12.05 0.86 -4.11 +1268 100 100 0 100 11.43 5.76 0.01 +1269 0 0 40 100 15.58 -1.33 2.32 +1270 0 40 40 100 14.55 2.15 3.20 +1271 0 100 40 100 13.65 6.43 5.33 +1272 40 0 40 100 14.44 -3.26 0.64 +1273 40 40 40 100 13.71 0.53 1.73 +1274 40 100 40 100 12.97 5.05 3.95 +1275 100 0 40 100 12.48 -5.55 -2.32 +1276 100 40 40 100 12.36 -1.39 -0.48 +1277 100 100 40 100 12.10 3.27 2.10 +1278 0 0 100 100 15.37 -3.20 6.36 +1279 0 40 100 100 14.60 -0.40 6.20 +1280 0 100 100 100 14.07 3.45 7.04 +1281 40 0 100 100 14.40 -5.36 4.99 +1282 40 40 100 100 13.92 -2.03 5.32 +1283 40 100 100 100 13.45 1.98 6.07 +1284 100 0 100 100 12.95 -8.05 3.02 +1285 100 40 100 100 12.80 -3.87 3.65 +1286 100 100 100 100 12.71 0.53 4.89 +1287 100 0 0 0 56.12 -34.90 -52.52 +1288 98 0 0 0 56.57 -34.55 -51.98 +1289 95 0 0 0 57.50 -33.86 -50.97 +1290 90 0 0 0 58.99 -32.23 -49.17 +1291 85 0 0 0 60.62 -30.20 -47.07 +1292 80 0 0 0 62.52 -28.10 -44.74 +1293 75 0 0 0 64.50 -26.08 -42.35 +1294 70 0 0 0 66.57 -24.03 -39.84 +1295 60 0 0 0 70.86 -20.12 -34.85 +1296 50 0 0 0 75.02 -16.20 -29.84 +1297 40 0 0 0 79.15 -12.57 -24.94 +1298 30 0 0 0 83.19 -9.04 -20.26 +1299 25 0 0 0 85.18 -7.33 -17.89 +1300 20 0 0 0 87.20 -5.64 -15.58 +1301 15 0 0 0 89.19 -3.96 -13.25 +1302 10 0 0 0 91.19 -2.28 -10.93 +1303 7 0 0 0 92.40 -1.23 -9.48 +1304 5 0 0 0 93.14 -0.51 -8.50 +1305 3 0 0 0 93.93 0.25 -7.56 +1306 2 0 0 0 94.35 0.55 -7.24 +1307 0 100 0 0 48.06 75.29 -5.18 +1308 0 98 0 0 48.58 74.48 -5.81 +1309 0 95 0 0 49.56 72.84 -6.62 +1310 0 90 0 0 51.30 69.51 -7.29 +1311 0 85 0 0 53.32 65.54 -7.71 +1312 0 80 0 0 55.59 61.24 -8.19 +1313 0 75 0 0 57.94 56.95 -8.67 +1314 0 70 0 0 60.42 52.69 -9.17 +1315 0 60 0 0 65.44 44.19 -9.58 +1316 0 50 0 0 70.47 36.07 -9.54 +1317 0 40 0 0 75.43 28.45 -9.24 +1318 0 30 0 0 80.33 21.39 -8.87 +1319 0 25 0 0 82.76 18.02 -8.63 +1320 0 20 0 0 85.20 14.67 -8.29 +1321 0 15 0 0 87.63 11.40 -7.90 +1322 0 10 0 0 90.08 8.15 -7.42 +1323 0 7 0 0 91.57 6.24 -7.19 +1324 0 5 0 0 92.53 5.00 -7.00 +1325 0 3 0 0 93.54 3.67 -6.73 +1326 0 2 0 0 94.02 3.03 -6.59 +1327 0 0 100 0 88.94 -4.04 92.37 +1328 0 0 98 0 89.05 -4.12 91.02 +1329 0 0 95 0 89.18 -4.15 88.37 +1330 0 0 90 0 89.33 -4.25 83.43 +1331 0 0 85 0 89.59 -4.30 78.11 +1332 0 0 80 0 89.85 -4.20 72.40 +1333 0 0 75 0 90.11 -4.17 66.82 +1334 0 0 70 0 90.44 -4.21 61.28 +1335 0 0 60 0 91.03 -3.89 50.35 +1336 0 0 50 0 91.62 -3.44 39.94 +1337 0 0 40 0 92.30 -2.85 30.21 +1338 0 0 30 0 92.93 -2.11 20.82 +1339 0 0 25 0 93.40 -1.69 16.51 +1340 0 0 20 0 93.66 -1.17 11.88 +1341 0 0 15 0 93.99 -0.63 7.37 +1342 0 0 10 0 94.39 -0.05 3.02 +1343 0 0 7 0 94.60 0.34 0.33 +1344 0 0 5 0 94.73 0.66 -1.45 +1345 0 0 3 0 94.88 0.93 -3.22 +1346 0 0 2 0 94.95 1.09 -4.07 +1347 0 0 0 100 16.00 0.07 -0.33 +1348 0 0 0 98 18.05 0.02 -0.43 +1349 0 0 0 95 21.52 -0.02 -0.81 +1350 0 0 0 90 27.02 -0.06 -1.52 +1351 0 0 0 85 32.37 -0.07 -2.07 +1352 0 0 0 80 37.53 -0.06 -2.55 +1353 0 0 0 75 42.24 -0.02 -2.96 +1354 0 0 0 70 46.75 0.02 -3.25 +1355 0 0 0 60 55.11 0.16 -3.90 +1356 0 0 0 50 62.72 0.31 -4.44 +1357 0 0 0 40 69.76 0.49 -4.90 +1358 0 0 0 30 76.38 0.70 -5.30 +1359 0 0 0 25 79.55 0.81 -5.46 +1360 0 0 0 20 82.71 0.94 -5.62 +1361 0 0 0 15 85.80 1.07 -5.72 +1362 0 0 0 10 88.87 1.20 -5.84 +1363 0 0 0 7 90.74 1.29 -5.91 +1364 0 0 0 5 91.93 1.35 -5.95 +1365 0 0 0 3 93.17 1.44 -6.02 +1366 0 0 0 2 93.76 1.45 -6.05 +1367 0 0 0 0 95.00 1.50 -6.00 +1368 100 85 85 0 26.30 -8.17 -4.54 +1369 80 65 65 0 36.49 -4.67 -4.60 +1370 60 45 45 0 50.74 -2.08 -4.61 +1371 40 27 27 0 66.01 -1.20 -5.85 +1372 20 12 12 0 80.96 -0.21 -6.62 +1373 10 6 6 0 88.02 0.65 -6.52 +1374 5 3 3 0 91.58 1.10 -6.43 +1375 40 27 27 10 61.99 -1.45 -5.47 +1376 20 12 12 10 75.81 -0.43 -6.33 +1377 10 6 6 10 82.35 0.39 -6.28 +1378 60 45 45 20 44.69 -2.51 -3.66 +1379 40 27 27 20 57.98 -1.61 -5.04 +1380 20 12 12 20 70.61 -0.59 -5.97 +1381 10 6 6 20 76.63 0.17 -5.98 +1382 80 65 65 40 27.71 -3.78 -2.51 +1383 60 45 45 40 38.04 -2.45 -2.75 +1384 40 27 27 40 49.24 -1.73 -4.05 +1385 20 12 12 40 59.61 -0.81 -5.04 +1386 10 6 6 40 64.59 -0.13 -5.13 +1387 100 85 85 60 17.70 -4.01 -0.61 +1388 80 65 65 60 22.63 -2.96 -1.16 +1389 60 45 45 60 30.36 -2.12 -1.67 +1390 40 27 27 60 39.06 -1.68 -2.95 +1391 20 12 12 60 47.01 -0.85 -3.91 +1392 10 6 6 60 50.89 -0.32 -4.09 +1393 100 85 85 80 14.88 -2.17 1.75 +1394 80 65 65 80 17.21 -1.53 0.63 +1395 60 45 45 80 21.59 -1.41 -0.19 +1396 40 27 27 80 26.96 -1.27 -1.44 +1397 20 12 12 80 32.13 -0.70 -2.44 +1398 10 6 6 80 34.71 -0.35 -2.66 +1399 100 85 85 100 12.62 0.12 4.12 +1400 80 65 65 100 12.68 0.09 2.71 +1401 60 45 45 100 13.10 0.10 1.39 +1402 40 27 27 100 13.98 0.00 0.32 +1403 20 12 12 100 15.06 -0.10 -0.36 +1404 10 6 6 100 15.59 -0.04 -0.46 +1405 100 0 0 70 27.49 -18.64 -25.44 +1406 0 100 0 70 23.52 35.19 -2.30 +1407 0 0 100 70 42.49 -4.09 42.01 +1408 100 100 0 70 15.42 9.13 -19.40 +1409 100 0 100 70 24.95 -31.00 10.13 +1410 0 100 100 70 23.56 29.25 17.99 +1411 40 40 0 70 31.54 4.94 -11.63 +1412 40 0 40 70 37.27 -10.46 3.88 +1413 0 40 40 70 35.66 10.84 9.34 +1414 3 3 0 0 92.55 2.20 -7.96 +1415 3 0 3 0 93.78 -0.25 -4.84 +1416 0 3 3 0 93.40 3.06 -4.03 +1417 3 3 3 0 92.34 1.87 -5.54 +1418 3 0 0 3 92.13 0.09 -7.49 +1419 0 3 0 3 91.79 3.43 -6.42 +1420 3 3 0 3 90.71 2.20 -8.14 +1421 0 0 3 3 93.04 0.91 -3.30 +1422 3 0 3 3 91.97 -0.36 -4.85 +1423 0 3 3 3 91.61 3.01 -4.04 +1424 3 3 3 3 90.56 1.72 -5.52 +1425 7 7 0 0 89.04 3.48 -10.58 +1426 7 0 7 0 91.94 -2.39 -3.22 +1427 0 7 7 0 91.18 5.14 -1.04 +1428 7 7 7 0 88.64 2.29 -4.41 +1429 7 0 0 7 88.25 -1.37 -9.15 +1430 0 7 0 7 87.49 5.71 -6.87 +1431 7 7 0 7 85.04 3.07 -10.21 +1432 0 0 7 7 90.32 0.22 0.07 +1433 7 0 7 7 87.81 -2.46 -3.19 +1434 0 7 7 7 87.07 4.70 -1.17 +1435 7 7 7 7 84.66 1.96 -4.38 +1436 40 3 0 0 77.93 -10.75 -25.27 +1437 3 40 0 0 74.61 26.77 -10.39 +1438 40 0 3 0 78.92 -13.18 -22.40 +1439 40 3 3 0 77.72 -11.43 -22.75 +1440 0 40 3 0 75.34 28.07 -7.02 +1441 3 40 3 0 74.45 26.59 -8.37 +1442 40 40 3 0 62.13 10.79 -23.92 +1443 3 0 40 0 91.15 -4.19 28.42 +1444 0 3 40 0 90.86 -0.60 29.02 +1445 3 3 40 0 89.76 -2.05 27.45 +1446 40 3 40 0 74.85 -17.75 8.07 +1447 3 40 40 0 72.48 23.76 18.99 +1448 40 0 0 3 77.67 -12.47 -24.39 +1449 40 3 0 3 76.42 -10.55 -24.92 +1450 0 40 0 3 74.02 27.71 -9.10 +1451 3 40 0 3 73.15 26.27 -10.51 +1452 40 40 0 3 61.12 11.14 -25.64 +1453 40 0 3 3 77.48 -13.20 -21.84 +1454 40 3 3 3 76.26 -11.22 -22.41 +1455 0 40 3 3 73.92 27.37 -6.91 +1456 3 40 3 3 73.05 25.93 -8.34 +1457 40 40 3 3 61.00 10.54 -23.50 +1458 0 0 40 3 90.45 -2.80 29.34 +1459 3 0 40 3 89.37 -4.26 27.78 +1460 40 0 40 3 74.61 -19.37 8.58 +1461 0 3 40 3 89.07 -0.67 28.27 +1462 3 3 40 3 88.00 -2.07 26.74 +1463 40 3 40 3 73.44 -17.46 7.77 +1464 0 40 40 3 71.98 24.68 19.89 +1465 3 40 40 3 71.07 23.12 18.45 +1466 40 40 40 3 58.83 5.61 1.84 +1467 3 0 0 40 68.97 -0.47 -5.92 +1468 0 3 0 40 68.68 1.98 -5.31 +1469 3 3 0 40 67.90 1.02 -6.38 +1470 40 3 0 40 57.49 -8.36 -18.26 +1471 3 40 0 40 54.94 18.59 -8.20 +1472 0 0 3 40 69.62 0.07 -2.86 +1473 3 0 3 40 68.82 -0.89 -3.94 +1474 40 0 3 40 58.20 -10.26 -16.04 +1475 0 3 3 40 68.53 1.58 -3.41 +1476 3 3 3 40 67.76 0.63 -4.46 +1477 40 3 3 40 57.36 -8.89 -16.42 +1478 0 40 3 40 55.43 19.26 -5.61 +1479 3 40 3 40 54.84 18.24 -6.56 +1480 40 40 3 40 46.48 7.16 -16.97 +1481 3 0 40 40 66.57 -3.98 19.51 +1482 0 3 40 40 66.31 -1.41 19.93 +1483 3 3 40 40 65.56 -2.43 18.78 +1484 40 3 40 40 55.13 -13.59 5.51 +1485 3 40 40 40 53.07 15.89 13.30 +1486 0 0 0 10 88.87 1.20 -5.84 +1487 0 0 10 10 88.24 -0.22 2.54 +1488 0 0 20 10 87.54 -1.22 10.66 +1489 0 0 40 10 86.23 -2.89 27.68 +1490 0 0 70 10 84.38 -4.29 56.70 +1491 0 10 0 10 84.30 7.28 -7.06 +1492 0 10 10 10 83.70 5.91 0.98 +1493 0 10 20 10 83.04 4.96 8.82 +1494 0 10 40 10 81.79 3.42 25.08 +1495 0 10 70 10 80.06 2.07 52.70 +1496 0 20 0 10 79.78 13.27 -7.75 +1497 0 20 10 10 79.19 12.05 -0.09 +1498 0 20 20 10 78.57 11.20 7.35 +1499 0 20 40 10 77.36 9.84 22.78 +1500 0 20 70 10 75.72 8.57 49.29 +1501 0 40 0 10 70.66 26.17 -8.83 +1502 0 40 10 10 70.20 25.09 -2.01 +1503 0 40 20 10 69.66 24.31 4.85 +1504 0 40 40 10 68.63 23.17 18.78 +1505 0 40 70 10 67.18 22.19 42.85 +1506 0 70 0 10 56.54 48.71 -8.78 +1507 0 70 10 10 56.16 48.22 -3.01 +1508 0 70 20 10 55.82 47.41 2.66 +1509 0 70 40 10 55.25 46.37 14.45 +1510 0 70 70 10 54.42 45.45 34.15 +1511 10 0 0 10 85.30 -2.40 -10.30 +1512 10 0 10 10 84.64 -3.94 -1.90 +1513 10 0 20 10 83.94 -5.11 6.25 +1514 10 0 40 10 82.58 -6.97 22.88 +1515 10 0 70 10 80.69 -8.74 50.84 +1516 10 10 0 10 80.92 3.59 -11.37 +1517 10 10 10 10 80.31 2.16 -3.42 +1518 10 10 20 10 79.64 1.02 4.36 +1519 10 10 40 10 78.32 -0.75 20.31 +1520 10 10 70 10 76.52 -2.40 47.48 +1521 10 20 0 10 76.55 9.49 -12.01 +1522 10 20 10 10 75.96 8.13 -4.43 +1523 10 20 20 10 75.34 7.07 3.10 +1524 10 20 40 10 74.08 5.48 18.28 +1525 10 20 70 10 72.37 3.91 44.21 +1526 10 40 0 10 67.78 22.03 -12.78 +1527 10 40 10 10 67.26 20.88 -6.02 +1528 10 40 20 10 66.70 19.95 0.71 +1529 10 40 40 10 65.67 18.52 14.59 +1530 10 40 70 10 64.17 17.26 38.14 +1531 10 70 0 10 53.96 44.28 -12.87 +1532 10 70 10 10 53.60 43.38 -7.17 +1533 10 70 20 10 53.24 42.67 -1.51 +1534 10 70 40 10 52.65 41.55 10.21 +1535 10 70 70 10 51.72 40.18 29.77 +1536 20 0 0 10 81.61 -5.48 -14.56 +1537 20 0 10 10 80.91 -7.17 -6.30 +1538 20 0 20 10 80.21 -8.56 1.77 +1539 20 0 40 10 78.80 -10.64 18.04 +1540 20 0 70 10 76.83 -12.75 45.48 +1541 20 10 0 10 77.43 0.32 -15.46 +1542 20 10 10 10 76.80 -1.33 -7.59 +1543 20 10 20 10 76.12 -2.57 0.04 +1544 20 10 40 10 74.74 -4.63 15.66 +1545 20 10 70 10 72.86 -6.62 42.38 +1546 20 20 0 10 73.23 6.03 -15.93 +1547 20 20 10 10 72.61 4.53 -8.46 +1548 20 20 20 10 71.98 3.31 -1.11 +1549 20 20 40 10 70.70 1.43 13.78 +1550 20 20 70 10 68.92 -0.45 39.35 +1551 20 40 0 10 64.72 18.15 -16.53 +1552 20 40 10 10 64.19 16.90 -9.85 +1553 20 40 20 10 63.62 15.86 -3.18 +1554 20 40 40 10 62.59 14.17 10.46 +1555 20 40 70 10 61.07 12.57 33.64 +1556 20 70 0 10 51.28 39.93 -16.57 +1557 20 70 10 10 50.93 38.94 -10.90 +1558 20 70 20 10 50.57 38.10 -5.41 +1559 20 70 40 10 49.96 36.56 6.09 +1560 20 70 70 10 49.00 35.14 25.36 +1561 40 0 0 10 74.18 -12.07 -23.20 +1562 40 0 10 10 73.40 -14.10 -15.36 +1563 40 0 20 10 72.65 -15.78 -7.61 +1564 40 0 40 10 71.21 -18.63 8.10 +1565 40 0 70 10 69.18 -21.62 34.72 +1566 40 10 0 10 70.30 -6.51 -23.88 +1567 40 10 10 10 69.62 -8.55 -16.29 +1568 40 10 20 10 68.92 -10.17 -8.86 +1569 40 10 40 10 67.54 -12.92 6.29 +1570 40 10 70 10 65.62 -15.82 31.84 +1571 40 20 0 10 66.44 -0.99 -24.08 +1572 40 20 10 10 65.79 -3.00 -16.85 +1573 40 20 20 10 65.12 -4.53 -9.77 +1574 40 20 40 10 63.82 -7.18 4.70 +1575 40 20 70 10 62.04 -9.90 29.26 +1576 40 40 0 10 58.51 10.38 -24.34 +1577 40 40 10 10 58.01 8.75 -17.80 +1578 40 40 20 10 57.40 7.44 -11.40 +1579 40 40 40 10 56.29 5.08 1.86 +1580 40 40 70 10 54.79 2.64 24.08 +1581 40 70 0 10 45.93 31.07 -24.24 +1582 40 70 10 10 45.59 29.75 -18.80 +1583 40 70 20 10 45.20 28.62 -13.36 +1584 40 70 40 10 44.43 26.65 -2.21 +1585 40 70 70 10 43.56 24.36 16.26 +1586 70 0 0 10 62.40 -23.02 -37.07 +1587 70 0 10 10 61.58 -25.88 -29.74 +1588 70 0 20 10 60.85 -28.45 -22.33 +1589 70 0 40 10 59.42 -32.83 -7.37 +1590 70 0 70 10 57.39 -38.02 17.38 +1591 70 10 0 10 59.10 -17.72 -37.33 +1592 70 10 10 10 58.41 -20.70 -30.10 +1593 70 10 20 10 57.69 -23.19 -23.01 +1594 70 10 40 10 56.34 -27.56 -8.62 +1595 70 10 70 10 54.39 -32.60 15.20 +1596 70 20 0 10 55.73 -12.82 -37.04 +1597 70 20 10 10 55.15 -15.56 -30.18 +1598 70 20 20 10 54.45 -17.96 -23.43 +1599 70 20 40 10 53.13 -22.13 -9.64 +1600 70 20 70 10 51.30 -27.04 13.19 +1601 70 40 0 10 48.89 -2.37 -36.71 +1602 70 40 10 10 48.38 -4.80 -30.47 +1603 70 40 20 10 47.76 -6.91 -24.27 +1604 70 40 40 10 46.66 -10.68 -11.66 +1605 70 40 70 10 45.12 -15.17 9.13 +1606 70 70 0 10 37.75 16.76 -36.11 +1607 70 70 10 10 37.46 14.56 -30.89 +1608 70 70 20 10 37.07 12.70 -25.68 +1609 70 70 40 10 36.35 9.41 -14.88 +1610 70 70 70 10 35.34 5.51 2.36 +1611 50 40 40 0 56.52 0.52 -2.91 +1612 100 0 0 10 52.62 -33.38 -48.95 +1613 0 100 0 10 44.79 70.33 -5.59 +1614 0 0 100 10 82.93 -4.35 86.26 +1615 0 100 100 10 44.53 64.54 41.83 +1616 100 0 100 10 46.36 -61.85 22.67 +1617 100 100 0 10 23.48 19.48 -44.21 +END_DATA diff --git a/crates/color/data/FOGRA52.txt b/crates/color/data/FOGRA52.txt new file mode 100644 index 0000000000..229c5b1c5f --- /dev/null +++ b/crates/color/data/FOGRA52.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA52" +ORIGINATOR "Fogra, www.fogra.org, developed with GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 5 = Wood-free uncoated, fluorescence high (> 14 DeltaB according to ISO 15397), 120 g/m2, tone value increase curves C (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 93.50 2.50 -10.00 +2 0 10 0 0 87.84 10.05 -10.46 +3 0 20 0 0 82.74 17.07 -10.66 +4 0 30 0 0 78.06 23.70 -10.61 +5 0 40 0 0 73.74 30.00 -10.32 +6 0 55 0 0 67.80 39.21 -9.60 +7 0 70 0 0 62.30 47.89 -8.22 +8 0 85 0 0 57.60 55.31 -6.22 +9 0 100 0 0 54.54 60.07 -4.30 +10 10 0 0 0 88.67 -1.16 -15.51 +11 10 10 0 0 83.36 5.91 -15.71 +12 10 20 0 0 78.55 12.48 -15.69 +13 10 30 0 0 74.13 18.69 -15.49 +14 10 40 0 0 70.02 24.58 -15.08 +15 10 55 0 0 64.43 33.15 -14.16 +16 10 70 0 0 59.19 41.31 -12.69 +17 10 85 0 0 54.66 48.36 -10.74 +18 10 100 0 0 51.67 52.96 -8.93 +19 20 0 0 0 84.29 -4.47 -20.44 +20 20 10 0 0 79.29 2.17 -20.40 +21 20 20 0 0 74.76 8.33 -20.19 +22 20 30 0 0 70.57 14.15 -19.84 +23 20 40 0 0 66.67 19.68 -19.34 +24 20 55 0 0 61.40 27.65 -18.21 +25 20 70 0 0 56.42 35.28 -16.64 +26 20 85 0 0 52.07 41.96 -14.69 +27 20 100 0 0 49.17 46.36 -12.96 +28 30 0 0 0 80.24 -7.50 -24.94 +29 30 10 0 0 75.53 -1.25 -24.68 +30 30 20 0 0 71.25 4.53 -24.30 +31 30 30 0 0 67.29 9.98 -23.81 +32 30 40 0 0 63.58 15.17 -23.20 +33 30 55 0 0 58.63 22.56 -21.87 +34 30 70 0 0 53.91 29.68 -20.18 +35 30 85 0 0 49.75 35.95 -18.21 +36 30 100 0 0 46.94 40.15 -16.52 +37 40 0 0 0 76.45 -10.28 -29.09 +38 40 10 0 0 72.02 -4.41 -28.63 +39 40 20 0 0 67.98 1.02 -28.09 +40 40 30 0 0 64.23 6.14 -27.46 +41 40 40 0 0 60.71 10.99 -26.76 +42 40 55 0 0 56.06 17.83 -25.22 +43 40 70 0 0 51.61 24.43 -23.39 +44 40 85 0 0 47.65 30.29 -21.37 +45 40 100 0 0 44.95 34.24 -19.69 +46 55 0 0 0 71.16 -14.26 -34.98 +47 55 10 0 0 67.16 -8.79 -34.07 +48 55 20 0 0 63.52 -3.74 -33.13 +49 55 30 0 0 60.12 1.02 -32.16 +50 55 40 0 0 56.92 5.55 -31.14 +51 55 55 0 0 52.80 11.83 -29.39 +52 55 70 0 0 48.83 17.92 -27.40 +53 55 85 0 0 45.28 23.39 -25.30 +54 55 100 0 0 42.84 27.13 -23.62 +55 70 0 0 0 66.13 -17.82 -40.45 +56 70 10 0 0 62.55 -12.77 -39.12 +57 70 20 0 0 59.27 -8.11 -37.83 +58 70 30 0 0 56.21 -3.72 -36.53 +59 70 40 0 0 53.32 0.45 -35.22 +60 70 55 0 0 49.74 6.14 -33.24 +61 70 70 0 0 46.26 11.70 -31.09 +62 70 85 0 0 43.12 16.72 -28.88 +63 70 100 0 0 40.96 20.19 -27.16 +64 85 0 0 0 61.71 -20.66 -45.11 +65 85 10 0 0 58.47 -16.02 -43.45 +66 85 20 0 0 55.52 -11.74 -41.84 +67 85 30 0 0 52.76 -7.72 -40.26 +68 85 40 0 0 50.15 -3.88 -38.69 +69 85 55 0 0 47.05 1.23 -36.52 +70 85 70 0 0 44.04 6.24 -34.20 +71 85 85 0 0 41.32 10.80 -31.87 +72 85 100 0 0 39.43 13.98 -30.09 +73 100 0 0 0 58.70 -22.35 -48.12 +74 100 10 0 0 55.71 -18.02 -46.24 +75 100 20 0 0 52.98 -14.03 -44.44 +76 100 30 0 0 50.42 -10.26 -42.69 +77 100 40 0 0 48.01 -6.69 -40.95 +78 100 55 0 0 45.25 -2.00 -38.66 +79 100 70 0 0 42.57 2.62 -36.22 +80 100 85 0 0 40.15 6.83 -33.80 +81 100 100 0 0 38.47 9.76 -31.96 +82 0 0 10 0 92.65 0.82 0.84 +83 0 10 10 0 87.02 8.58 -0.61 +84 0 20 10 0 81.96 15.80 -1.70 +85 0 30 10 0 77.31 22.61 -2.48 +86 0 40 10 0 73.02 29.08 -2.98 +87 0 55 10 0 67.21 38.37 -3.29 +88 0 70 10 0 61.83 47.13 -2.94 +89 0 85 10 0 57.23 54.62 -1.90 +90 0 100 10 0 54.24 59.43 -0.66 +91 10 0 10 0 87.76 -3.15 -5.03 +92 10 10 10 0 82.49 4.15 -6.14 +93 10 20 10 0 77.74 10.93 -6.96 +94 10 30 10 0 73.37 17.34 -7.53 +95 10 40 10 0 69.31 23.43 -7.87 +96 10 55 10 0 63.85 32.11 -7.97 +97 10 70 10 0 58.74 40.38 -7.50 +98 10 85 10 0 54.33 47.53 -6.49 +99 10 100 10 0 51.42 52.21 -5.36 +100 20 0 10 0 83.32 -6.77 -10.27 +101 20 10 10 0 78.39 0.13 -11.09 +102 20 20 10 0 73.92 6.52 -11.67 +103 20 30 10 0 69.80 12.55 -12.06 +104 20 40 10 0 65.96 18.29 -12.24 +105 20 55 10 0 60.84 26.41 -12.11 +106 20 70 10 0 56.00 34.18 -11.54 +107 20 85 10 0 51.78 40.98 -10.52 +108 20 100 10 0 48.95 45.49 -9.45 +109 30 0 10 0 79.22 -10.10 -15.07 +110 30 10 10 0 74.59 -3.58 -15.62 +111 30 20 10 0 70.40 2.45 -15.98 +112 30 30 10 0 66.51 8.13 -16.17 +113 30 40 10 0 62.87 13.54 -16.22 +114 30 55 10 0 58.08 21.11 -15.87 +115 30 70 10 0 53.51 28.39 -15.16 +116 30 85 10 0 49.49 34.83 -14.11 +117 30 100 10 0 46.77 39.14 -13.07 +118 40 0 10 0 75.39 -13.19 -19.50 +119 40 10 10 0 71.05 -7.03 -19.79 +120 40 20 10 0 67.11 -1.34 -19.94 +121 40 30 10 0 63.44 4.03 -19.97 +122 40 40 10 0 60.00 9.13 -19.88 +123 40 55 10 0 55.53 16.17 -19.31 +124 40 70 10 0 51.24 22.97 -18.44 +125 40 85 10 0 47.43 29.01 -17.31 +126 40 100 10 0 44.83 33.10 -16.29 +127 55 0 10 0 70.17 -17.38 -25.68 +128 55 10 10 0 66.26 -11.60 -25.50 +129 55 20 10 0 62.70 -6.27 -25.25 +130 55 30 10 0 59.38 -1.25 -24.92 +131 55 40 10 0 56.27 3.52 -24.51 +132 55 55 10 0 52.29 10.03 -23.64 +133 55 70 10 0 48.44 16.37 -22.55 +134 55 85 10 0 45.00 22.06 -21.29 +135 55 100 10 0 42.64 25.93 -20.20 +136 70 0 10 0 65.19 -21.21 -31.44 +137 70 10 10 0 61.70 -15.83 -30.84 +138 70 20 10 0 58.51 -10.86 -30.21 +139 70 30 10 0 55.53 -6.19 -29.54 +140 70 40 10 0 52.72 -1.75 -28.83 +141 70 55 10 0 49.23 4.22 -27.67 +142 70 70 10 0 45.84 10.04 -26.34 +143 70 85 10 0 42.79 15.30 -24.89 +144 70 100 10 0 40.68 18.93 -23.72 +145 85 0 10 0 60.80 -24.35 -36.38 +146 85 10 10 0 57.67 -19.34 -35.43 +147 85 20 10 0 54.80 -14.73 -34.48 +148 85 30 10 0 52.12 -10.39 -33.53 +149 85 40 10 0 49.59 -6.27 -32.54 +150 85 55 10 0 46.55 -0.84 -31.12 +151 85 70 10 0 43.60 4.47 -29.55 +152 85 85 10 0 40.92 9.31 -27.94 +153 85 100 10 0 39.07 12.66 -26.66 +154 100 0 10 0 57.83 -26.26 -39.62 +155 100 10 10 0 54.93 -21.54 -38.43 +156 100 20 10 0 52.28 -17.18 -37.28 +157 100 30 10 0 49.81 -13.10 -36.12 +158 100 40 10 0 47.47 -9.21 -34.97 +159 100 55 10 0 44.75 -4.17 -33.38 +160 100 70 10 0 42.10 0.77 -31.65 +161 100 85 10 0 39.70 5.27 -29.89 +162 100 100 10 0 38.04 8.40 -28.52 +163 0 0 20 0 91.90 -0.46 10.79 +164 0 10 20 0 86.29 7.45 8.46 +165 0 20 20 0 81.25 14.82 6.55 +166 0 30 20 0 76.63 21.78 5.01 +167 0 40 20 0 72.37 28.37 3.80 +168 0 55 20 0 66.68 37.70 2.53 +169 0 70 20 0 61.40 46.50 1.95 +170 0 85 20 0 56.90 54.03 2.11 +171 0 100 20 0 53.96 58.87 2.71 +172 10 0 20 0 86.95 -4.72 4.61 +173 10 10 20 0 81.72 2.76 2.67 +174 10 20 20 0 77.01 9.71 1.08 +175 10 30 20 0 72.68 16.27 -0.21 +176 10 40 20 0 68.66 22.50 -1.22 +177 10 55 20 0 63.33 31.26 -2.24 +178 10 70 20 0 58.34 39.59 -2.71 +179 10 85 20 0 54.03 46.81 -2.56 +180 10 100 20 0 51.18 51.54 -2.06 +181 20 0 20 0 82.46 -8.61 -0.93 +182 20 10 20 0 77.58 -1.53 -2.53 +183 20 20 20 0 73.17 5.05 -3.83 +184 20 30 20 0 69.10 11.26 -4.88 +185 20 40 20 0 65.31 17.16 -5.70 +186 20 55 20 0 60.32 25.37 -6.49 +187 20 70 20 0 55.62 33.24 -6.82 +188 20 85 20 0 51.51 40.14 -6.66 +189 20 100 20 0 48.76 44.71 -6.20 +190 30 0 20 0 78.31 -12.23 -6.00 +191 30 10 20 0 73.76 -5.50 -7.28 +192 30 20 20 0 69.62 0.73 -8.31 +193 30 30 20 0 65.80 6.61 -9.14 +194 30 40 20 0 62.23 12.20 -9.78 +195 30 55 20 0 57.58 19.89 -10.33 +196 30 70 20 0 53.16 27.29 -10.51 +197 30 85 20 0 49.26 33.85 -10.29 +198 30 100 20 0 46.62 38.25 -9.87 +199 40 0 20 0 74.44 -15.60 -10.68 +200 40 10 20 0 70.19 -9.21 -11.66 +201 40 20 20 0 66.32 -3.30 -12.44 +202 40 30 20 0 62.73 2.28 -13.06 +203 40 40 20 0 59.36 7.57 -13.53 +204 40 55 20 0 55.05 14.75 -13.84 +205 40 70 20 0 50.91 21.70 -13.85 +206 40 85 20 0 47.23 27.89 -13.56 +207 40 100 20 0 44.72 32.08 -13.13 +208 55 0 20 0 69.28 -19.99 -17.11 +209 55 10 20 0 65.45 -13.96 -17.62 +210 55 20 20 0 61.97 -8.40 -17.99 +211 55 30 20 0 58.73 -3.16 -18.24 +212 55 40 20 0 55.68 1.82 -18.38 +213 55 55 20 0 51.82 8.51 -18.34 +214 55 70 20 0 48.09 15.02 -18.05 +215 55 85 20 0 44.76 20.87 -17.55 +216 55 100 20 0 42.46 24.87 -17.02 +217 70 0 20 0 64.35 -24.06 -23.14 +218 70 10 20 0 60.94 -18.40 -23.20 +219 70 20 20 0 57.82 -13.18 -23.19 +220 70 30 20 0 54.91 -8.27 -23.09 +221 70 40 20 0 52.17 -3.61 -22.92 +222 70 55 20 0 48.77 2.56 -22.52 +223 70 70 20 0 45.46 8.60 -21.94 +224 70 85 20 0 42.48 14.06 -21.20 +225 70 100 20 0 40.42 17.82 -20.54 +226 85 0 20 0 60.01 -27.46 -28.34 +227 85 10 20 0 56.95 -22.15 -28.03 +228 85 20 20 0 54.16 -17.26 -27.69 +229 85 30 20 0 51.55 -12.67 -27.29 +230 85 40 20 0 49.09 -8.30 -26.85 +231 85 55 20 0 46.10 -2.62 -26.12 +232 85 70 20 0 43.19 2.95 -25.25 +233 85 85 20 0 40.56 8.00 -24.28 +234 85 100 20 0 38.73 11.50 -23.47 +235 100 0 20 0 57.06 -29.59 -31.76 +236 100 10 20 0 54.25 -24.54 -31.22 +237 100 20 20 0 51.67 -19.89 -30.66 +238 100 30 20 0 49.27 -15.52 -30.06 +239 100 40 20 0 47.00 -11.38 -29.43 +240 100 55 20 0 44.30 -6.06 -28.50 +241 100 70 20 0 41.68 -0.84 -27.41 +242 100 85 20 0 39.30 3.90 -26.26 +243 100 100 20 0 37.65 7.20 -25.35 +244 0 0 30 0 91.22 -1.45 20.12 +245 0 10 30 0 85.62 6.59 16.96 +246 0 20 30 0 80.60 14.07 14.29 +247 0 30 30 0 76.01 21.13 12.04 +248 0 40 30 0 71.77 27.83 10.16 +249 0 55 30 0 66.18 37.17 8.02 +250 0 70 30 0 60.99 45.97 6.55 +251 0 85 30 0 56.58 53.50 5.90 +252 0 100 30 0 53.70 58.36 5.90 +253 10 0 30 0 86.21 -5.97 13.64 +254 10 10 30 0 81.02 1.65 10.92 +255 10 20 30 0 76.34 8.73 8.62 +256 10 30 30 0 72.04 15.42 6.67 +257 10 40 30 0 68.06 21.77 5.03 +258 10 55 30 0 62.84 30.56 3.15 +259 10 70 30 0 57.96 38.92 1.82 +260 10 85 30 0 53.75 46.18 1.15 +261 10 100 30 0 50.96 50.94 1.07 +262 20 0 30 0 81.67 -10.12 7.82 +263 20 10 30 0 76.84 -2.88 5.50 +264 20 20 30 0 72.47 3.84 3.54 +265 20 30 30 0 68.45 10.19 1.86 +266 20 40 30 0 64.71 16.23 0.44 +267 20 55 30 0 59.85 24.49 -1.18 +268 20 70 30 0 55.26 32.42 -2.37 +269 20 85 30 0 51.26 39.38 -3.00 +270 20 100 30 0 48.58 44.02 -3.13 +271 30 0 30 0 77.48 -14.00 2.50 +272 30 10 30 0 72.99 -7.10 0.55 +273 30 20 30 0 68.91 -0.70 -1.11 +274 30 30 30 0 65.15 5.33 -2.53 +275 30 40 30 0 61.63 11.07 -3.73 +276 30 55 30 0 57.12 18.83 -5.10 +277 30 70 30 0 52.83 26.32 -6.12 +278 30 85 30 0 49.04 32.96 -6.69 +279 30 100 30 0 46.48 37.43 -6.83 +280 40 0 30 0 73.58 -17.64 -2.41 +281 40 10 30 0 69.40 -11.06 -4.03 +282 40 20 30 0 65.60 -4.97 -5.40 +283 40 30 30 0 62.07 0.78 -6.57 +284 40 40 30 0 58.78 6.24 -7.56 +285 40 55 30 0 54.61 13.52 -8.68 +286 40 70 30 0 50.61 20.57 -9.52 +287 40 85 30 0 47.05 26.88 -10.00 +288 40 100 30 0 44.62 31.15 -10.13 +289 55 0 30 0 68.47 -22.20 -9.07 +290 55 10 30 0 64.72 -15.97 -10.21 +291 55 20 30 0 61.30 -10.21 -11.15 +292 55 30 30 0 58.12 -4.79 -11.95 +293 55 40 30 0 55.14 0.37 -12.61 +294 55 55 30 0 51.39 7.19 -13.32 +295 55 70 30 0 47.77 13.83 -13.81 +296 55 85 30 0 44.52 19.81 -14.03 +297 55 100 30 0 42.29 23.90 -14.01 +298 70 0 30 0 63.60 -26.48 -15.34 +299 70 10 30 0 60.25 -20.60 -16.02 +300 70 20 30 0 57.20 -15.17 -16.58 +301 70 30 30 0 54.35 -10.06 -17.02 +302 70 40 30 0 51.68 -5.22 -17.36 +303 70 55 30 0 48.35 1.13 -17.66 +304 70 70 30 0 45.11 7.33 -17.78 +305 70 85 30 0 42.20 12.94 -17.71 +306 70 100 30 0 40.18 16.81 -17.53 +307 85 0 30 0 59.29 -30.13 -20.77 +308 85 10 30 0 56.31 -24.56 -21.08 +309 85 20 30 0 53.58 -19.44 -21.28 +310 85 30 30 0 51.03 -14.63 -21.42 +311 85 40 30 0 48.63 -10.07 -21.48 +312 85 55 30 0 45.68 -4.18 -21.40 +313 85 70 30 0 42.82 1.58 -21.18 +314 85 85 30 0 40.22 6.81 -20.82 +315 85 100 30 0 38.42 10.44 -20.46 +316 100 0 30 0 56.37 -32.45 -24.37 +317 100 10 30 0 53.63 -27.12 -24.43 +318 100 20 30 0 51.12 -22.22 -24.42 +319 100 30 30 0 48.77 -17.62 -24.35 +320 100 40 30 0 46.56 -13.26 -24.21 +321 100 55 30 0 43.89 -7.71 -23.87 +322 100 70 30 0 41.29 -2.27 -23.41 +323 100 85 30 0 38.93 2.68 -22.84 +324 100 100 30 0 37.28 6.11 -22.33 +325 0 0 40 0 90.59 -2.19 28.94 +326 0 10 40 0 85.01 5.94 25.01 +327 0 20 40 0 80.00 13.50 21.63 +328 0 30 40 0 75.42 20.65 18.71 +329 0 40 40 0 71.21 27.42 16.20 +330 0 55 40 0 65.70 36.74 13.23 +331 0 70 40 0 60.61 45.53 10.95 +332 0 85 40 0 56.28 53.05 9.51 +333 0 100 40 0 53.46 57.91 8.95 +334 10 0 40 0 85.53 -6.96 22.17 +335 10 10 40 0 80.36 0.76 18.73 +336 10 20 40 0 75.71 7.95 15.78 +337 10 30 40 0 71.44 14.74 13.20 +338 10 40 40 0 67.49 21.18 10.97 +339 10 55 40 0 62.38 29.97 8.27 +340 10 70 40 0 57.60 38.34 6.13 +341 10 85 40 0 53.48 45.62 4.70 +342 10 100 40 0 50.75 50.40 4.06 +343 20 0 40 0 80.94 -11.35 16.10 +344 20 10 40 0 76.16 -3.99 13.10 +345 20 20 40 0 71.83 2.85 10.52 +346 20 30 40 0 67.85 9.32 8.26 +347 20 40 40 0 64.15 15.46 6.29 +348 20 55 40 0 59.40 23.74 3.87 +349 20 70 40 0 54.93 31.70 1.88 +350 20 85 40 0 51.02 38.70 0.49 +351 20 100 40 0 48.41 43.37 -0.18 +352 30 0 40 0 76.71 -15.48 10.54 +353 30 10 40 0 72.27 -8.44 7.96 +354 30 20 40 0 68.25 -1.91 5.71 +355 30 30 40 0 64.54 4.26 3.75 +356 30 40 40 0 61.07 10.12 2.03 +357 30 55 40 0 56.69 17.92 -0.13 +358 30 70 40 0 52.52 25.46 -1.93 +359 30 85 40 0 48.84 32.17 -3.25 +360 30 100 40 0 46.35 36.68 -3.92 +361 40 0 40 0 72.77 -19.38 5.41 +362 40 10 40 0 68.66 -12.63 3.20 +363 40 20 40 0 64.92 -6.38 1.28 +364 40 30 40 0 61.46 -0.49 -0.40 +365 40 40 40 0 58.22 5.11 -1.89 +366 40 55 40 0 54.19 12.45 -3.78 +367 40 70 40 0 50.32 19.57 -5.38 +368 40 85 40 0 46.88 25.94 -6.59 +369 40 100 40 0 44.54 30.29 -7.25 +370 55 0 40 0 67.72 -24.08 -1.46 +371 55 10 40 0 64.03 -17.68 -3.18 +372 55 20 40 0 60.68 -11.76 -4.67 +373 55 30 40 0 57.55 -6.18 -5.97 +374 55 40 40 0 54.63 -0.88 -7.12 +375 55 55 40 0 50.98 6.03 -8.55 +376 55 70 40 0 47.46 12.76 -9.75 +377 55 85 40 0 44.31 18.84 -10.65 +378 55 100 40 0 42.14 23.01 -11.12 +379 70 0 40 0 62.90 -28.55 -7.94 +380 70 10 40 0 59.62 -22.48 -9.20 +381 70 20 40 0 56.62 -16.88 -10.29 +382 70 30 40 0 53.84 -11.61 -11.24 +383 70 40 40 0 51.21 -6.60 -12.06 +384 70 55 40 0 47.95 -0.13 -13.02 +385 70 70 40 0 44.78 6.19 -13.81 +386 70 85 40 0 41.93 11.92 -14.37 +387 70 100 40 0 39.95 15.88 -14.64 +388 85 0 40 0 58.63 -32.41 -13.59 +389 85 10 40 0 55.71 -26.64 -14.46 +390 85 20 40 0 53.04 -21.33 -15.20 +391 85 30 40 0 50.55 -16.34 -15.82 +392 85 40 40 0 48.20 -11.61 -16.36 +393 85 55 40 0 45.30 -5.55 -16.90 +394 85 70 40 0 42.47 0.36 -17.29 +395 85 85 40 0 39.90 5.75 -17.51 +396 85 100 40 0 38.12 9.48 -17.57 +397 100 0 40 0 55.74 -34.91 -17.35 +398 100 10 40 0 53.06 -29.37 -17.96 +399 100 20 40 0 50.61 -24.25 -18.48 +400 100 30 40 0 48.32 -19.46 -18.89 +401 100 40 40 0 46.16 -14.92 -19.23 +402 100 55 40 0 43.51 -9.18 -19.47 +403 100 70 40 0 40.92 -3.55 -19.58 +404 100 85 40 0 38.57 1.56 -19.55 +405 100 100 40 0 36.94 5.12 -19.44 +406 0 0 55 0 89.71 -2.76 41.59 +407 0 10 55 0 84.13 5.50 36.52 +408 0 20 55 0 79.14 13.19 32.10 +409 0 30 55 0 74.58 20.47 28.21 +410 0 40 55 0 70.39 27.37 24.77 +411 0 55 55 0 65.07 36.48 20.75 +412 0 70 55 0 60.15 45.10 17.39 +413 0 85 55 0 55.95 52.49 14.92 +414 0 100 55 0 53.21 57.28 13.60 +415 10 0 55 0 84.63 -7.77 34.17 +416 10 10 55 0 79.47 0.07 29.68 +417 10 20 55 0 74.83 7.37 25.75 +418 10 30 55 0 70.58 14.27 22.27 +419 10 40 55 0 66.65 20.82 19.18 +420 10 55 55 0 61.68 29.48 15.50 +421 10 70 55 0 57.03 37.74 12.35 +422 10 85 55 0 53.02 44.93 9.97 +423 10 100 55 0 50.37 49.66 8.64 +424 20 0 55 0 80.03 -12.41 27.49 +425 20 10 55 0 75.25 -4.94 23.52 +426 20 20 55 0 70.93 2.00 20.05 +427 20 30 55 0 66.97 8.57 16.95 +428 20 40 55 0 63.29 14.81 14.18 +429 20 55 55 0 58.64 23.03 10.82 +430 20 70 55 0 54.27 30.94 7.90 +431 20 85 55 0 50.45 37.89 5.63 +432 20 100 55 0 47.90 42.54 4.32 +433 30 0 55 0 75.79 -16.78 21.37 +434 30 10 55 0 71.36 -9.65 17.89 +435 30 20 55 0 67.35 -3.02 14.82 +436 30 30 55 0 63.65 3.24 12.08 +437 30 40 55 0 60.20 9.19 9.61 +438 30 55 55 0 55.88 16.99 6.59 +439 30 70 55 0 51.78 24.53 3.91 +440 30 85 55 0 48.16 31.24 1.77 +441 30 100 55 0 45.72 35.77 0.50 +442 40 0 55 0 71.84 -20.92 15.69 +443 40 10 55 0 67.74 -14.09 12.66 +444 40 20 55 0 64.01 -7.76 9.99 +445 40 30 55 0 60.56 -1.78 7.58 +446 40 40 55 0 57.34 3.91 5.41 +447 40 55 55 0 53.34 11.29 2.71 +448 40 70 55 0 49.51 18.48 0.28 +449 40 85 55 0 46.10 24.91 -1.69 +450 40 100 55 0 43.78 29.31 -2.91 +451 55 0 55 0 66.74 -25.80 8.22 +452 55 10 55 0 63.08 -19.29 5.76 +453 55 20 55 0 59.74 -13.26 3.58 +454 55 30 55 0 56.64 -7.58 1.63 +455 55 40 55 0 53.73 -2.18 -0.14 +456 55 55 55 0 50.13 4.78 -2.30 +457 55 70 55 0 46.66 11.57 -4.25 +458 55 85 55 0 43.55 17.70 -5.83 +459 55 100 55 0 41.41 21.92 -6.80 +460 70 0 55 0 61.87 -30.47 1.14 +461 70 10 55 0 58.62 -24.26 -0.79 +462 70 20 55 0 55.65 -18.53 -2.49 +463 70 30 55 0 52.89 -13.14 -4.02 +464 70 40 55 0 50.30 -8.02 -5.40 +465 70 55 55 0 47.10 -1.49 -7.01 +466 70 70 55 0 43.99 4.89 -8.46 +467 70 85 55 0 41.19 10.67 -9.62 +468 70 100 55 0 39.26 14.68 -10.34 +469 85 0 55 0 57.57 -34.54 -5.06 +470 85 10 55 0 54.68 -28.61 -6.53 +471 85 20 55 0 52.04 -23.14 -7.82 +472 85 30 55 0 49.59 -18.00 -8.98 +473 85 40 55 0 47.27 -13.13 -10.01 +474 85 55 55 0 44.44 -7.04 -11.11 +475 85 70 55 0 41.68 -1.06 -12.09 +476 85 85 55 0 39.19 4.38 -12.85 +477 85 100 55 0 37.45 8.16 -13.30 +478 100 0 55 0 54.64 -37.20 -9.23 +479 100 10 55 0 52.00 -31.47 -10.39 +480 100 20 55 0 49.59 -26.18 -11.41 +481 100 30 55 0 47.34 -21.23 -12.30 +482 100 40 55 0 45.22 -16.54 -13.10 +483 100 55 55 0 42.65 -10.75 -13.85 +484 100 70 55 0 40.14 -5.06 -14.48 +485 100 85 55 0 37.87 0.10 -14.94 +486 100 100 55 0 36.28 3.71 -15.19 +487 0 0 70 0 88.89 -2.96 53.84 +488 0 10 70 0 83.30 5.39 47.71 +489 0 20 70 0 78.31 13.18 42.32 +490 0 30 70 0 73.77 20.54 37.50 +491 0 40 70 0 69.60 27.52 33.18 +492 0 55 70 0 64.45 36.39 28.16 +493 0 70 70 0 59.68 44.80 23.75 +494 0 85 70 0 55.62 52.02 20.29 +495 0 100 70 0 52.97 56.72 18.22 +496 10 0 70 0 83.78 -8.21 45.81 +497 10 10 70 0 78.62 -0.30 40.34 +498 10 20 70 0 73.98 7.07 35.50 +499 10 30 70 0 69.74 14.05 31.16 +500 10 40 70 0 65.83 20.68 27.24 +501 10 55 70 0 60.99 29.16 22.61 +502 10 70 70 0 56.47 37.27 18.50 +503 10 85 70 0 52.57 44.34 15.19 +504 10 100 70 0 49.99 49.01 13.17 +505 20 0 70 0 79.17 -13.09 38.58 +506 20 10 70 0 74.38 -5.56 33.70 +507 20 20 70 0 70.07 1.44 29.37 +508 20 30 70 0 66.11 8.07 25.46 +509 20 40 70 0 62.44 14.38 21.92 +510 20 55 70 0 57.90 22.49 17.67 +511 20 70 70 0 53.62 30.30 13.86 +512 20 85 70 0 49.88 37.19 10.72 +513 20 100 70 0 47.39 41.80 8.77 +514 30 0 70 0 74.92 -17.70 31.92 +515 30 10 70 0 70.48 -10.52 27.60 +516 30 20 70 0 66.48 -3.85 23.74 +517 30 30 70 0 62.78 2.47 20.25 +518 30 40 70 0 59.34 8.48 17.07 +519 30 55 70 0 55.09 16.23 13.20 +520 30 70 70 0 51.04 23.74 9.67 +521 30 85 70 0 47.48 30.43 6.73 +522 30 100 70 0 45.08 34.96 4.87 +523 40 0 70 0 70.96 -22.09 25.73 +524 40 10 70 0 66.86 -15.22 21.93 +525 40 20 70 0 63.13 -8.85 18.53 +526 40 30 70 0 59.69 -2.82 15.43 +527 40 40 70 0 56.47 2.91 12.60 +528 40 55 70 0 52.50 10.32 9.10 +529 40 70 70 0 48.70 17.52 5.88 +530 40 85 70 0 45.32 23.99 3.16 +531 40 100 70 0 43.03 28.40 1.41 +532 55 0 70 0 65.81 -27.13 17.71 +533 55 10 70 0 62.15 -20.56 14.54 +534 55 20 70 0 58.83 -14.47 11.70 +535 55 30 70 0 55.74 -8.72 9.12 +536 55 40 70 0 52.85 -3.26 6.74 +537 55 55 70 0 49.29 3.71 3.87 +538 55 70 70 0 45.86 10.53 1.21 +539 55 85 70 0 42.79 16.70 -1.06 +540 55 100 70 0 40.69 20.94 -2.52 +541 70 0 70 0 60.89 -32.00 10.06 +542 70 10 70 0 57.66 -25.70 7.49 +543 70 20 70 0 54.71 -19.89 5.20 +544 70 30 70 0 51.98 -14.40 3.10 +545 70 40 70 0 49.40 -9.19 1.16 +546 70 55 70 0 46.26 -2.67 -1.07 +547 70 70 70 0 43.21 3.74 -3.16 +548 70 85 70 0 40.46 9.56 -4.93 +549 70 100 70 0 38.56 13.59 -6.08 +550 85 0 70 0 56.54 -36.28 3.33 +551 85 10 70 0 53.68 -30.23 1.28 +552 85 20 70 0 51.07 -24.65 -0.54 +553 85 30 70 0 48.65 -19.41 -2.20 +554 85 40 70 0 46.36 -14.42 -3.73 +555 85 55 70 0 43.60 -8.32 -5.39 +556 85 70 70 0 40.91 -2.31 -6.92 +557 85 85 70 0 38.48 3.15 -8.21 +558 85 100 70 0 36.78 6.95 -9.05 +559 100 0 70 0 53.58 -39.11 -1.22 +560 100 10 70 0 50.98 -33.23 -2.91 +561 100 20 70 0 48.60 -27.83 -4.42 +562 100 30 70 0 46.38 -22.74 -5.79 +563 100 40 70 0 44.30 -17.93 -7.04 +564 100 55 70 0 41.81 -12.12 -8.29 +565 100 70 70 0 39.38 -6.41 -9.42 +566 100 85 70 0 37.17 -1.22 -10.36 +567 100 100 70 0 35.64 2.40 -10.95 +568 0 0 85 0 88.16 -2.85 64.82 +569 0 10 85 0 82.57 5.54 57.79 +570 0 20 85 0 77.57 13.39 51.55 +571 0 30 85 0 73.04 20.81 45.93 +572 0 40 85 0 68.89 27.84 40.84 +573 0 55 85 0 63.89 36.46 34.94 +574 0 70 85 0 59.27 44.62 29.61 +575 0 85 85 0 55.32 51.66 25.22 +576 0 100 85 0 52.75 56.25 22.49 +577 10 0 85 0 83.04 -8.32 56.29 +578 10 10 85 0 77.86 -0.38 49.96 +579 10 20 85 0 73.22 7.03 44.34 +580 10 30 85 0 68.98 14.06 39.23 +581 10 40 85 0 65.09 20.72 34.60 +582 10 55 85 0 60.37 29.01 29.13 +583 10 70 85 0 55.95 36.95 24.14 +584 10 85 85 0 52.15 43.88 20.00 +585 10 100 85 0 49.64 48.46 17.36 +586 20 0 85 0 78.40 -13.42 48.57 +587 20 10 85 0 73.61 -5.88 42.90 +588 20 20 85 0 69.29 1.15 37.83 +589 20 30 85 0 65.34 7.82 33.22 +590 20 40 85 0 61.68 14.16 29.00 +591 20 55 85 0 57.22 22.14 23.96 +592 20 70 85 0 53.02 29.84 19.32 +593 20 85 85 0 49.36 36.62 15.41 +594 20 100 85 0 46.91 41.18 12.89 +595 30 0 85 0 74.14 -18.25 41.45 +596 30 10 85 0 69.70 -11.06 36.39 +597 30 20 85 0 65.69 -4.38 31.86 +598 30 30 85 0 61.99 1.96 27.70 +599 30 40 85 0 58.56 8.00 23.89 +600 30 55 85 0 54.36 15.68 19.27 +601 30 70 85 0 50.37 23.12 14.97 +602 30 85 85 0 46.86 29.77 11.31 +603 30 100 85 0 44.49 34.26 8.92 +604 40 0 85 0 70.17 -22.87 34.83 +605 40 10 85 0 66.07 -16.00 30.34 +606 40 20 85 0 62.34 -9.61 26.31 +607 40 30 85 0 58.90 -3.58 22.60 +608 40 40 85 0 55.69 2.17 19.19 +609 40 55 85 0 51.73 9.56 14.98 +610 40 70 85 0 47.95 16.77 11.03 +611 40 85 85 0 44.60 23.23 7.62 +612 40 100 85 0 42.32 27.65 5.38 +613 55 0 85 0 64.97 -28.05 26.32 +614 55 10 85 0 61.32 -21.46 22.53 +615 55 20 85 0 58.00 -15.34 19.12 +616 55 30 85 0 54.93 -9.56 15.96 +617 55 40 85 0 52.05 -4.06 13.05 +618 55 55 85 0 48.52 2.89 9.54 +619 55 70 85 0 45.13 9.70 6.22 +620 55 85 85 0 42.09 15.86 3.35 +621 55 100 85 0 40.01 20.11 1.44 +622 70 0 85 0 60.01 -33.09 18.18 +623 70 10 85 0 56.79 -26.75 15.05 +624 70 20 85 0 53.86 -20.89 12.23 +625 70 30 85 0 51.14 -15.35 9.62 +626 70 40 85 0 48.58 -10.09 7.21 +627 70 55 85 0 45.49 -3.58 4.39 +628 70 70 85 0 42.49 2.81 1.74 +629 70 85 85 0 39.78 8.63 -0.58 +630 70 100 85 0 37.91 12.67 -2.14 +631 85 0 85 0 55.61 -37.57 10.99 +632 85 10 85 0 52.78 -31.45 8.43 +633 85 20 85 0 50.20 -25.79 6.13 +634 85 30 85 0 47.79 -20.47 4.01 +635 85 40 85 0 45.53 -15.42 2.04 +636 85 55 85 0 42.83 -9.34 -0.11 +637 85 70 85 0 40.20 -3.35 -2.15 +638 85 85 85 0 37.82 2.12 -3.93 +639 85 100 85 0 36.16 5.94 -5.13 +640 100 0 85 0 52.63 -40.56 6.11 +641 100 10 85 0 50.05 -34.58 3.95 +642 100 20 85 0 47.70 -29.08 2.00 +643 100 30 85 0 45.51 -23.90 0.20 +644 100 40 85 0 43.45 -19.00 -1.45 +645 100 55 85 0 41.03 -13.21 -3.15 +646 100 70 85 0 38.67 -7.52 -4.74 +647 100 85 85 0 36.53 -2.33 -6.13 +648 100 100 85 0 35.04 1.31 -7.04 +649 0 0 100 0 87.66 -2.65 72.38 +650 0 10 100 0 82.06 5.78 64.76 +651 0 20 100 0 77.06 13.65 57.96 +652 0 30 100 0 72.52 21.10 51.81 +653 0 40 100 0 68.39 28.16 46.22 +654 0 55 100 0 63.50 36.57 39.70 +655 0 70 100 0 58.97 44.55 33.74 +656 0 85 100 0 55.11 51.44 28.74 +657 0 100 100 0 52.59 55.96 25.52 +658 10 0 100 0 82.52 -8.27 63.50 +659 10 10 100 0 77.33 -0.31 56.64 +660 10 20 100 0 72.69 7.12 50.49 +661 10 30 100 0 68.45 14.16 44.88 +662 10 40 100 0 64.56 20.85 39.76 +663 10 55 100 0 59.92 28.98 33.72 +664 10 70 100 0 55.59 36.78 28.13 +665 10 85 100 0 51.85 43.59 23.41 +666 10 100 100 0 49.39 48.11 20.33 +667 20 0 100 0 77.88 -13.51 55.48 +668 20 10 100 0 73.07 -5.97 49.29 +669 20 20 100 0 68.75 1.07 43.73 +670 20 30 100 0 64.80 7.74 38.65 +671 20 40 100 0 61.14 14.10 33.97 +672 20 55 100 0 56.74 21.96 28.38 +673 20 70 100 0 52.59 29.56 23.18 +674 20 85 100 0 48.98 36.27 18.73 +675 20 100 100 0 46.58 40.78 15.80 +676 30 0 100 0 73.60 -18.50 48.07 +677 30 10 100 0 69.16 -11.32 42.52 +678 30 20 100 0 65.14 -4.63 37.52 +679 30 30 100 0 61.44 1.71 32.93 +680 30 40 100 0 58.01 7.75 28.68 +681 30 55 100 0 53.84 15.36 23.55 +682 30 70 100 0 49.88 22.76 18.72 +683 30 85 100 0 46.41 29.34 14.55 +684 30 100 100 0 44.07 33.81 11.79 +685 40 0 100 0 69.63 -23.27 41.16 +686 40 10 100 0 65.52 -16.42 36.22 +687 40 20 100 0 61.79 -10.04 31.75 +688 40 30 100 0 58.34 -4.01 27.62 +689 40 40 100 0 55.13 1.74 23.81 +690 40 55 100 0 51.19 9.11 19.10 +691 40 70 100 0 47.42 16.29 14.66 +692 40 85 100 0 44.08 22.75 10.78 +693 40 100 100 0 41.82 27.15 8.20 +694 55 0 100 0 64.40 -28.54 32.33 +695 55 10 100 0 60.75 -21.95 28.12 +696 55 20 100 0 57.43 -15.83 24.31 +697 55 30 100 0 54.36 -10.05 20.78 +698 55 40 100 0 51.48 -4.54 17.49 +699 55 55 100 0 47.98 2.39 13.54 +700 55 70 100 0 44.61 9.17 9.78 +701 55 85 100 0 41.59 15.33 6.47 +702 55 100 100 0 39.53 19.57 4.25 +703 70 0 100 0 59.40 -33.69 23.86 +704 70 10 100 0 56.19 -27.34 20.36 +705 70 20 100 0 53.27 -21.45 17.17 +706 70 30 100 0 50.55 -15.90 14.21 +707 70 40 100 0 48.01 -10.62 11.47 +708 70 55 100 0 44.95 -4.14 8.27 +709 70 70 100 0 41.97 2.22 5.20 +710 70 85 100 0 39.30 8.03 2.50 +711 70 100 100 0 37.45 12.07 0.66 +712 85 0 100 0 54.97 -38.30 16.35 +713 85 10 100 0 52.15 -32.15 13.46 +714 85 20 100 0 49.58 -26.46 10.83 +715 85 30 100 0 47.19 -21.10 8.40 +716 85 40 100 0 44.94 -16.01 6.12 +717 85 55 100 0 42.28 -9.96 3.63 +718 85 70 100 0 39.69 -4.00 1.22 +719 85 85 100 0 37.35 1.45 -0.90 +720 85 100 100 0 35.72 5.26 -2.34 +721 100 0 100 0 51.97 -41.41 11.25 +722 100 10 100 0 49.41 -35.38 8.77 +723 100 20 100 0 47.07 -29.82 6.51 +724 100 30 100 0 44.90 -24.59 4.44 +725 100 40 100 0 42.86 -19.64 2.49 +726 100 55 100 0 40.49 -13.89 0.49 +727 100 70 100 0 38.17 -8.23 -1.42 +728 100 85 100 0 36.08 -3.04 -3.11 +729 100 100 100 0 34.61 0.58 -4.25 +730 0 0 0 20 79.36 2.03 -8.10 +731 0 10 0 20 74.95 7.78 -8.31 +732 0 20 0 20 70.96 13.13 -8.35 +733 0 40 0 20 63.82 22.99 -7.97 +734 0 70 0 20 54.68 36.65 -6.96 +735 0 100 0 20 48.15 46.40 -4.82 +736 10 0 0 20 75.61 -0.90 -11.96 +737 10 10 0 20 71.48 4.53 -12.03 +738 10 20 0 20 67.73 9.57 -11.96 +739 10 40 0 20 60.99 18.87 -11.45 +740 10 70 0 20 52.36 31.76 -10.17 +741 10 100 0 20 46.12 41.09 -8.02 +742 20 0 0 20 72.20 -3.57 -15.43 +743 20 10 0 20 68.31 1.57 -15.37 +744 20 20 0 20 64.78 6.33 -15.20 +745 20 40 0 20 58.42 15.11 -14.56 +746 20 70 0 20 50.28 27.27 -13.02 +747 20 100 0 20 44.31 36.19 -10.83 +748 40 0 0 20 66.02 -8.34 -21.55 +749 40 10 0 20 62.60 -3.73 -21.26 +750 40 20 0 20 59.48 0.54 -20.92 +751 40 40 0 20 53.82 8.39 -20.06 +752 40 70 0 20 46.61 19.16 -17.97 +753 40 100 0 20 41.22 27.19 -15.62 +754 70 0 0 20 57.80 -14.52 -30.30 +755 70 10 0 20 55.00 -10.44 -29.37 +756 70 20 0 20 52.44 -6.68 -28.45 +757 70 40 0 20 47.78 0.22 -26.59 +758 70 70 0 20 42.21 9.42 -23.89 +759 70 100 0 20 37.99 16.42 -21.28 +760 100 0 0 20 51.73 -18.65 -36.40 +761 100 10 0 20 49.38 -15.03 -35.04 +762 100 20 0 20 47.23 -11.69 -33.73 +763 100 40 0 20 43.30 -5.57 -31.16 +764 100 70 0 20 39.05 2.29 -28.00 +765 100 100 0 20 35.81 8.33 -25.10 +766 0 0 10 20 78.61 0.63 0.22 +767 0 10 10 20 74.20 6.53 -0.75 +768 0 20 10 20 70.22 12.00 -1.49 +769 0 40 10 20 63.10 22.10 -2.40 +770 0 70 10 20 54.20 35.88 -2.90 +771 0 100 10 20 47.85 45.74 -1.97 +772 10 0 10 20 74.81 -2.45 -3.96 +773 10 10 10 20 70.71 3.13 -4.73 +774 10 20 10 20 66.99 8.30 -5.31 +775 10 40 10 20 60.32 17.85 -5.99 +776 10 70 10 20 51.92 30.89 -6.17 +777 10 100 10 20 45.84 40.35 -5.20 +778 20 0 10 20 71.36 -5.26 -7.72 +779 20 10 10 20 67.54 0.03 -8.31 +780 20 20 10 20 64.06 4.94 -8.74 +781 20 40 10 20 57.80 13.98 -9.21 +782 20 70 10 20 49.87 26.30 -9.08 +783 20 100 10 20 44.07 35.35 -8.04 +784 40 0 10 20 65.13 -10.34 -14.38 +785 40 10 10 20 61.81 -5.55 -14.65 +786 40 20 10 20 58.77 -1.13 -14.81 +787 40 40 10 20 53.28 7.01 -14.88 +788 40 70 10 20 46.27 17.96 -14.14 +789 40 100 10 20 41.03 26.15 -12.88 +790 70 0 10 20 57.01 -16.78 -23.58 +791 70 10 10 20 54.30 -12.51 -23.19 +792 70 20 10 20 51.82 -8.57 -22.76 +793 70 40 10 20 47.31 -1.32 -21.81 +794 70 70 10 20 41.84 8.15 -20.23 +795 70 100 10 20 37.68 15.37 -18.52 +796 100 0 10 20 51.02 -21.19 -30.07 +797 100 10 10 20 48.75 -17.33 -29.23 +798 100 20 10 20 46.67 -13.78 -28.39 +799 100 40 10 20 42.89 -7.28 -26.72 +800 100 70 10 20 38.65 0.95 -24.49 +801 100 100 10 20 35.42 7.26 -22.34 +802 0 0 20 20 77.93 -0.47 7.88 +803 0 10 20 20 73.52 5.52 6.20 +804 0 20 20 20 69.54 11.09 4.82 +805 0 40 20 20 62.44 21.36 2.73 +806 0 70 20 20 53.76 35.22 0.86 +807 0 100 20 20 47.57 45.16 0.68 +808 10 0 20 20 74.09 -3.70 3.40 +809 10 10 20 20 70.02 1.99 1.99 +810 10 20 20 20 66.32 7.27 0.82 +811 10 40 20 20 59.71 17.00 -0.95 +812 10 70 20 20 51.51 30.13 -2.48 +813 10 100 20 20 45.59 39.68 -2.59 +814 20 0 20 20 70.60 -6.65 -0.63 +815 20 10 20 20 66.83 -1.24 -1.81 +816 20 20 20 20 63.40 3.77 -2.79 +817 20 40 20 20 57.23 13.02 -4.26 +818 20 70 20 20 49.50 25.44 -5.44 +819 20 100 20 20 43.84 34.59 -5.46 +820 40 0 20 20 64.32 -12.01 -7.77 +821 40 10 20 20 61.08 -7.09 -8.54 +822 40 20 20 20 58.13 -2.54 -9.17 +823 40 40 20 20 52.79 5.84 -10.10 +824 40 70 20 20 45.97 16.91 -10.59 +825 40 100 20 20 40.85 25.21 -10.33 +826 70 0 20 20 56.30 -18.70 -17.39 +827 70 10 20 20 53.67 -14.26 -17.48 +828 70 20 20 20 51.26 -10.17 -17.51 +829 70 40 20 20 46.88 -2.65 -17.40 +830 70 70 20 20 41.50 7.04 -16.83 +831 70 100 20 20 37.41 14.43 -15.96 +832 100 0 20 20 50.38 -23.36 -24.22 +833 100 10 20 20 48.18 -19.31 -23.85 +834 100 20 20 20 46.17 -15.59 -23.46 +835 100 40 20 20 42.51 -8.76 -22.59 +836 100 70 20 20 38.28 -0.23 -21.22 +837 100 100 20 20 35.05 6.31 -19.78 +838 0 0 40 20 76.72 -2.07 21.88 +839 0 10 40 20 72.31 4.05 18.94 +840 0 20 40 20 68.32 9.74 16.39 +841 0 40 40 20 61.23 20.23 12.16 +842 0 70 40 20 52.94 34.12 7.79 +843 0 100 40 20 47.06 44.14 5.58 +844 10 0 40 20 72.81 -5.56 16.87 +845 10 10 40 20 68.78 0.27 14.29 +846 10 20 40 20 65.12 5.69 12.05 +847 10 40 40 20 58.59 15.68 8.31 +848 10 70 40 20 50.77 28.85 4.35 +849 10 100 40 20 45.11 38.50 2.25 +850 20 0 40 20 69.26 -8.78 12.35 +851 20 10 40 20 65.56 -3.20 10.10 +852 20 20 40 20 62.21 1.96 8.14 +853 20 40 40 20 56.19 11.51 4.85 +854 20 70 40 20 48.82 23.99 1.29 +855 20 100 40 20 43.41 33.25 -0.67 +856 40 0 40 20 62.86 -14.67 4.32 +857 40 10 40 20 59.79 -9.55 2.65 +858 40 20 40 20 56.98 -4.80 1.18 +859 40 40 40 20 51.90 3.93 -1.30 +860 40 70 40 20 45.41 15.11 -4.03 +861 40 100 40 20 40.53 23.55 -5.62 +862 70 0 40 20 55.04 -21.77 -6.01 +863 70 10 40 20 52.55 -17.10 -6.98 +864 70 20 40 20 50.26 -12.78 -7.84 +865 70 40 40 20 46.12 -4.86 -9.23 +866 70 70 40 20 40.89 5.14 -10.55 +867 70 100 40 20 36.90 12.75 -11.20 +868 100 0 40 20 49.25 -26.89 -13.46 +869 100 10 40 20 47.18 -22.55 -13.95 +870 100 20 40 20 45.29 -18.56 -14.36 +871 100 40 40 20 41.84 -11.25 -14.98 +872 100 70 40 20 37.61 -2.24 -15.17 +873 100 100 40 20 34.37 4.65 -15.02 +874 0 0 70 20 74.77 -3.06 40.37 +875 0 10 70 20 70.51 3.15 35.90 +876 0 20 70 20 66.66 8.94 31.92 +877 0 40 70 20 59.85 19.65 25.08 +878 0 70 70 20 52.01 32.82 17.49 +879 0 100 70 20 46.41 42.41 12.57 +880 10 0 70 20 70.92 -6.83 34.43 +881 10 10 70 20 66.99 -0.93 30.43 +882 10 20 70 20 63.44 4.57 26.87 +883 10 40 70 20 57.12 14.75 20.71 +884 10 70 70 20 49.72 27.43 13.77 +885 10 100 70 20 44.36 36.79 9.18 +886 20 0 70 20 67.42 -10.33 29.04 +887 20 10 70 20 63.80 -4.69 25.49 +888 20 20 70 20 60.53 0.55 22.30 +889 20 40 70 20 54.66 10.25 16.76 +890 20 70 70 20 47.67 22.45 10.45 +891 20 100 70 20 42.54 31.57 6.20 +892 40 0 70 20 61.14 -16.75 19.42 +893 40 10 70 20 58.08 -11.59 16.64 +894 40 20 70 20 55.29 -6.80 14.14 +895 40 40 70 20 50.26 2.04 9.75 +896 40 70 70 20 44.07 13.33 4.65 +897 40 100 70 20 39.44 21.90 1.13 +898 70 0 70 20 53.36 -24.18 7.46 +899 70 10 70 20 50.92 -19.43 5.59 +900 70 20 70 20 48.68 -15.03 3.91 +901 70 40 70 20 44.62 -6.96 0.94 +902 70 70 70 20 39.75 3.10 -2.24 +903 70 100 70 20 36.03 10.86 -4.43 +904 100 0 70 20 47.61 -29.64 -1.32 +905 100 10 70 20 45.61 -25.18 -2.54 +906 100 20 70 20 43.77 -21.08 -3.63 +907 100 40 70 20 40.45 -13.56 -5.53 +908 100 70 70 20 36.62 -4.51 -7.18 +909 100 100 70 20 33.68 2.47 -8.23 +910 0 0 100 20 73.29 -3.19 54.36 +911 0 10 100 20 69.13 3.02 48.81 +912 0 20 100 20 65.39 8.82 43.84 +913 0 40 100 20 58.78 19.57 35.09 +914 0 70 100 20 51.28 31.99 25.11 +915 0 100 100 20 45.90 41.12 18.09 +916 10 0 100 20 69.48 -7.20 47.79 +917 10 10 100 20 65.63 -1.31 42.78 +918 10 20 100 20 62.15 4.20 38.28 +919 10 40 100 20 55.99 14.40 30.33 +920 10 70 100 20 48.89 26.53 21.16 +921 10 100 100 20 43.75 35.54 14.67 +922 20 0 100 20 66.02 -10.92 41.81 +923 20 10 100 20 62.46 -5.31 37.31 +924 20 20 100 20 59.22 -0.07 33.24 +925 20 40 100 20 53.46 9.63 26.03 +926 20 70 100 20 46.76 21.46 17.64 +927 20 100 100 20 41.85 30.35 11.64 +928 40 0 100 20 59.83 -17.80 31.04 +929 40 10 100 20 56.77 -12.67 27.46 +930 40 20 100 20 53.99 -7.90 24.20 +931 40 40 100 20 48.98 0.92 18.37 +932 40 70 100 20 43.01 12.17 11.48 +933 40 100 100 20 38.56 20.76 6.46 +934 70 0 100 20 52.08 -25.47 17.93 +935 70 10 100 20 49.67 -20.72 15.39 +936 70 20 100 20 47.46 -16.32 13.08 +937 70 40 100 20 43.45 -8.23 8.93 +938 70 70 100 20 38.84 1.77 4.32 +939 70 100 100 20 35.34 9.53 0.93 +940 100 0 100 20 46.35 -31.21 8.19 +941 100 10 100 20 44.39 -26.72 6.41 +942 100 20 100 20 42.61 -22.59 4.81 +943 100 40 100 20 39.36 -15.00 1.93 +944 100 70 100 20 35.84 -6.03 -0.84 +945 100 100 100 20 33.14 0.95 -2.83 +946 0 0 0 40 66.75 1.60 -6.39 +947 0 20 0 40 60.42 9.67 -6.27 +948 0 40 0 40 54.96 16.86 -5.81 +949 0 70 0 40 47.98 26.68 -5.51 +950 0 100 0 40 42.76 33.96 -4.58 +951 20 0 0 40 61.38 -2.76 -11.01 +952 20 20 0 40 55.83 4.59 -10.77 +953 20 40 0 40 51.02 11.11 -10.30 +954 20 70 0 40 44.81 20.17 -9.61 +955 20 100 0 40 40.13 26.98 -8.53 +956 40 0 0 40 56.70 -6.57 -14.89 +957 40 20 0 40 51.84 0.17 -14.57 +958 40 40 0 40 47.61 6.13 -14.09 +959 40 70 0 40 42.12 14.49 -13.05 +960 40 100 0 40 37.93 20.83 -11.79 +961 70 0 0 40 50.38 -11.37 -21.24 +962 70 20 0 40 46.34 -5.23 -20.05 +963 70 40 0 40 42.81 0.16 -18.84 +964 70 70 0 40 38.57 7.48 -17.40 +965 70 100 0 40 35.31 13.10 -15.93 +966 100 0 0 40 45.61 -14.85 -25.81 +967 100 20 0 40 42.17 -9.20 -24.02 +968 100 40 0 40 39.16 -4.24 -22.28 +969 100 70 0 40 35.92 2.20 -20.53 +970 100 100 0 40 33.42 7.19 -18.88 +971 0 0 20 40 65.47 -0.48 5.38 +972 0 20 20 40 59.08 7.86 3.36 +973 0 40 20 40 53.58 15.25 1.93 +974 0 70 20 40 47.06 25.24 0.26 +975 0 100 20 40 42.20 32.70 -0.40 +976 20 0 20 40 60.00 -4.95 -0.33 +977 20 20 20 40 54.63 2.66 -1.83 +978 20 40 20 40 49.97 9.41 -2.90 +979 20 70 20 40 44.06 18.55 -4.01 +980 20 100 20 40 39.59 25.46 -4.39 +981 40 0 20 40 55.25 -8.86 -5.17 +982 40 20 20 40 50.76 -1.87 -6.25 +983 40 40 20 40 46.86 4.31 -7.01 +984 40 70 20 40 41.52 12.67 -7.58 +985 40 100 20 40 37.43 19.04 -7.65 +986 70 0 20 40 49.12 -13.93 -12.19 +987 70 20 20 40 45.39 -7.47 -12.37 +988 70 40 20 40 42.12 -1.78 -12.39 +989 70 70 20 40 37.93 5.67 -12.20 +990 70 100 20 40 34.69 11.41 -11.77 +991 100 0 20 40 44.49 -17.65 -17.31 +992 100 20 20 40 41.30 -11.61 -16.87 +993 100 40 20 40 38.53 -6.30 -16.34 +994 100 70 20 40 35.24 0.42 -15.56 +995 100 100 20 40 32.70 5.62 -14.72 +996 0 0 40 40 64.36 -1.94 15.73 +997 0 20 40 40 57.90 6.51 11.84 +998 0 40 40 40 52.36 14.01 8.75 +999 0 70 40 40 46.24 24.06 5.38 +1000 0 100 40 40 41.70 31.63 3.33 +1001 20 0 40 40 58.80 -6.53 9.08 +1002 20 20 40 40 53.58 1.20 6.07 +1003 20 40 40 40 49.05 8.07 3.65 +1004 20 70 40 40 43.39 17.20 0.98 +1005 20 100 40 40 39.11 24.15 -0.68 +1006 40 0 40 40 53.99 -10.57 3.41 +1007 40 20 40 40 49.82 -3.45 1.14 +1008 40 40 40 40 46.20 2.87 -0.72 +1009 40 70 40 40 40.99 11.16 -2.71 +1010 40 100 40 40 36.98 17.51 -3.96 +1011 70 0 40 40 48.02 -15.86 -4.18 +1012 70 20 40 40 44.55 -9.21 -5.56 +1013 70 40 40 40 41.52 -3.34 -6.65 +1014 70 70 40 40 37.36 4.18 -7.57 +1015 70 100 40 40 34.13 9.98 -8.06 +1016 100 0 40 40 43.51 -19.79 -9.78 +1017 100 20 40 40 40.55 -13.50 -10.51 +1018 100 40 40 40 37.97 -7.97 -11.04 +1019 100 70 40 40 34.64 -1.06 -11.13 +1020 100 100 40 40 32.05 4.27 -10.99 +1021 0 0 70 40 62.23 -3.04 28.54 +1022 0 20 70 40 56.29 5.38 22.83 +1023 0 40 70 40 51.20 12.89 18.08 +1024 0 70 70 40 45.35 22.29 12.39 +1025 0 100 70 40 40.98 29.42 8.38 +1026 20 0 70 40 56.93 -7.84 20.64 +1027 20 20 70 40 51.97 -0.15 16.08 +1028 20 40 70 40 47.68 6.72 12.26 +1029 20 70 70 40 42.41 15.57 7.65 +1030 20 100 70 40 38.41 22.37 4.38 +1031 40 0 70 40 52.35 -12.07 13.84 +1032 40 20 70 40 48.24 -4.98 10.27 +1033 40 40 70 40 44.66 1.32 7.26 +1034 40 70 70 40 39.91 9.65 3.65 +1035 40 100 70 40 36.28 16.10 1.08 +1036 70 0 70 40 46.63 -17.38 5.25 +1037 70 20 70 40 43.25 -10.82 2.83 +1038 70 40 70 40 40.30 -5.01 0.79 +1039 70 70 70 40 36.60 2.53 -1.37 +1040 70 100 70 40 33.74 8.40 -2.89 +1041 100 0 70 40 42.31 -21.38 -1.20 +1042 100 20 70 40 39.47 -15.19 -2.77 +1043 100 40 70 40 36.99 -9.75 -4.05 +1044 100 70 70 40 34.12 -2.84 -5.09 +1045 100 100 70 40 31.91 2.53 -5.72 +1046 0 0 100 40 60.56 -3.52 38.39 +1047 0 20 100 40 55.02 4.78 31.35 +1048 0 40 100 40 50.29 12.24 25.39 +1049 0 70 100 40 44.65 21.00 17.93 +1050 0 100 100 40 40.40 27.71 12.38 +1051 20 0 100 40 55.47 -8.52 29.61 +1052 20 20 100 40 50.71 -0.93 23.89 +1053 20 40 100 40 46.60 5.87 19.01 +1054 20 70 100 40 41.63 14.40 12.94 +1055 20 100 100 40 37.85 21.01 8.41 +1056 40 0 100 40 51.06 -12.93 22.00 +1057 40 20 100 40 46.98 -5.93 17.43 +1058 40 40 100 40 43.43 0.30 13.52 +1059 40 70 100 40 39.05 8.59 8.70 +1060 40 100 100 40 35.71 15.06 5.10 +1061 70 0 100 40 45.55 -18.28 12.67 +1062 70 20 100 40 42.23 -11.83 9.44 +1063 70 40 100 40 39.33 -6.12 6.68 +1064 70 70 100 40 36.00 1.38 3.57 +1065 70 100 100 40 33.43 7.26 1.25 +1066 100 0 100 40 41.38 -22.32 5.60 +1067 100 20 100 40 38.63 -16.27 3.38 +1068 100 40 100 40 36.21 -10.94 1.50 +1069 100 70 100 40 33.72 -4.11 -0.24 +1070 100 100 100 40 31.80 1.25 -1.49 +1071 0 0 0 60 54.52 1.49 -4.08 +1072 0 20 0 60 50.60 7.24 -3.86 +1073 0 40 0 60 47.18 12.39 -3.47 +1074 0 70 0 60 42.00 19.32 -3.15 +1075 0 100 0 60 38.02 24.59 -2.51 +1076 20 0 0 60 50.85 -1.53 -7.37 +1077 20 20 0 60 47.25 3.71 -7.07 +1078 20 40 0 60 44.10 8.38 -6.65 +1079 20 70 0 60 39.68 14.80 -5.95 +1080 20 100 0 60 36.25 19.73 -5.10 +1081 40 0 0 60 47.62 -4.19 -10.19 +1082 40 20 0 60 44.31 0.61 -9.82 +1083 40 40 0 60 41.41 4.88 -9.36 +1084 40 70 0 60 37.66 10.82 -8.34 +1085 40 100 0 60 34.75 15.43 -7.28 +1086 70 0 0 60 43.30 -7.63 -14.70 +1087 70 20 0 60 40.52 -3.23 -13.73 +1088 70 40 0 60 38.07 0.66 -12.77 +1089 70 70 0 60 35.16 5.91 -11.45 +1090 70 100 0 60 32.88 10.02 -10.20 +1091 100 0 0 60 39.97 -10.24 -18.06 +1092 100 20 0 60 37.58 -6.16 -16.67 +1093 100 40 0 60 35.49 -2.56 -15.34 +1094 100 70 0 60 33.24 2.14 -13.78 +1095 100 100 0 60 31.49 5.81 -12.36 +1096 0 0 20 60 53.78 -0.05 3.94 +1097 0 20 20 60 49.60 5.81 2.72 +1098 0 40 20 60 45.96 11.05 1.82 +1099 0 70 20 60 41.37 18.15 0.80 +1100 0 100 20 60 37.85 23.63 0.32 +1101 20 0 20 60 50.07 -3.14 -0.02 +1102 20 20 20 60 46.46 2.25 -0.90 +1103 20 40 20 60 43.31 7.05 -1.55 +1104 20 70 20 60 39.17 13.56 -2.11 +1105 20 100 20 60 35.97 18.58 -2.29 +1106 40 0 20 60 46.81 -5.86 -3.43 +1107 40 20 20 60 43.71 -0.87 -4.03 +1108 40 40 20 60 40.99 3.56 -4.45 +1109 40 70 20 60 37.27 9.49 -4.59 +1110 40 100 20 60 34.37 14.12 -4.49 +1111 70 0 20 60 42.46 -9.38 -8.40 +1112 70 20 20 60 39.90 -4.78 -8.38 +1113 70 40 20 60 37.65 -0.70 -8.27 +1114 70 70 20 60 34.72 4.62 -7.87 +1115 70 100 20 60 32.41 8.78 -7.38 +1116 100 0 20 60 39.10 -12.05 -12.15 +1117 100 20 20 60 36.96 -7.75 -11.68 +1118 100 40 20 60 35.07 -3.95 -11.17 +1119 100 70 20 60 32.76 0.88 -10.34 +1120 100 100 20 60 30.94 4.66 -9.53 +1121 0 0 40 60 53.14 -1.23 11.06 +1122 0 20 40 60 48.72 4.68 8.55 +1123 0 40 40 60 44.86 9.94 6.51 +1124 0 70 40 60 40.81 17.16 4.32 +1125 0 100 40 60 37.70 22.77 2.87 +1126 20 0 40 60 49.39 -4.39 6.51 +1127 20 20 40 60 45.77 1.09 4.58 +1128 20 40 40 60 42.59 5.97 3.00 +1129 20 70 40 60 38.72 12.48 1.33 +1130 20 100 40 60 35.72 17.56 0.23 +1131 40 0 40 60 46.10 -7.18 2.58 +1132 40 20 40 60 43.18 -2.08 1.13 +1133 40 40 40 60 40.62 2.47 -0.05 +1134 40 70 40 60 36.93 8.36 -1.23 +1135 40 100 40 60 34.03 12.96 -1.99 +1136 70 0 40 60 41.72 -10.76 -2.81 +1137 70 20 40 60 39.36 -6.02 -3.61 +1138 70 40 40 60 37.29 -1.83 -4.24 +1139 70 70 40 60 34.32 3.52 -4.66 +1140 70 100 40 60 31.99 7.70 -4.85 +1141 100 0 40 60 38.33 -13.49 -6.88 +1142 100 20 40 60 36.40 -9.04 -7.21 +1143 100 40 40 60 34.71 -5.10 -7.42 +1144 100 70 40 60 32.32 -0.20 -7.26 +1145 100 100 40 60 30.45 3.64 -6.99 +1146 0 0 70 60 51.70 -2.29 19.92 +1147 0 20 70 60 47.66 3.61 16.19 +1148 0 40 70 60 44.15 8.91 13.06 +1149 0 70 70 60 39.95 15.64 9.18 +1150 0 100 70 60 36.71 20.89 6.33 +1151 20 0 70 60 48.05 -5.53 14.50 +1152 20 20 70 60 44.63 -0.09 11.56 +1153 20 40 70 60 41.64 4.77 9.05 +1154 20 70 70 60 37.85 11.09 5.96 +1155 20 100 70 60 34.91 16.04 3.68 +1156 40 0 70 60 44.85 -8.38 9.78 +1157 40 20 70 60 41.98 -3.35 7.51 +1158 40 40 70 60 39.45 1.14 5.57 +1159 40 70 70 60 36.04 7.08 3.19 +1160 40 100 70 60 33.38 11.74 1.43 +1161 70 0 70 60 40.76 -11.97 3.82 +1162 70 20 70 60 38.43 -7.32 2.30 +1163 70 40 70 60 36.38 -3.18 1.02 +1164 70 70 70 60 33.67 2.21 -0.37 +1165 70 100 70 60 31.54 6.44 -1.34 +1166 100 0 70 60 37.61 -14.72 -0.75 +1167 100 20 70 60 35.69 -10.34 -1.70 +1168 100 40 70 60 34.00 -6.46 -2.48 +1169 100 70 70 60 31.85 -1.54 -3.05 +1170 100 100 70 60 30.15 2.35 -3.41 +1171 0 0 100 60 50.56 -2.90 26.86 +1172 0 20 100 60 46.82 2.94 22.22 +1173 0 40 100 60 43.58 8.21 18.25 +1174 0 70 100 60 39.26 14.50 13.05 +1175 0 100 100 60 35.91 19.39 9.09 +1176 20 0 100 60 46.98 -6.23 20.79 +1177 20 20 100 60 43.72 -0.88 17.06 +1178 20 40 100 60 40.87 3.93 13.86 +1179 20 70 100 60 37.15 10.04 9.65 +1180 20 100 100 60 34.26 14.83 6.43 +1181 40 0 100 60 43.85 -9.17 15.49 +1182 40 20 100 60 41.01 -4.24 12.56 +1183 40 40 100 60 38.51 0.18 10.03 +1184 40 70 100 60 35.33 6.11 6.71 +1185 40 100 100 60 32.85 10.80 4.17 +1186 70 0 100 60 40.01 -12.77 9.09 +1187 70 20 100 60 37.69 -8.20 7.00 +1188 70 40 100 60 35.65 -4.15 5.21 +1189 70 70 100 60 33.14 1.23 3.08 +1190 70 100 100 60 31.17 5.48 1.47 +1191 100 0 100 60 37.05 -15.55 4.15 +1192 100 20 100 60 35.13 -11.26 2.72 +1193 100 40 100 60 33.44 -7.46 1.49 +1194 100 70 100 60 31.47 -2.53 0.32 +1195 100 100 100 60 29.92 1.36 -0.52 +1196 0 0 0 80 42.14 1.38 -1.76 +1197 0 40 0 80 39.20 7.94 -1.09 +1198 0 70 0 80 35.92 11.91 -0.55 +1199 0 100 0 80 33.33 15.01 -0.01 +1200 40 0 0 80 38.37 -1.82 -5.43 +1201 40 40 0 80 35.03 3.64 -4.55 +1202 40 70 0 80 33.06 7.15 -3.49 +1203 40 100 0 80 31.52 9.93 -2.54 +1204 70 0 0 80 36.11 -3.79 -7.95 +1205 70 40 0 80 33.21 1.25 -6.53 +1206 70 70 0 80 31.62 4.44 -5.33 +1207 70 100 0 80 30.37 6.98 -4.26 +1208 100 0 0 80 34.33 -5.37 -9.91 +1209 100 40 0 80 31.76 -0.65 -8.07 +1210 100 70 0 80 30.49 2.29 -6.75 +1211 100 100 0 80 29.49 4.62 -5.58 +1212 0 0 40 80 41.75 -0.52 6.46 +1213 0 40 40 80 37.20 5.94 4.35 +1214 0 70 40 80 35.29 10.23 3.46 +1215 0 100 40 80 33.79 13.68 2.84 +1216 40 0 40 80 38.03 -3.84 1.81 +1217 40 40 40 80 34.84 2.05 0.69 +1218 40 70 40 80 32.71 5.54 0.36 +1219 40 100 40 80 31.02 8.31 0.19 +1220 70 0 40 80 35.27 -5.73 -1.27 +1221 70 40 40 80 32.90 -0.32 -1.70 +1222 70 70 40 80 31.16 2.85 -1.63 +1223 70 100 40 80 29.76 5.37 -1.49 +1224 100 0 40 80 33.09 -7.21 -3.66 +1225 100 40 40 80 31.37 -2.19 -3.56 +1226 100 70 40 80 29.93 0.74 -3.18 +1227 100 100 40 80 28.78 3.06 -2.80 +1228 0 0 70 80 41.00 -1.42 11.31 +1229 0 40 70 80 36.93 5.04 8.07 +1230 0 70 70 80 34.47 9.01 6.15 +1231 0 100 70 80 32.52 12.21 4.67 +1232 40 0 70 80 37.15 -4.71 5.72 +1233 40 40 70 80 34.05 0.97 3.88 +1234 40 70 70 80 32.03 4.49 2.78 +1235 40 100 70 80 30.42 7.29 1.95 +1236 70 0 70 80 34.75 -6.63 2.48 +1237 70 40 70 80 32.31 -1.37 1.31 +1238 70 70 70 80 30.61 1.86 0.72 +1239 70 100 70 80 29.24 4.44 0.31 +1240 100 0 70 80 32.84 -8.14 -0.07 +1241 100 40 70 80 30.93 -3.19 -0.73 +1242 100 70 70 80 29.48 -0.22 -0.89 +1243 100 100 70 80 28.32 2.16 -0.96 +1244 0 0 100 80 40.40 -2.08 15.17 +1245 0 40 100 80 36.72 4.36 11.06 +1246 0 70 100 80 33.81 8.06 8.30 +1247 0 100 100 80 31.49 11.01 6.15 +1248 40 0 100 80 36.45 -5.36 8.88 +1249 40 40 100 80 33.41 0.13 6.45 +1250 40 70 100 80 31.48 3.65 4.74 +1251 40 100 100 80 29.93 6.48 3.38 +1252 70 0 100 80 34.33 -7.31 5.50 +1253 70 40 100 80 31.83 -2.17 3.72 +1254 70 70 100 80 30.16 1.07 2.62 +1255 70 100 100 80 28.81 3.66 1.76 +1256 100 0 100 80 32.64 -8.84 2.85 +1257 100 40 100 80 30.57 -3.98 1.56 +1258 100 70 100 80 29.11 -0.97 0.96 +1259 100 100 100 80 27.93 1.44 0.49 +1260 0 0 0 100 32.69 1.24 0.11 +1261 0 40 0 100 33.02 4.60 0.85 +1262 0 100 0 100 29.84 7.72 2.31 +1263 40 0 0 100 31.27 -0.08 -1.70 +1264 40 40 0 100 30.06 2.72 -0.80 +1265 40 100 0 100 29.01 5.74 1.26 +1266 100 0 0 100 30.08 -1.53 -3.38 +1267 100 40 0 100 28.90 0.97 -2.30 +1268 100 100 0 100 27.93 3.85 -0.23 +1269 0 0 40 100 33.03 0.02 3.17 +1270 0 40 40 100 31.27 2.99 2.86 +1271 0 100 40 100 30.91 6.74 3.22 +1272 40 0 40 100 31.77 -1.40 1.34 +1273 40 40 40 100 30.32 1.70 1.32 +1274 40 100 40 100 28.67 4.75 2.00 +1275 100 0 40 100 29.11 -2.55 -0.93 +1276 100 40 40 100 28.78 0.03 -0.42 +1277 100 100 40 100 27.46 2.65 0.55 +1278 0 0 100 100 32.62 -1.23 6.32 +1279 0 40 100 100 31.43 1.66 5.61 +1280 0 100 100 100 28.21 4.77 4.26 +1281 40 0 100 100 30.73 -2.44 3.83 +1282 40 40 100 100 29.42 0.14 3.72 +1283 40 100 100 100 27.68 3.22 2.91 +1284 100 0 100 100 29.26 -3.87 1.98 +1285 100 40 100 100 28.33 -1.37 1.71 +1286 100 100 100 100 26.36 1.50 1.35 +1287 100 0 0 0 58.70 -22.35 -48.12 +1288 98 0 0 0 59.01 -22.19 -47.82 +1289 95 0 0 0 59.47 -21.94 -47.37 +1290 90 0 0 0 60.41 -21.42 -46.43 +1291 85 0 0 0 61.71 -20.66 -45.11 +1292 80 0 0 0 63.03 -19.85 -43.73 +1293 75 0 0 0 64.56 -18.87 -42.12 +1294 70 0 0 0 66.13 -17.82 -40.45 +1295 60 0 0 0 69.47 -15.49 -36.84 +1296 50 0 0 0 72.89 -12.97 -33.07 +1297 40 0 0 0 76.45 -10.28 -29.09 +1298 30 0 0 0 80.24 -7.50 -24.94 +1299 25 0 0 0 82.25 -6.00 -22.71 +1300 20 0 0 0 84.29 -4.47 -20.44 +1301 15 0 0 0 86.46 -2.83 -18.00 +1302 10 0 0 0 88.67 -1.16 -15.51 +1303 7 0 0 0 90.11 -0.07 -13.87 +1304 5 0 0 0 91.08 0.66 -12.77 +1305 3 0 0 0 92.04 1.39 -11.67 +1306 2 0 0 0 92.53 1.76 -11.12 +1307 0 100 0 0 54.54 60.07 -4.30 +1308 0 98 0 0 54.84 59.61 -4.52 +1309 0 95 0 0 55.31 58.89 -4.85 +1310 0 90 0 0 56.27 57.40 -5.47 +1311 0 85 0 0 57.60 55.31 -6.22 +1312 0 80 0 0 58.99 53.12 -6.91 +1313 0 75 0 0 60.61 50.56 -7.61 +1314 0 70 0 0 62.30 47.89 -8.22 +1315 0 60 0 0 65.93 42.15 -9.23 +1316 0 50 0 0 69.73 36.19 -9.91 +1317 0 40 0 0 73.74 30.00 -10.32 +1318 0 30 0 0 78.06 23.70 -10.61 +1319 0 25 0 0 80.38 20.40 -10.66 +1320 0 20 0 0 82.74 17.07 -10.66 +1321 0 15 0 0 85.26 13.57 -10.59 +1322 0 10 0 0 87.84 10.05 -10.46 +1323 0 7 0 0 89.52 7.78 -10.35 +1324 0 5 0 0 90.66 6.26 -10.26 +1325 0 3 0 0 91.79 4.76 -10.16 +1326 0 2 0 0 92.36 4.01 -10.11 +1327 0 0 100 0 87.66 -2.65 72.38 +1328 0 0 98 0 87.71 -2.67 71.61 +1329 0 0 95 0 87.79 -2.71 70.44 +1330 0 0 90 0 87.95 -2.77 68.05 +1331 0 0 85 0 88.16 -2.85 64.82 +1332 0 0 80 0 88.38 -2.91 61.53 +1333 0 0 75 0 88.63 -2.95 57.72 +1334 0 0 70 0 88.89 -2.96 53.84 +1335 0 0 60 0 89.43 -2.86 45.69 +1336 0 0 50 0 90.00 -2.61 37.42 +1337 0 0 40 0 90.59 -2.19 28.94 +1338 0 0 30 0 91.22 -1.45 20.12 +1339 0 0 25 0 91.55 -0.99 15.48 +1340 0 0 20 0 91.90 -0.46 10.79 +1341 0 0 15 0 92.27 0.15 5.84 +1342 0 0 10 0 92.65 0.82 0.84 +1343 0 0 7 0 92.90 1.29 -2.41 +1344 0 0 5 0 93.07 1.62 -4.58 +1345 0 0 3 0 93.24 1.96 -6.74 +1346 0 0 2 0 93.33 2.14 -7.83 +1347 0 0 0 100 32.69 1.24 0.11 +1348 0 0 0 98 33.41 1.25 -0.04 +1349 0 0 0 95 34.48 1.28 -0.28 +1350 0 0 0 90 36.58 1.31 -0.70 +1351 0 0 0 85 39.33 1.34 -1.23 +1352 0 0 0 80 42.14 1.38 -1.76 +1353 0 0 0 75 45.19 1.40 -2.33 +1354 0 0 0 70 48.31 1.44 -2.91 +1355 0 0 0 60 54.52 1.49 -4.08 +1356 0 0 0 50 60.65 1.55 -5.23 +1357 0 0 0 40 66.75 1.60 -6.39 +1358 0 0 0 30 72.92 1.81 -7.22 +1359 0 0 0 25 76.13 1.92 -7.66 +1360 0 0 0 20 79.36 2.03 -8.10 +1361 0 0 0 15 82.74 2.14 -8.55 +1362 0 0 0 10 86.16 2.25 -9.01 +1363 0 0 0 7 88.36 2.33 -9.31 +1364 0 0 0 5 89.84 2.38 -9.51 +1365 0 0 0 3 91.30 2.42 -9.70 +1366 0 0 0 2 92.03 2.45 -9.80 +1367 0 0 0 0 93.50 2.50 -10.00 +1368 100 85 85 0 36.53 -2.33 -6.13 +1369 80 65 65 0 42.78 -2.14 -7.05 +1370 60 45 45 0 51.99 -1.00 -7.01 +1371 40 27 27 0 63.31 -0.49 -8.22 +1372 20 12 12 0 77.32 1.07 -9.52 +1373 10 6 6 0 84.94 1.93 -9.69 +1374 5 3 3 0 89.15 2.29 -9.77 +1375 40 27 27 10 59.43 -0.41 -7.08 +1376 20 12 12 10 71.80 0.91 -8.28 +1377 10 6 6 10 78.56 1.68 -8.53 +1378 60 45 45 20 46.79 -0.60 -5.29 +1379 40 27 27 20 55.82 -0.34 -6.02 +1380 20 12 12 20 66.69 0.75 -7.12 +1381 10 6 6 20 72.66 1.46 -7.47 +1382 80 65 65 40 36.25 -0.61 -3.70 +1383 60 45 45 40 42.09 -0.28 -3.71 +1384 40 27 27 40 49.05 -0.22 -4.04 +1385 20 12 12 40 57.16 0.48 -4.97 +1386 10 6 6 40 61.67 1.04 -5.49 +1387 100 85 85 60 30.68 0.14 -1.47 +1388 80 65 65 60 33.43 0.03 -2.04 +1389 60 45 45 60 37.69 0.30 -2.11 +1390 40 27 27 60 42.56 0.29 -2.44 +1391 20 12 12 60 48.14 0.74 -3.13 +1392 10 6 6 60 51.18 1.12 -3.48 +1393 100 85 85 80 28.59 0.75 0.00 +1394 80 65 65 80 30.50 0.66 -0.29 +1395 60 45 45 80 33.13 0.84 -0.43 +1396 40 27 27 80 35.87 0.77 -0.77 +1397 20 12 12 80 38.92 0.98 -1.24 +1398 10 6 6 80 40.50 1.19 -1.45 +1399 100 85 85 100 26.92 1.19 1.21 +1400 80 65 65 100 28.18 1.11 1.17 +1401 60 45 45 100 29.54 1.21 0.94 +1402 40 27 27 100 30.65 1.11 0.58 +1403 20 12 12 100 31.80 1.11 0.29 +1404 10 6 6 100 32.30 1.20 0.20 +1405 100 0 0 70 37.13 -7.82 -14.02 +1406 0 100 0 70 35.65 19.79 -1.31 +1407 0 0 100 70 45.47 -2.51 20.99 +1408 100 100 0 70 30.49 5.19 -8.99 +1409 100 0 100 70 34.84 -12.16 3.48 +1410 0 100 100 70 33.68 15.17 7.55 +1411 40 40 0 70 38.22 4.25 -6.95 +1412 40 0 40 70 42.06 -5.49 2.18 +1413 0 40 40 70 41.03 7.91 5.42 +1414 3 3 0 0 90.36 3.61 -11.81 +1415 3 0 3 0 91.78 0.83 -8.44 +1416 0 3 3 0 91.53 4.24 -6.99 +1417 3 3 3 0 90.10 3.06 -8.67 +1418 3 0 0 3 89.89 1.35 -11.29 +1419 0 3 0 3 89.64 4.60 -9.85 +1420 3 3 0 3 88.27 3.49 -11.42 +1421 0 0 3 3 91.04 1.91 -6.56 +1422 3 0 3 3 89.63 0.81 -8.19 +1423 0 3 3 3 89.39 4.10 -6.80 +1424 3 3 3 3 88.01 2.96 -8.40 +1425 7 7 0 0 86.30 4.97 -14.09 +1426 7 0 7 0 89.48 -1.43 -6.45 +1427 0 7 7 0 88.94 6.68 -3.24 +1428 7 7 7 0 85.70 3.73 -7.13 +1429 7 0 0 7 85.25 -0.05 -12.76 +1430 0 7 0 7 84.70 7.15 -9.59 +1431 7 7 0 7 81.75 4.56 -12.93 +1432 0 0 7 7 87.79 1.20 -2.36 +1433 7 0 7 7 84.65 -1.31 -5.98 +1434 0 7 7 7 84.14 6.11 -3.09 +1435 7 7 7 7 81.17 3.40 -6.57 +1436 40 3 0 0 75.11 -8.52 -28.96 +1437 3 40 0 0 72.61 28.36 -11.77 +1438 40 0 3 0 76.13 -11.19 -26.21 +1439 40 3 3 0 74.80 -9.40 -26.15 +1440 0 40 3 0 73.52 29.71 -8.11 +1441 3 40 3 0 72.40 28.05 -9.57 +1442 40 40 3 0 60.49 10.41 -24.69 +1443 3 0 40 0 89.06 -3.62 26.89 +1444 0 3 40 0 88.90 0.24 27.73 +1445 3 3 40 0 87.40 -1.23 25.73 +1446 40 3 40 0 71.53 -17.36 4.73 +1447 3 40 40 0 70.08 25.54 14.61 +1448 40 0 0 3 74.83 -9.99 -27.91 +1449 40 3 0 3 73.54 -8.29 -27.79 +1450 0 40 0 3 72.20 28.90 -9.96 +1451 3 40 0 3 71.11 27.33 -11.34 +1452 40 40 0 3 59.64 10.58 -25.71 +1453 40 0 3 3 74.51 -10.84 -25.14 +1454 40 3 3 3 73.23 -9.12 -25.09 +1455 0 40 3 3 71.98 28.61 -7.83 +1456 3 40 3 3 70.90 27.01 -9.23 +1457 40 40 3 3 59.43 10.03 -23.73 +1458 0 0 40 3 88.43 -2.17 27.83 +1459 3 0 40 3 86.95 -3.55 25.86 +1460 40 0 40 3 71.23 -18.64 5.23 +1461 0 3 40 3 86.79 0.16 26.67 +1462 3 3 40 3 85.35 -1.24 24.75 +1463 40 3 40 3 70.04 -16.69 4.58 +1464 0 40 40 3 69.65 26.29 15.56 +1465 3 40 40 3 68.58 24.49 14.04 +1466 40 40 40 3 57.24 4.93 -1.80 +1467 3 0 0 40 65.91 0.92 -7.12 +1468 0 3 0 40 65.75 2.85 -6.39 +1469 3 3 0 40 64.93 2.16 -7.12 +1470 40 3 0 40 55.93 -5.52 -14.86 +1471 3 40 0 40 54.34 15.95 -6.52 +1472 0 0 3 40 66.55 1.24 -4.55 +1473 3 0 3 40 65.70 0.56 -5.31 +1474 40 0 3 40 56.47 -6.96 -13.37 +1475 0 3 3 40 65.55 2.51 -4.61 +1476 3 3 3 40 64.72 1.80 -5.36 +1477 40 3 3 40 55.72 -5.90 -13.37 +1478 0 40 3 40 54.75 16.59 -4.60 +1479 3 40 3 40 54.14 15.68 -5.32 +1480 40 40 3 40 47.49 5.84 -12.99 +1481 3 0 40 40 63.48 -2.65 14.68 +1482 0 3 40 40 63.34 -0.62 15.10 +1483 3 3 40 40 62.50 -1.36 14.07 +1484 40 3 40 40 53.33 -9.46 3.04 +1485 3 40 40 40 51.83 13.08 7.94 +1486 0 0 0 10 86.16 2.25 -9.01 +1487 0 0 10 10 85.35 0.72 0.51 +1488 0 0 20 10 84.64 -0.47 9.26 +1489 0 0 40 10 83.38 -2.13 25.25 +1490 0 0 70 10 81.55 -3.02 46.81 +1491 0 10 0 10 81.15 8.87 -9.35 +1492 0 10 10 10 80.36 7.51 -0.69 +1493 0 10 20 10 79.66 6.45 7.27 +1494 0 10 40 10 78.41 4.95 21.83 +1495 0 10 70 10 76.65 4.21 41.55 +1496 0 20 0 10 76.62 15.01 -9.46 +1497 0 20 10 10 75.86 13.81 -1.60 +1498 0 20 20 10 75.17 12.87 5.64 +1499 0 20 40 10 73.93 11.53 18.88 +1500 0 20 70 10 72.26 10.95 36.89 +1501 0 40 0 10 68.59 26.34 -9.11 +1502 0 40 10 10 67.87 25.43 -2.69 +1503 0 40 20 10 67.22 24.71 3.22 +1504 0 40 40 10 66.02 23.66 14.08 +1505 0 40 70 10 64.53 23.40 28.94 +1506 0 70 0 10 58.33 42.04 -7.60 +1507 0 70 10 10 57.85 41.28 -2.96 +1508 0 70 20 10 57.41 40.64 1.33 +1509 0 70 40 10 56.61 39.59 9.25 +1510 0 70 70 10 55.67 38.56 20.44 +1511 10 0 0 10 81.89 -1.02 -13.66 +1512 10 0 10 10 81.04 -2.78 -4.48 +1513 10 0 20 10 80.27 -4.19 3.97 +1514 10 0 40 10 78.92 -6.23 19.40 +1515 10 0 70 10 77.10 -7.50 39.88 +1516 10 10 0 10 77.19 5.19 -13.79 +1517 10 10 10 10 76.38 3.62 -5.41 +1518 10 10 20 10 75.65 2.36 2.31 +1519 10 10 40 10 74.34 0.50 16.41 +1520 10 10 70 10 72.58 -0.64 35.18 +1521 10 20 0 10 72.93 10.96 -13.75 +1522 10 20 10 10 72.16 9.56 -6.11 +1523 10 20 20 10 71.46 8.43 0.94 +1524 10 20 40 10 70.21 6.76 13.83 +1525 10 20 70 10 68.51 5.76 31.00 +1526 10 40 0 10 65.34 21.60 -13.20 +1527 10 40 10 10 64.65 20.51 -6.90 +1528 10 40 20 10 64.01 19.63 -1.09 +1529 10 40 40 10 62.87 18.31 9.57 +1530 10 40 70 10 61.31 17.57 23.83 +1531 10 70 0 10 55.63 36.34 -11.41 +1532 10 70 10 10 55.19 35.44 -6.85 +1533 10 70 20 10 54.78 34.67 -2.63 +1534 10 70 40 10 54.04 33.40 5.17 +1535 10 70 70 10 52.94 32.14 16.00 +1536 20 0 0 10 78.01 -4.00 -17.83 +1537 20 0 10 10 77.11 -5.98 -8.95 +1538 20 0 20 10 76.31 -7.59 -0.78 +1539 20 0 40 10 74.88 -10.01 14.14 +1540 20 0 70 10 73.07 -11.66 33.61 +1541 20 10 0 10 73.59 1.86 -17.78 +1542 20 10 10 10 72.76 0.08 -9.65 +1543 20 10 20 10 72.00 -1.38 -2.16 +1544 20 10 40 10 70.66 -3.58 11.53 +1545 20 10 70 10 68.89 -5.12 29.42 +1546 20 20 0 10 69.58 7.29 -17.60 +1547 20 20 10 10 68.80 5.69 -10.15 +1548 20 20 20 10 68.10 4.39 -3.29 +1549 20 20 40 10 66.84 2.39 9.27 +1550 20 20 70 10 65.12 0.96 25.69 +1551 20 40 0 10 62.39 17.30 -16.86 +1552 20 40 10 10 61.73 16.04 -10.67 +1553 20 40 20 10 61.12 15.00 -4.96 +1554 20 40 40 10 60.02 13.40 5.53 +1555 20 40 70 10 58.40 12.21 19.23 +1556 20 70 0 10 53.23 31.12 -14.78 +1557 20 70 10 10 52.81 30.08 -10.29 +1558 20 70 20 10 52.44 29.18 -6.13 +1559 20 70 40 10 51.75 27.69 1.55 +1560 20 70 70 10 50.52 26.21 12.05 +1561 40 0 0 10 71.04 -9.28 -25.17 +1562 40 0 10 10 70.06 -11.70 -16.84 +1563 40 0 20 10 69.19 -13.73 -9.17 +1564 40 0 40 10 67.63 -16.91 4.83 +1565 40 0 70 10 65.86 -19.30 22.44 +1566 40 10 0 10 67.13 -4.06 -24.80 +1567 40 10 10 10 66.26 -6.26 -17.12 +1568 40 10 20 10 65.47 -8.10 -10.04 +1569 40 10 40 10 64.05 -11.02 2.90 +1570 40 10 70 10 62.30 -13.33 19.17 +1571 40 20 0 10 63.57 0.76 -24.36 +1572 40 20 10 10 62.78 -1.23 -17.28 +1573 40 20 20 10 62.07 -2.89 -10.75 +1574 40 20 40 10 60.80 -5.56 1.22 +1575 40 20 70 10 59.07 -7.78 16.24 +1576 40 40 0 10 57.14 9.63 -23.28 +1577 40 40 10 10 56.52 8.03 -17.29 +1578 40 40 20 10 55.96 6.67 -11.76 +1579 40 40 40 10 54.95 4.49 -1.59 +1580 40 40 70 10 53.26 2.46 11.12 +1581 40 70 0 10 49.01 21.69 -20.59 +1582 40 70 10 10 48.67 20.37 -16.22 +1583 40 70 20 10 48.35 19.21 -12.17 +1584 40 70 40 10 47.78 17.25 -4.69 +1585 40 70 70 10 46.30 15.34 5.23 +1586 70 0 0 10 61.80 -16.14 -35.18 +1587 70 0 10 10 60.94 -18.92 -27.36 +1588 70 0 20 10 60.17 -21.27 -20.16 +1589 70 0 40 10 58.82 -25.01 -6.95 +1590 70 0 70 10 56.98 -27.91 8.69 +1591 70 10 0 10 58.63 -11.59 -34.06 +1592 70 10 10 10 57.86 -14.12 -26.87 +1593 70 10 20 10 57.17 -16.25 -20.24 +1594 70 10 40 10 55.95 -19.67 -8.06 +1595 70 10 70 10 54.16 -22.42 6.49 +1596 70 20 0 10 55.72 -7.39 -32.96 +1597 70 20 10 10 55.04 -9.68 -26.35 +1598 70 20 20 10 54.42 -11.62 -20.24 +1599 70 20 40 10 53.33 -14.74 -9.02 +1600 70 20 70 10 51.59 -17.35 4.51 +1601 70 40 0 10 50.44 0.32 -30.74 +1602 70 40 10 10 49.91 -1.54 -25.19 +1603 70 40 20 10 49.43 -3.11 -20.06 +1604 70 40 40 10 48.58 -5.70 -10.60 +1605 70 40 70 10 46.93 -8.02 1.04 +1606 70 70 0 10 44.16 10.50 -27.36 +1607 70 70 10 10 43.77 9.05 -23.18 +1608 70 70 20 10 43.41 7.78 -19.30 +1609 70 70 40 10 42.77 5.64 -12.13 +1610 70 70 70 10 41.42 3.41 -2.69 +1611 50 40 40 0 55.80 1.09 -5.42 +1612 100 0 0 10 55.07 -20.50 -42.06 +1613 0 100 0 10 51.18 53.01 -4.66 +1614 0 0 100 10 80.18 -2.95 63.01 +1615 0 100 100 10 49.06 48.28 21.54 +1616 100 0 100 10 49.05 -36.09 9.64 +1617 100 100 0 10 37.09 9.00 -28.41 +END_DATA diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 96640b5508..e82ad2b548 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -5,7 +5,9 @@ //! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB; //! the desktop canvas converts it into the display's own profile last ([`display`]). //! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model -//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers); +//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from +//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old +//! profile-free formula (kept for exact legacy numbers); //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). //! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with //! the profiles [`use_document_profiles`] last put in place of the working spaces; @@ -17,6 +19,7 @@ pub mod display; pub mod generic; pub mod icc; pub mod lab; +pub mod measured; use std::cell::{Cell, RefCell}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -37,6 +40,12 @@ pub const DISPLAY_P3: &str = "Display P3"; pub const PROPHOTO_RGB: &str = "ProPhoto RGB"; /// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile. pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)"; +/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on +/// premium coated paper, see [`measured`]). +pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)"; +/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on +/// wood-free uncoated paper, see [`measured`]). +pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)"; /// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers. pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)"; /// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen). @@ -44,7 +53,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)"; /// Built-in RGB and CMYK working spaces, in menu order. const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB]; -const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK]; +const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]; /// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents /// and commands that still use an old name get the current profile. @@ -228,6 +237,21 @@ fn generic() -> Arc { G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone() } +/// The working space of `condition`, computed from its data once and kept. +fn measured_space(condition: &measured::Condition) -> Result, CmsError> { + static SPACES: [OnceLock>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()]; + let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i)); + slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone()) + .ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference))) +} + +/// The registered printing condition a built-in CMYK working space characterizes: its reference +/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs +/// to (by its current or legacy name). `None` for every other profile. +pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> { + measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY)) +} + static USER: RwLock>> = RwLock::new(Vec::new()); /// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]). static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0); @@ -248,7 +272,11 @@ fn user_profile(name: &str) -> Option> { } fn cmyk_space(name: &str) -> Result { - match canonical_name(name) { + let canonical = canonical_name(name); + if let Some(c) = measured::condition(canonical) { + return measured_space(c).map(CmykSpace::Generic); + } + match canonical { GENERIC_CMYK => Ok(CmykSpace::Generic(generic())), DEVICE_CMYK => Ok(CmykSpace::Device), _ => match user_profile(name) { @@ -371,9 +399,13 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { CmykSpace::Generic(g) => g.paper_xyz(), CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, }; + let copyright = match measured::condition(name) { + Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference), + None => icc::NO_COPYRIGHT.to_string(), + }; let to_lab = |c| cms.cmyk_to_lab(c); let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); - icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + icc::encode(&icc::cmyk_profile(name, paper, ©right, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } @@ -1193,3 +1225,5 @@ pub(crate) fn cmyk_is_device() -> bool { mod tests; #[cfg(test)] mod tests_icc; +#[cfg(test)] +mod tests_measured; diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 16f251054b..57d9d9d329 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -30,6 +30,7 @@ use std::sync::OnceLock; use super::Intent; use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb}; +use super::measured::Lattice; /// Black generation. #[derive(Clone, Copy, Debug, PartialEq)] @@ -129,6 +130,9 @@ pub struct GenericCmyk { paper_xyz: [f32; 3], /// Media-relative XYZ of the black point (for black-point compensation). black_rel: [f32; 3], + /// A media-relative Lab correction added to the model, fitted to measured data + /// ([`super::measured`]). + correction: Option, gbd: OnceLock, } @@ -139,6 +143,15 @@ impl GenericCmyk { } pub fn new(params: GenericCmykParams) -> Self { + Self::build(params, None) + } + + /// The model of `params` with `correction` added to its media-relative Lab. + pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self { + Self::build(params, Some(correction)) + } + + fn build(params: GenericCmykParams, correction: Option) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) { @@ -149,7 +162,7 @@ impl GenericCmyk { let g = params.tvi50[i]; if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 } }); - let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() }; + let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() }; g.black_rel = g.to_xyz_rel(g.black_point_build()); g } @@ -218,6 +231,14 @@ impl GenericCmyk { /// Media-relative XYZ (paper = D50 white). pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] { + match &self.correction { + Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)), + None => self.neugebauer(cmyk), + } + } + + /// Media-relative XYZ of the Neugebauer model alone. + fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] { let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i])); let mut out = [0.0f32; 3]; for (i, p) in self.prim.iter().enumerate() { @@ -236,7 +257,14 @@ impl GenericCmyk { } pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab { - xyz_to_lab(self.to_xyz_rel(cmyk)) + let lab = xyz_to_lab(self.neugebauer(cmyk)); + match &self.correction { + Some(c) => { + let d = c.at(cmyk); + Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2]) + } + None => lab, + } } pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab { xyz_to_lab(self.to_xyz(cmyk)) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8fc287ae23..e83b0c1449 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option { Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())])) } +/// The copyright text of profiles made here: they carry no copyright claim. +pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely"; + /// Profiles made here carry their name and no copyright claim. -fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile { +fn labelled(p: ColorProfile, name: &str) -> ColorProfile { + with_copyright(p, name, NO_COPYRIGHT) +} + +fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile { p.description = text_tag(name); - p.copyright = text_tag("No copyright, use freely"); + p.copyright = text_tag(copyright); p } @@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9; /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK /// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which -/// the ICC-absolute colorimetric intent reproduces. +/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`. pub(super) fn cmyk_profile( name: &str, paper: [f32; 3], + copyright: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, mapped: impl Fn(lab::Lab) -> [f32; 4], colorimetric: impl Fn(lab::Lab) -> [f32; 4], @@ -520,7 +528,7 @@ pub(super) fn cmyk_profile( p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); - labelled(p, name) + with_copyright(p, name, copyright) } /// The grey space of greyscale exports: sRGB's tone curve, D50 white. diff --git a/crates/color/src/cms/measured.rs b/crates/color/src/cms/measured.rs new file mode 100644 index 0000000000..3c8d9ff6e7 --- /dev/null +++ b/crates/color/src/cms/measured.rs @@ -0,0 +1,362 @@ +//! CMYK working spaces computed from published characterization data. +//! +//! Fogra publishes the measured colors of its reference printing conditions +//! () and allows the data to be +//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and +//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the +//! first time it is used: +//! +//! * The paper is the measured blank patch. The 15 solids and overprints of the +//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve +//! is fitted to its single-ink ramp. +//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed +//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The +//! smoothing carries the fit into regions the patch set does not sample, such as dark builds +//! with more than 60% black. +//! +//! The total ink limit and the black generation are VectorCraft's own values. + +use super::generic::{GenericCmyk, GenericCmykParams, swop_like}; +use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab}; + +/// A printing condition with published characterization data. +#[derive(Clone, Copy, Debug)] +pub struct Condition { + /// The working space's name. + pub name: &'static str, + /// The reference name of the characterization data, which a PDF/X output intent uses as + /// its `/OutputConditionIdentifier`. + pub reference: &'static str, + /// The characterization data file, as published. + pub data: &'static [u8], + /// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value. + pub tac: f32, +} + +/// The registry that the reference names of [`CONDITIONS`] belong to +/// (). +pub const REGISTRY: &str = "http://www.color.org"; + +/// The printing conditions VectorCraft computes working spaces for. +pub const CONDITIONS: [Condition; 2] = [ + Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 }, + Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 }, +]; + +/// The condition a working space of [`CONDITIONS`] is computed for. +pub fn condition(name: &str) -> Option<&'static Condition> { + CONDITIONS.iter().find(|c| c.name == name) +} + +/// One measured patch: nominal inks (0..1) and absolute Lab (D50). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Patch { + pub cmyk: [f32; 4], + pub lab: Lab, +} + +/// The most patches [`parse`] reads. +const MAX_PATCHES: usize = 20_000; + +/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`, +/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a +/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, or the +/// file has no rows. +pub fn parse(data: &[u8]) -> Option> { + let text = std::str::from_utf8(data).ok()?; + let mut lines = text.lines().map(str::trim); + lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?; + let mut fields = vec![]; + for line in lines.by_ref() { + if line == "END_DATA_FORMAT" { + break; + } + fields.extend(line.split_whitespace()); + } + let at = |f: &str| fields.iter().position(|x| *x == f); + let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?]; + lines.by_ref().find(|l| *l == "BEGIN_DATA")?; + let mut out = vec![]; + for line in lines { + if line == "END_DATA" { + break; + } + if line.is_empty() { + continue; + } + if out.len() >= MAX_PATCHES { + return None; + } + let row: Vec<&str> = line.split_whitespace().collect(); + let mut v = [0f32; 7]; + for (slot, &col) in v.iter_mut().zip(&cols) { + *slot = row.get(col)?.parse::().ok().filter(|x| x.is_finite())?; + } + if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) { + return None; + } + out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) }); + } + (!out.is_empty()).then_some(out) +} + +/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white). +fn relative(lab: Lab, paper: [f32; 3]) -> Lab { + let x = lab_to_xyz(lab); + xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i])) +} + +/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ. +fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option { + let mut sum = [0f32; 3]; + let mut n = 0; + for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) { + let x = lab_to_xyz(p.lab); + for i in 0..3 { + sum[i] += x[i]; + } + n += 1; + } + (n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32))) +} + +/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the +/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the +/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area +/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most +/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ). +fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> { + let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?; + let span = D50[ch] - solid[ch]; + if span.abs() < 1e-4 { + return None; + } + let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64); + for p in patches { + let a = p.cmyk[ink]; + let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0); + if !alone || a <= 0.0 || a >= 1.0 { + continue; + } + let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span; + let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0))); + let d = f64::from(e - a); + s11 += b1 * b1; + s12 += b1 * b2; + s22 += b2 * b2; + r1 += b1 * d; + r2 += b2 * d; + } + let det = s11 * s22 - s12 * s12; + if det.abs() < 1e-12 { + return None; + } + let u = ((r1 * s22 - r2 * s12) / det) as f32; + let v = ((s11 * r2 - s12 * r1) / det) as f32; + let tvi50 = u.clamp(0.0, 0.45); + let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45); + Some((tvi50, tvi40)) +} + +/// Absolute Lab → media-relative XYZ. +fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] { + let x = lab_to_xyz(lab); + [0, 1, 2].map(|i| x[i] * D50[i] / paper[i]) +} + +/// The press model of `condition`, computed from its data. `None` when the data does not parse +/// or lacks the paper, a solid or overprint, or a single-ink ramp. +pub fn model(condition: &Condition) -> Option { + fit(condition, &parse(condition.data)?, SMOOTHING) +} + +/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing`. +pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option { + let paper = mean_lab(patches, [0.0; 4])?; + let paper_xyz = lab_to_xyz(paper); + let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15]; + for (i, slot) in primaries.iter_mut().enumerate() { + let bits = i + 1; + let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 }); + *slot = relative(mean_lab(patches, inks)?, paper_xyz); + } + let mut tvi50 = [0f32; 4]; + let mut tvi40 = [0f32; 4]; + for ink in 0..4 { + let solid = lab_to_xyz(primaries[(1 << ink) - 1]); + (tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?; + } + let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg }; + let base = GenericCmyk::new(params.clone()); + let points: Vec<([f32; 4], [f32; 3])> = patches + .iter() + .map(|p| { + let want = relative(p.lab, paper_xyz); + let got = base.to_lab_rel(p.cmyk); + (p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b]) + }) + .collect(); + Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing))) +} + +/// Weight of the lattice's smoothness against its fit to the patches. +pub(crate) const SMOOTHING: f64 = 0.02; + +/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps. +const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0]; +const N: usize = KNOTS.len(); +const NODES: usize = N * N * N * N; + +/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`]. +#[derive(Clone, Debug)] +pub struct Lattice { + values: Vec<[f32; 3]>, +} + +/// The cell of `v` along an axis and its position in it. +fn locate(v: f32) -> (usize, f32) { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2); + let (lo, hi) = (KNOTS[i], KNOTS[i + 1]); + (i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0)) +} + +/// The 16 nodes around `cmyk` with their interpolation weights. +fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] { + let cells = cmyk.map(locate); + let mut out = [(0, 0.0); 16]; + for (corner, slot) in out.iter_mut().enumerate() { + let mut index = 0; + let mut w = 1.0; + for (axis, (cell, t)) in cells.iter().enumerate() { + let up = corner & (1 << axis) != 0; + index = index * N + cell + usize::from(up); + w *= if up { *t } else { 1.0 - t }; + } + *slot = (index, w); + } + out +} + +/// Index strides of the four axes (C is the slowest). +const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1]; + +impl Lattice { + /// The correction at `cmyk`. + pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] { + let mut out = [0f32; 3]; + for (i, w) in corners(cmyk) { + if w == 0.0 { + continue; + } + let v = self.values.get(i).copied().unwrap_or_default(); + for c in 0..3 { + out[c] += w * v[c]; + } + } + out + } + + /// The lattice that best fits `points` (inks, correction) in the least-squares sense, with + /// `smoothing` times the squared second differences of the nodes along each axis added to the + /// error. The node at no ink stays 0, so the paper keeps the model's color (white, media- + /// relative). Solved by conjugate gradients, one Lab channel at a time. + pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice { + let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect(); + // The divided second difference at interior knot j, scaled to a unit spacing of 1/8. + let curvature: Vec<[f64; 3]> = (1..N - 1) + .map(|j| { + let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j])); + let s = 0.125f64 * 0.125; + [2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s] + }) + .collect(); + let apply = |x: &[f64], out: &mut [f64]| { + out.fill(0.0); + for w in &weights { + let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, w) in w { + if let Some(o) = out.get_mut(*i) { + *o += f64::from(*w) * v; + } + } + } + for node in 0..NODES { + let mut rest = node; + for stride in STRIDES { + let j = rest / stride; + rest %= stride; + // Only interior knots (1 to N − 2) have a second difference. + let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue }; + let idx = [node - stride, node, node + stride]; + let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, c) in idx.iter().zip(c) { + if let Some(o) = out.get_mut(*i) { + *o += smoothing * c * d; + } + } + } + } + for (o, v) in out.iter_mut().zip(x) { + *o += 1e-9 * v; + } + // The paper's node is held: with its right-hand side 0 it stays 0 in every iterate. + if let (Some(o), Some(v)) = (out.first_mut(), x.first()) { + *o = *v; + } + }; + let mut values = vec![[0f32; 3]; NODES]; + for ch in 0..3 { + let mut b = vec![0f64; NODES]; + for (w, (_, r)) in weights.iter().zip(points) { + for (i, w) in w { + if let Some(o) = b.get_mut(*i) { + *o += f64::from(*w) * f64::from(r[ch]); + } + } + } + if let Some(o) = b.first_mut() { + *o = 0.0; + } + let x = conjugate_gradients(&apply, &b, 4000); + for (v, x) in values.iter_mut().zip(&x) { + v[ch] = *x as f32; + } + } + Lattice { values } + } +} + +/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by. +fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec { + let n = b.len(); + let mut x = vec![0f64; n]; + let mut r = b.to_vec(); + let mut p = r.clone(); + let mut ap = vec![0f64; n]; + let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::(); + let mut rr = dot(&r, &r); + let stop = rr * 1e-20; + for _ in 0..max_iterations { + if rr <= stop || rr == 0.0 { + break; + } + apply(&p, &mut ap); + let pap = dot(&p, &ap); + if pap <= 0.0 || !pap.is_finite() { + break; + } + let alpha = rr / pap; + for i in 0..n { + x[i] += alpha * p[i]; + r[i] -= alpha * ap[i]; + } + let next = dot(&r, &r); + let beta = next / rr; + rr = next; + for i in 0..n { + p[i] = r[i] + beta * p[i]; + } + } + x +} diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs new file mode 100644 index 0000000000..25983e91bb --- /dev/null +++ b/crates/color/src/cms/tests_measured.rs @@ -0,0 +1,186 @@ +use super::*; +use sha2::{Digest, Sha256}; + +fn hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The data files ship exactly as Fogra publishes them in +/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip. +#[test] +fn characterization_data_is_the_published_files() { + let want = [ + ("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111), + ("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781), + ]; + for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) { + assert_eq!(c.reference, reference); + assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}"); + } +} + +#[test] +fn the_data_parses_into_its_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + assert_eq!(patches.len(), 1617, "{}", c.reference); + assert_eq!(patches[0].cmyk, [0.0; 4]); + } + let p = measured::parse(measured::CONDITIONS[0].data).unwrap(); + assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0)); + assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]); + assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42)); +} + +#[test] +fn malformed_data_is_refused() { + let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n"); + let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B"; + let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"); + assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2)); + for bad in [ + file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"), + file(fields, "1 0 0 0 0 95 1"), + file(fields, "1 0 0 0 0 95 NaN -6"), + file(fields, "1 0 0 0 0 95 x -6"), + file(fields, "1 0 0 0 101 95 1 -6"), + file(fields, "1 -1 0 0 0 95 1 -6"), + file(fields, ""), + "BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(), + ] { + assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}"); + } + assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None); +} + +/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max). +fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) { + let errors: Vec = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect(); + (errors.iter().sum::() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max)) +} + +#[test] +fn the_working_spaces_reproduce_the_measured_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let start = std::time::Instant::now(); + let g = measured::model(c).unwrap(); + let took = start.elapsed(); + let (mean, max) = accuracy(&g, &patches); + println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference); + assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference); + // The paper is the measured blank patch. + assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05); + } +} + +/// A model fitted without every fourth patch (the paper and the solids and overprints stay in) +/// predicts the patches it left out. +#[test] +fn the_fit_predicts_patches_it_left_out() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); + let (kept, left): (Vec<(usize, &measured::Patch)>, Vec<_>) = patches.iter().enumerate().partition(|(i, p)| i % 4 != 3 || corner(p)); + let kept: Vec = kept.into_iter().map(|(_, p)| *p).collect(); + let left: Vec = left.into_iter().map(|(_, p)| *p).collect(); + let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap(); + let (mean, max) = accuracy(&g, &left); + println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len()); + assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference); + } +} + +/// More of any ink never makes a build lighter, also where the data has few patches (black above +/// 60%, and builds over the ink limit). +#[test] +fn more_ink_never_lightens_a_build() { + let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); + let coarse = [0.0, 0.25, 0.5, 0.75, 1.0]; + for c in &measured::CONDITIONS { + let g = measured::model(c).unwrap(); + let mut worst = 0f32; + for ink in 0..4 { + for a in coarse { + for b in coarse { + for d in coarse { + let mut others = [a, b, d].into_iter(); + let mut build = [0f32; 4]; + for (i, slot) in build.iter_mut().enumerate() { + if i != ink { + *slot = others.next().unwrap(); + } + } + let mut last = f32::INFINITY; + for &v in &steps { + build[ink] = v; + let l = g.to_lab_rel(build).l; + worst = worst.max(l - last); + last = l; + } + } + } + } + } + println!("{}: largest L* rise with more ink {worst:.3}", c.reference); + assert!(worst < 0.3, "{}: {worst}", c.reference); + } +} + +#[test] +fn the_working_spaces_follow_generic_cmyk_in_the_list() { + let cmyk: Vec = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect(); + assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]); + assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK); + assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org"))); + assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org"))); + assert_eq!(characterization(GENERIC_CMYK), None); + assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_)))); +} + +#[test] +fn colors_separate_and_come_back_in_the_measured_spaces() { + for name in [FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], [0.5, 0.5, 0.5], [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] { + let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric); + assert!(inks.iter().sum::() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}"); + if cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD { + let back = cms.cmyk_to_srgb(inks, false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back)); + assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})"); + } + } + // White is paper with no ink, and black is the darkest build within the ink limit. + assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]); + let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + assert!(black[3] > 0.8 && black.iter().sum::() <= 3.0 + 1e-3, "{name}: {black:?}"); + } + // The coated paper prints a larger gamut than the uncoated one. + let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 }; + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap(); + assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue)); +} + +#[test] +fn the_profiles_carry_the_paper_and_the_data_source() { + for c in &measured::CONDITIONS { + let start = std::time::Instant::now(); + let bytes = icc_bytes(c.name).unwrap(); + println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed()); + let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap(); + assert_eq!( + (p.profile_class, p.color_space, p.pcs), + (moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab) + ); + assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some()); + let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab); + let white = p.media_white_point.unwrap(); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference); + } + let text = format!("{:?}", p.copyright); + assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}"); + } +} diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..280bb356b4 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 36b0845aa1..871403b2ab 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent; FOGRA51 or FOGRA52 for the built-in profiles computed from that data, with registry http://www.color.org unless registry is given), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index f5e4bb6e36..127846ad4b 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -573,6 +573,8 @@ impl Dest { /// The catalog entries `set` asks for (none in PDF/A files, see [`warnings`]); a PDF/X file's /// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one. +/// A profile computed for a registered printing condition ([`cms::characterization`]) gives the +/// condition identifier and registry the settings leave blank. fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { let o = &set.output; if set.standard == Standard::PdfA2b { @@ -589,13 +591,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { ProfileKind::Gray => None, }); let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::(); - OutputIntent { - id: text(if id.is_empty() { name } else { id }), - condition: text(&o.output_condition), - registry: text(&o.registry), - info: text(name), - profile, - } + // Without a condition identifier, a profile computed for a registered printing condition + // names that condition and, unless the settings name one, the registry it belongs to. + let (id, registry) = match cms::characterization(name) { + Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }), + _ => (if id.is_empty() { name } else { id }, o.registry.as_str()), + }; + OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile } }); let trapped = (o.trapped || intent.is_some()).then_some(o.trapped); (intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped }) diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index 1c12b9586f..5cfcebf782 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -151,6 +151,74 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds"))); } +/// The ICC tag signatures of `icc`'s tag table. +fn icc_tags(icc: &[u8]) -> Vec { + let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize; + (0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect() +} + +#[test] +fn a_registered_condition_profile_names_its_condition_and_embeds_itself() { + use std::io::Read; + let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]); + for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] { + let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let t = text(&r.bytes); + let info = profile.replace('(', r"\(").replace(')', r"\)"); + for want in [ + "/S/GTS_PDFX".to_string(), + format!("/OutputConditionIdentifier({reference})"), + "/RegistryName(http://www.color.org)".into(), + format!("/Info({info})"), + ] { + assert!(t.contains(&want), "{profile}: {want}"); + } + // The embedded profile is the working space's: a CMYK output profile with Lab tables both + // ways, read from the file's bytes. + let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap(); + let obj = &r.bytes[start..end]; + let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap(); + let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap(); + let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len(); + data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count(); + let raw = &obj[data..data + length]; + let mut icc = vec![]; + if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() { + flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap(); + } else { + icc = raw.to_vec(); + } + assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap()); + assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..])); + assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]); + let tags = icc_tags(&icc); + for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] { + assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}"); + } + let back = cms::IccProfile::from_bytes(None, &icc).unwrap(); + assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk)); + assert!(import(&r.bytes).is_ok()); + } + // A condition identifier or registry the settings give stays. + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.output_condition_id = "Press 2".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}"); + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.registry = "https://example.com/registry".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)")); + // Other profiles keep their name as the identifier, with no registry. + let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap()); + assert!(!t.contains("/RegistryName"), "{t}"); +} + #[test] fn pdfx_1a_files_have_no_rgb() { let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..7b7ba78e78 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5841,6 +5841,8 @@ lighting Light Светлина VectorCraft Default По подразбиране за VectorCraft VectorCraft Defaults Стандартни настройки на VectorCraft VectorCraft Generic CMYK (SWOP-like) Общ CMYK за VectorCraft (подобен на SWOP) + VectorCraft Coated CMYK (FOGRA51) Мелиран CMYK за VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) Немелиран CMYK за VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Образци на VectorCraft (.vcswatches) Vertical Align Вертикално подравняване Vertical Area Type Вертикално въвеждане в област diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..54fabf3cad 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -603,6 +603,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft generički CMYK (sličan SWOP-u) + VectorCraft Coated CMYK (FOGRA51) VectorCraft premazani CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nepremazani CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Naslijeđeni Macintosh RGB (gama 1.8) Internet Standard RGB (sRGB) Internet standardni RGB (sRGB) Monitor RGB RGB monitora diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..54508d2b8c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5316,6 +5316,8 @@ digits Malayalam Malaiàlam VectorCraft didn't quit normally last time. These documents had unsaved changes: VectorCraft no es va tancar correctament l’última vegada. Aquests documents tenien canvis no desats: VectorCraft documents: one locked object, updated when the file changes. Documents de VectorCraft: un objecte bloquejat, actualitzat quan canvia el fitxer. VectorCraft Generic CMYK (SWOP-like) CMYK genèric de VectorCraft (similar a SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK estucat de VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucat de VectorCraft (FOGRA52) VectorCraft Help… Ajuda de VectorCraft… VectorCraft on getartcraft.com VectorCraft a getartcraft.com VectorCraft on GitHub VectorCraft al GitHub diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..4f0d8a340d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -616,6 +616,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft obecný CMYK (podobný SWOP) + VectorCraft Coated CMYK (FOGRA51) VectorCraft natíraný CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nenatíraný CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Starší Macintosh RGB (gama 1,8) Internet Standard RGB (sRGB) Standardní internetové RGB (sRGB) Monitor RGB RGB monitoru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..5cc646778b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3266,6 +3266,8 @@ liquify-list-end {0}, {1} {0} og {1} RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft-generisk CMYK (SWOP-lignende) + VectorCraft Coated CMYK (FOGRA51) VectorCraft bestrøget CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft ubestrøget CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Ældre Macintosh RGB (gamma 1,8) Internet Standard RGB (sRGB) Internetstandard-RGB (sRGB) Monitor RGB Skærm-RGB diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..0c214a7b9f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6063,6 +6063,8 @@ digits Malayalam Μαλαγιάλαμ VectorCraft Default Προεπιλογή VectorCraft VectorCraft Defaults Προεπιλογές VectorCraft VectorCraft Generic CMYK (SWOP-like) Γενικό CMYK του VectorCraft (τύπου SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK επιχρισμένου χαρτιού του VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK μη επιχρισμένου χαρτιού του VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Δείγματα χρωμάτων VectorCraft (.vcswatches) Vertical Align Κατακόρυφη στοίχιση Vertical Area Type Κατακόρυφο κείμενο περιοχής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..816794a7ef 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6230,6 +6230,8 @@ mark-style Japanese Japonesas Variation Variación VectorCraft Default Predeterminado de VectorCraft VectorCraft Generic CMYK (SWOP-like) CMYK genérico de VectorCraft (similar a SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK estucado de VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucado de VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Muestras de VectorCraft (.vcswatches) Vertical Area Type Texto de área vertical Vertical Type Texto vertical diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..42c6c3481b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -610,6 +610,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraftin yleinen CMYK (SWOP-tyyppinen) + VectorCraft Coated CMYK (FOGRA51) VectorCraftin päällystetty CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraftin päällystämätön CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Vanha Macintosh RGB (gamma 1.8) Internet Standard RGB (sRGB) Internetin standardi-RGB (sRGB) Monitor RGB Näytön RGB diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..22be7f5486 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6343,6 +6343,8 @@ lighting Light Lumière VectorCraft Default VectorCraft par défaut VectorCraft Defaults Valeurs par défaut de VectorCraft VectorCraft Generic CMYK (SWOP-like) CMJN générique VectorCraft (de type SWOP) + VectorCraft Coated CMYK (FOGRA51) CMJN couché VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMJN non couché VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Nuances VectorCraft (.vcswatches) Vertical Align Alignement vertical Vertical Area Type Texte captif vertical diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..61e1096f5a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5736,6 +5736,8 @@ antiAlias Sharp शार्प VectorCraft didn't quit normally last time. These documents had unsaved changes: पिछली बार VectorCraft सामान्य तरीके से बंद नहीं हुआ था। इन डॉक्यूमेंट्स में बिना सेव किए बदलाव थे: VectorCraft documents: one locked object, updated when the file changes. VectorCraft डॉक्यूमेंट्स: एक लॉक्ड ऑब्जेक्ट, जो फ़ाइल बदलने पर अपडेट होता है। VectorCraft Generic CMYK (SWOP-like) वेक्टर क्रेफ्ट जेनेरिक CMYK (SWOP-like) + VectorCraft Coated CMYK (FOGRA51) वेक्टर क्रेफ्ट कोटेड CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) वेक्टर क्रेफ्ट अनकोटेड CMYK (FOGRA52) VectorCraft Help… VectorCraft मदद… VectorCraft on getartcraft.com getartcraft.com पर VectorCraft VectorCraft on GitHub GitHub पर VectorCraft diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..14e7ba4ea1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4953,6 +4953,8 @@ mark-style Japanese Japán VectorCraft didn't quit normally last time. These documents had unsaved changes: A VectorCraft legutóbb nem szabályosan lépett ki. Ezekben a dokumentumokban mentetlen módosítások voltak: VectorCraft documents: one locked object, updated when the file changes. VectorCraft-dokumentumok: egyetlen zárolt objektum, amely a fájl változásakor frissül. VectorCraft Generic CMYK (SWOP-like) VectorCraft általános CMYK (SWOP-szerű) + VectorCraft Coated CMYK (FOGRA51) VectorCraft mázolt CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft mázolatlan CMYK (FOGRA52) VectorCraft Help… VectorCraft súgó… VectorCraft on getartcraft.com A VectorCraft a getartcraft.com oldalon VectorCraft on GitHub A VectorCraft a GitHubon diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..9e3c117d74 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -567,6 +567,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) CMYK generik VectorCraft (mirip SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK kertas berlapis VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK kertas tanpa lapisan VectorCraft (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) RGB Macintosh lama (Gamma 1.8) Internet Standard RGB (sRGB) RGB standar Internet (sRGB) Monitor RGB RGB monitor diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..847250274f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7924,6 +7924,8 @@ mark-style Japanese იაპონური Variation ვარიაცია VectorCraft Default VectorCraft-ის ნაგულისხმევი VectorCraft Generic CMYK (SWOP-like) VectorCraft-ის ზოგადი CMYK (SWOP-ის მსგავსი) + VectorCraft Coated CMYK (FOGRA51) VectorCraft-ის ცარციანი ქაღალდის CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft-ის უცარცო ქაღალდის CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft-ის ფერის ნიმუშები (.vcswatches) Vertical Area Type ვერტიკალური არის ტექსტი Vertical Type ვერტიკალური ტექსტი diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..fc856f7527 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1140,6 +1140,8 @@ liquify-list-end {0}, {1} {0} en {1} RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) Generieke VectorCraft-CMYK (SWOP-achtig) + VectorCraft Coated CMYK (FOGRA51) Gestreken VectorCraft-CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) Ongestreken VectorCraft-CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Verouderde Macintosh-RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internetstandaard-RGB (sRGB) Monitor RGB Monitor-RGB diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..755d76c41c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6231,6 +6231,8 @@ mark-style Japanese Japonesas Variation Variação VectorCraft Default Padrão do VectorCraft VectorCraft Generic CMYK (SWOP-like) CMYK Genérico do VectorCraft (tipo SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK Revestido do VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK Não Revestido do VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Amostras do VectorCraft (.vcswatches) Vertical Area Type Texto de Área Vertical Vertical Type Texto Vertical diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..88b552d0cf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7118,6 +7118,8 @@ axis Y Axis Ось Y VectorCraft Default VectorCraft по умолчанию VectorCraft Defaults Стандартные VectorCraft VectorCraft Generic CMYK (SWOP-like) Общий CMYK VectorCraft (как SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK VectorCraft для мелованной бумаги (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK VectorCraft для немелованной бумаги (FOGRA52) VectorCraft Swatches (.vcswatches) Образцы VectorCraft (.vcswatches) Vertical Align Вертикальное выравнивание Vertical Area Type Вертикальный текст в области diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..bfd07f44a3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6264,6 +6264,8 @@ lighting Light Ljus VectorCraft Default VectorCraft-standard VectorCraft Defaults VectorCraft-standardvärden VectorCraft Generic CMYK (SWOP-like) VectorCraft allmän CMYK (SWOP-liknande) + VectorCraft Coated CMYK (FOGRA51) VectorCraft bestruken CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft obestruken CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft-färgrutor (.vcswatches) Vertical Align Vertikal justering Vertical Area Type Vertikal områdestext diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..3227dac07d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6121,6 +6121,8 @@ lighting Light Işık VectorCraft Default VectorCraft Varsayılanı VectorCraft Defaults VectorCraft Varsayılanları VectorCraft Generic CMYK (SWOP-like) VectorCraft Genel CMYK (SWOP benzeri) + VectorCraft Coated CMYK (FOGRA51) VectorCraft Kaplamalı CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft Kaplamasız CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft Renk Örnekleri (.vcswatches) Vertical Align Dikey Hizalama Vertical Area Type Dikey Alan Türü diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..364486eb4f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5672,6 +5672,8 @@ liquify-list-end {0}, {1} {0}和{1} Photo Low Fidelity 低保真照片 Restricted Colors 受限颜色 VectorCraft Generic CMYK (SWOP-like) VectorCraft 通用 CMYK (类 SWOP) + VectorCraft Coated CMYK (FOGRA51) VectorCraft 涂布纸 CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft 非涂布纸 CMYK (FOGRA52) sRGB IEC61966-2.1 sRGB IEC61966-2.1 Working RGB 工作 RGB Dot Gain 15% 网点扩大 15% diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..8f49734a5d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9396,6 +9396,18 @@ PDF/X-4 always embeds one), a TrimBox on every page (the artboard), `/Trapped` T document has none) and dates; type is outlined or embedded; editing data, passwords and, in PDF/X-1a and PDF/X-3, PDF layers are refused. +The built-in CMYK working spaces `VectorCraft Coated CMYK (FOGRA51)` and `VectorCraft Uncoated CMYK (FOGRA52)` are +VectorCraft's own press models, computed when first used from the FOGRA51 and FOGRA52 characterization data that Fogra +publishes (); the data files ship unmodified in +`crates/color/data/`. An output intent with one of them, and with `output.outputConditionId` blank, has the +`/OutputConditionIdentifier` `FOGRA51` or `FOGRA52` and, unless `output.registry` names another, the `/RegistryName` +`http://www.color.org` (), with the profile embedded. Their total ink limit +(300%) and black generation are VectorCraft's own values. + +```json +{"name":"run_command","arguments":{"command":"document.exportPdf","params":{"path":"/tmp/press.pdf","preset":"PDF/X-4:2010","output":{"outputIntent":"VectorCraft Coated CMYK (FOGRA51)"}}}} +``` + - **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB destination or output intent is refused. Transparency is flattened before writing. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a1d4bd4576..141d655c60 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1763,6 +1763,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. + - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), 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.66). A PDF/X output intent made with one names `FOGRA51` or `FOGRA52` in the `http://www.color.org` registry and embeds the profile. 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. - **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. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. From eaf50e01ef4cddf96603a92e67c251ad623c0253 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:43:11 -0800 Subject: [PATCH 03/84] Tests: name the FOGRA ink-order test after the limit it checks more_ink_never_lightens_a_build allows an L* rise of up to 0.3 (the largest is 0.193 for FOGRA51 and 0.234 for FOGRA52). The test is now more_ink_lightens_a_build_by_less_than_0_3_l, and its comment states the limit. --- crates/color/src/cms/tests_measured.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 25983e91bb..5789605fcc 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -91,10 +91,10 @@ fn the_fit_predicts_patches_it_left_out() { } } -/// More of any ink never makes a build lighter, also where the data has few patches (black above -/// 60%, and builds over the ink limit). +/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches +/// (black above 60%, and builds over the ink limit). #[test] -fn more_ink_never_lightens_a_build() { +fn more_ink_lightens_a_build_by_less_than_0_3_l() { let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); let coarse = [0.0, 0.25, 0.5, 0.75, 1.0]; for c in &measured::CONDITIONS { From d3cd060e12c449797eb96a21a9d176c9b13b87a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 08:24:43 -0800 Subject: [PATCH 04/84] Color: refuse truncated Fogra data and a dark paper; hold out repeated builds together - measured::parse needs END_DATA and checks a NUMBER_OF_SETS in the header against the rows it read. - measured::fit refuses a paper whose XYZ is not positive and finite. - The left-out test keeps every row of a repeated build on the side of its first row; the docs line gives the new figures. - The round trip of a 50% gray is asserted whatever the gamut check says. - The output intent doc comment and the docs line say when the FOGRA identifier and color.org registry defaults apply. --- crates/color/src/cms/measured.rs | 28 +++++++++++++---- crates/color/src/cms/tests_measured.rs | 42 ++++++++++++++++++++++---- crates/pdf/src/output.rs | 6 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 63 insertions(+), 15 deletions(-) diff --git a/crates/color/src/cms/measured.rs b/crates/color/src/cms/measured.rs index 3c8d9ff6e7..9394b69394 100644 --- a/crates/color/src/cms/measured.rs +++ b/crates/color/src/cms/measured.rs @@ -60,10 +60,19 @@ const MAX_PATCHES: usize = 20_000; /// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`, /// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a -/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, or the -/// file has no rows. +/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the +/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is +/// not the number of rows. pub fn parse(data: &[u8]) -> Option> { let text = std::str::from_utf8(data).ok()?; + let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| { + let mut words = l.split_whitespace(); + (words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"'))) + }); + let sets = match sets { + Some(n) => Some(n?.parse::().ok()?), + None => None, + }; let mut lines = text.lines().map(str::trim); lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?; let mut fields = vec![]; @@ -77,8 +86,10 @@ pub fn parse(data: &[u8]) -> Option> { let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?]; lines.by_ref().find(|l| *l == "BEGIN_DATA")?; let mut out = vec![]; + let mut ended = false; for line in lines { if line == "END_DATA" { + ended = true; break; } if line.is_empty() { @@ -97,7 +108,7 @@ pub fn parse(data: &[u8]) -> Option> { } out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) }); } - (!out.is_empty()).then_some(out) + (ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out) } /// Absolute Lab → media-relative Lab (`paper` maps to the D50 white). @@ -164,16 +175,21 @@ fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] { [0, 1, 2].map(|i| x[i] * D50[i] / paper[i]) } -/// The press model of `condition`, computed from its data. `None` when the data does not parse -/// or lacks the paper, a solid or overprint, or a single-ink ramp. +/// The press model of `condition`, computed from its data. `None` when the data does not parse, +/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not +/// positive and finite. pub fn model(condition: &Condition) -> Option { fit(condition, &parse(condition.data)?, SMOOTHING) } -/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing`. +/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in +/// the cases [`model`] lists). pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option { let paper = mean_lab(patches, [0.0; 4])?; let paper_xyz = lab_to_xyz(paper); + if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) { + return None; + } let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15]; for (i, slot) in primaries.iter_mut().enumerate() { let bits = i + 1; diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 5789605fcc..4c8508f780 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -51,6 +51,30 @@ fn malformed_data_is_refused() { assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}"); } assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None); + // The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them. + let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"; + let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n"); + assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA"); + for (sets, len) in [ + ("NUMBER_OF_SETS\t2", Some(2)), + ("NUMBER_OF_SETS\t3", None), + ("NUMBER_OF_SETS\t1", None), + ("NUMBER_OF_SETS\tx", None), + ("NUMBER_OF_SETS", None), + ] { + assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}"); + } +} + +/// A paper measured as black has no XYZ to make the other patches relative to. +#[test] +fn a_paper_without_light_is_refused() { + let c = &measured::CONDITIONS[0]; + let mut patches = measured::parse(c.data).unwrap(); + for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) { + p.lab = Lab::new(0.0, 0.0, 0.0); + } + assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none()); } /// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max). @@ -75,15 +99,18 @@ fn the_working_spaces_reproduce_the_measured_patches() { } /// A model fitted without every fourth patch (the paper and the solids and overprints stay in) -/// predicts the patches it left out. +/// predicts the patches it left out. The data repeats some builds, and every row of a build is +/// on the side of the build's first row, so the fit never sees a left-out build. #[test] fn the_fit_predicts_patches_it_left_out() { for c in &measured::CONDITIONS { let patches = measured::parse(c.data).unwrap(); let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); - let (kept, left): (Vec<(usize, &measured::Patch)>, Vec<_>) = patches.iter().enumerate().partition(|(i, p)| i % 4 != 3 || corner(p)); - let kept: Vec = kept.into_iter().map(|(_, p)| *p).collect(); - let left: Vec = left.into_iter().map(|(_, p)| *p).collect(); + 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.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); + let kept: Vec = kept.into_iter().copied().collect(); + let left: Vec = left.into_iter().copied().collect(); let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap(); let (mean, max) = accuracy(&g, &left); println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len()); @@ -142,10 +169,13 @@ fn the_working_spaces_follow_generic_cmyk_in_the_list() { fn colors_separate_and_come_back_in_the_measured_spaces() { for name in [FOGRA51_CMYK, FOGRA52_CMYK] { let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); - for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], [0.5, 0.5, 0.5], [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] { + // A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure + // L* 11.43 and 26.36), so it comes back whatever the gamut check says. + let gray = [0.5, 0.5, 0.5]; + for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] { let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric); assert!(inks.iter().sum::() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}"); - if cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD { + if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD { let back = cms.cmyk_to_srgb(inks, false); let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back)); assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})"); diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index e8cf6e74f7..9ff6783115 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -617,8 +617,10 @@ impl Dest { /// The catalog entries `set` asks for (none in PDF/A files, see [`warnings`]); a PDF/X file's /// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one. -/// A profile computed for a registered printing condition ([`cms::characterization`]) gives the -/// condition identifier and registry the settings leave blank. +/// When the settings leave the condition identifier blank, a profile computed for a registered +/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier, +/// and its registry when the settings leave the registry blank too. An identifier set in the +/// settings is written as given, with the settings' registry. fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { let o = &set.output; if set.standard == Standard::PdfA2b { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 54c38b0433..bc51e9bcb5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1879,7 +1879,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. - - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), 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.66). A PDF/X output intent made with one names `FOGRA51` or `FOGRA52` in the `http://www.color.org` registry and embeds the profile. The 300% ink limit and black generation are VectorCraft's own values. + - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), 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`. - **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`. From 119d8c0264991425d89120e0a6d06d7bb2325e30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 13:59:04 -0800 Subject: [PATCH 05/84] Color: keep the paper for absolute colorimetric Generic CMYK conversions Convert to Working Space now passes the absolute Lab of a Generic-type source (Generic CMYK, FOGRA51, FOGRA52) to the destination for the absolute colorimetric intent, so the source paper tint carries into the converted inks. CMYK to RGB in those spaces shows the paper with the absolute intent instead of relative white. The PDF/X test also checks the output condition identifier written for Generic CMYK. --- crates/color/src/cms.rs | 20 +++++++++++---- crates/color/src/cms/tests_measured.rs | 34 ++++++++++++++++++++++++++ crates/pdf/src/tests/pdfx.rs | 3 ++- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index e82ad2b548..a99f05fab2 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -508,7 +508,8 @@ impl Cms { /// directly into the RGB profile: not through display sRGB, which would clip colours a wider /// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the /// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before - /// (Generic CMYK compensates in its own model). + /// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the + /// paper colour shows. pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] { let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0)); let src = match &self.cmyk { @@ -521,7 +522,7 @@ impl Cms { }; src.zip(dest) .and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc)) - .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false))) + .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric))) } /// Display sRGB → working CMYK with `intent`. pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] { @@ -534,6 +535,14 @@ impl Cms { _ => lab::srgb_to_lab(self.cmyk_to_srgb(cmyk, false)), } } + /// Lab of a working-space CMYK colour for `intent`: absolute (the paper colour kept) for the + /// absolute colorimetric intent in a Generic-type space, otherwise [`Self::cmyk_to_lab`]. + fn cmyk_to_lab_for(&self, cmyk: [f32; 4], intent: Intent) -> Lab { + match &self.cmyk { + CmykSpace::Generic(g) if intent == Intent::AbsoluteColorimetric => g.to_lab_abs(cmyk.map(|v| v.clamp(0.0, 1.0))), + _ => self.cmyk_to_lab(cmyk), + } + } /// Lab of working-space CMYK as it displays: [`Self::cmyk_to_lab`] plus, for the built-in /// Generic CMYK, the black-point compensation of [`Self::cmyk_to_srgb`] (its press black shows /// as black). Unclipped, for interpolating tables. @@ -623,8 +632,9 @@ impl Cms { /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to /// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded /// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's - /// black-point compensation; CMYK goes through Lab when either space is built in. Grey and - /// Lab colours stay as they are. + /// black-point compensation; CMYK goes through Lab when either space is built in, with a + /// Generic-type source's paper kept for the absolute colorimetric intent. Grey and Lab colours + /// stay as they are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -646,7 +656,7 @@ impl Cms { }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent), + _ => dest.lab_to_cmyk(self.cmyk_to_lab_for(inks, intent), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 4c8508f780..7bf5735c7a 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -193,6 +193,40 @@ fn colors_separate_and_come_back_in_the_measured_spaces() { assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue)); } +/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces. +fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab { + match &cms.cmyk { + CmykSpace::Generic(g) => g.to_lab_abs(cmyk), + CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"), + } +} + +#[test] +fn absolute_cmyk_to_rgb_shows_the_paper() { + for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric); + assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}"); + assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}"); + } +} + +#[test] +fn absolute_cmyk_conversion_keeps_the_source_paper() { + // Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6), + // so printing it on FOGRA51 paper takes ink. + let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric) + else { + panic!("a CMYK colour converts to CMYK"); + }; + let inks = [c, m, y, k]; + assert!(inks.iter().sum::() > 0.01, "{inks:?}"); + let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4])); + assert!(de < 2.0, "{inks:?}: ΔE {de}"); +} + #[test] fn the_profiles_carry_the_paper_and_the_data_source() { for c in &measured::CONDITIONS { diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index 5cfcebf782..a3d4af69b0 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -216,7 +216,8 @@ fn a_registered_condition_profile_names_its_condition_and_embeds_itself() { assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)")); // Other profiles keep their name as the identifier, with no registry. let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap()); - assert!(!t.contains("/RegistryName"), "{t}"); + let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)"); + assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}"); } #[test] From 2ab519a6308b2d9d9e02e898f680a5cdfe31e6e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:04:09 -0800 Subject: [PATCH 06/84] Packaging Tools: a crease, partial cut or perforation can fold at its own angle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Set Fold Angle… (Object › Plug-ins › Packaging Tools) gives the selected fold lines their own fold angle, from -180° to 180°, in place of their role's 90° away from or toward the print, to the millionth of a degree; reset: true takes it away. The angle is kept in the line's data under vc-fold-angle, which native files and SVG with Preserve Editing keep and plain SVG export leaves out of the path's attributes. A line keeps its angle when it is given another role. The Fold Lines panel shows a Fold Angle field for the selected lines it can change, empty when they differ, and a Reset button. - addon.packaging.setFoldAngle is one undo step, none when nothing changes, and is dimmed while the selection holds no Crease, Partial Cut or Perforation line that is neither locked nor hidden. An angle stored as other text for the same number counts as unchanged. - addon.packaging.roles also returns foldLines, foldAngle, ownAngles and storedAngles for the lines Set Fold Angle can change, which are none while nothing is selected. - A hinge folds at the angle of the line with the most length in it, counting a line the planar map splits into pieces whole and a line's subpaths on top of each other once; among lines of equal length the lowest id wins, in any line order. Before, it took the role of its longest piece, so a hinge whose lines have different roles can now fold the other way when a split line is the longer one. - Fold Preview: a panel folded flat onto another (180°) is drawn behind that panel's printed side, and at -180° in front of it; a flap folded back over a folded panel lies between it and the panel before; a 0° hinge keeps its panel level with its parent. Panels in one plane keep their order when the panels they fold from are seen edge on, and a panel that comes round onto another's plane lies on the side it came from. Only panels in one plane stack by these rules; panels in different planes go by depth, so folds a hair short of flat stay in order wherever the blank lies in the document. The stack is worked out from the blank's largest panel whichever panel the window folds about, so a double-click on another panel moves the blank without changing which panel shows. Panels that 90° folds bring into one plane, such as a carton's closing flaps, now stack by these rules too. - Set Fold Angle…'s dialog keeps the angle within -180° to 180° as it is typed, as the panel's field does. Both show every decimal place the angle has. ui.menuDialog opens the dialog for addon.packaging.setFoldAngle, and gives the command's reason while the selection holds no line it can change. - Set Fold Angle skips a locked or hidden path of a compound path that is named by id or selected without its compound. addon.packaging.setRole (Make Cut Line and the other Make ... Line items) now skips it too; before, it changed the whole compound. - Folding: a hinge whose middle falls in a cutout turns its panel by the side its parent lies on next to the hinge's own pieces, not by a point anywhere inside the parent, which folded a panel the wrong way when the parent also ran on past the hinge. Docs: docs/mcp.md (Fold angles), ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/addons.rs | 2 +- crates/engine/src/cmd/addons/packaging.rs | 8 +- .../engine/src/cmd/addons/packaging/angle.rs | 250 ++++ .../src/cmd/addons/packaging/angle/tests.rs | 409 +++++++ .../engine/src/cmd/addons/packaging/check.rs | 6 +- .../engine/src/cmd/addons/packaging/fold.rs | 2 +- .../engine/src/cmd/addons/packaging/roles.rs | 73 +- .../engine/src/cmd/addons/packaging/tests.rs | 16 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/mcp/src/ui_catalog.rs | 2 +- crates/three-d/src/fold.rs | 63 +- crates/three-d/src/fold/pose.rs | 157 ++- crates/three-d/src/fold/raster.rs | 248 +++- crates/three-d/src/fold/raster/tests.rs | 1027 ++++++++++++++++- crates/three-d/src/fold/tests.rs | 207 +++- crates/ui-egui/src/addons/packaging.rs | 87 +- .../src/addons/packaging/preview/tests.rs | 2 + crates/ui-egui/src/addons/packaging/tests.rs | 159 ++- crates/ui-egui/src/dialogs/command.rs | 9 + crates/ui-egui/src/dialogs/form.rs | 8 + crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/menus/invoke.rs | 2 + crates/ui-egui/src/menus/run.rs | 5 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/numeric.rs | 15 + docs/mcp.md | 67 +- 56 files changed, 2882 insertions(+), 90 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/angle.rs create mode 100644 crates/engine/src/cmd/addons/packaging/angle/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index ea37f12caf..9b15d9afc3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 359fc8761f..67a75de367 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -839,7 +839,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{fold_source, print_hidden}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..32f8cfa645 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{fold_source, print_hidden}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..779b044358 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -2,13 +2,16 @@ //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each //! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold -//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu -//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set +//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins › +//! Packaging Tools) and its Fold Lines panel are the UI's. +mod angle; mod check; mod fold; mod roles; +pub use angle::{FoldAngles, selection_fold_angles}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -17,6 +20,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..b458a3e410 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -0,0 +1,250 @@ +//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease, +//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of +//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a +//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side. + +use std::collections::HashSet; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::kept_angle; + +use super::super::super::edit::refuse_symbol_part; +use super::super::super::overprint::edit_counted; +use super::super::super::pathops::number_given; +use super::super::super::{CommandSpec, bad, cmd, switch_or}; +use super::check::kind; +use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots}; +use crate::{Result, Session}; + +/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export +/// leaves `vc-` keys out. +pub(crate) const KEY: &str = "vc-fold-angle"; + +const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The range a fold angle may take, in degrees. +const RANGE: std::ops::RangeInclusive = -180.0..=180.0; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.setFoldAngle", + "Set Fold Angle…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}", + has_fold_line, + set_fold_angle + )] +} + +/// Why Set Fold Angle has nothing to change. +const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + +/// The last answer of [`has_fold_line`], with what it was for. +struct Answer { + /// The document (a weak reference keeps another document from taking the same address). + doc: Weak, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + found: bool, +} + +thread_local! { + /// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the + /// document, its revision and the objects looked at. + static LAST_ANSWER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object. +fn has_fold_line(s: &Session) -> std::result::Result<(), String> { + refuse_symbol_part(s).map_err(|e| e.to_string())?; + let st = s.doc().map_err(|e| e.to_string())?; + let objects = &st.selection.objects; + let kept = LAST_ANSWER.with_borrow(|last| match last { + Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found), + _ => None, + }); + let found = kept.unwrap_or_else(|| { + // An id of no object (given as `ids`) is left to the command, which names it. + let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects); + LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found })); + found + }); + if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) } +} + +/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through +/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`] +/// takes them, an object inside another one given is left out (a crease in a selected layer counts +/// no more than the layer does), a layer is left out, and a path of a compound path stands for the +/// compound path, which holds its role, unless it is locked or hidden. +fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool { + fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool { + match &n.kind { + // A group's clipping path draws no stroke. + NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)), + _ => hit(n), + } + } + let table = RoleTable::of(d); + let editable = d.editable(); + let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id); + let given: HashSet = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + let a = d.ancestry(id)?; + let (_, up) = a.split_last()?; + if up.iter().any(|p| given.contains(p)) { + return None; + } + match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) { + // A locked or hidden path of a compound path is left out, as `editable_members` leaves it. + Some(_) if !editable(id) => None, + Some(compound) => Some(compound), + None => Some(id), + } + }; + // An object given twice is looked through once. + let mut seen = HashSet::new(); + roots + .iter() + .filter_map(|id| outer(*id)) + .filter(|id| seen.insert(*id)) + .filter_map(|id| d.node(id)) + .filter(|n| !n.is_layer()) + .any(|n| find(n, &hit)) +} + +/// The text `n`'s data holds under [`KEY`], if any. +fn stored(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from +/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as +/// no angle of its own. +pub(super) fn own_angle(n: &Node) -> Option { + stored(n)?.trim().parse::().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle) +} + +/// Whether a line with `role` folds: every role but Cut. +pub(super) fn folds(role: Role) -> bool { + kind(role).fold_angle().is_some() +} + +/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed. +fn store(d: &mut Document, id: NodeId, angle: Option) -> bool { + // `+ 0.0` turns -0 into 0, so a line set to 0° reads "0". + let text = angle.map(|a| format!("{}", a + 0.0)); + // Read first: taking the node to change it copies it, its geometry included. An angle stored + // as other text for the same number ("45.0") is kept; a reset removes any stored text. + let same = |n: &Node| match angle { + Some(a) => own_angle(n) == Some(a), + None => stored(n).is_none(), + }; + if d.node(id).is_none_or(same) { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.edit_attrs(|a| match text { + Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = text, + None => a.data.push((KEY.into(), text)), + }, + None => a.data.retain(|(k, _)| k != KEY), + }); + true +} + +fn set_fold_angle(s: &mut Session, p: &Value) -> Result { + let angle = number_given(p, "angle", SET_FOLD_ANGLE)?; + let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?; + let angle = match (angle, reset) { + (Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")), + (None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")), + (Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")), + // Kept to the millionth of a degree, the angle the line folds at. + (a, _) => a.map(kept_angle), + }; + let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?; + let d = &s.doc()?.doc; + let (targets, skipped) = role_targets(d, &roots, false); + let mut skipped = skipped + named; + let mut ids = folding(d, &RoleTable::of(d), &targets); + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + skipped += targets.len() - ids.len(); + if ids.is_empty() { + return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE)); + } + let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" }; + let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order. +fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect() +} + +/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip +/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FoldAngles { + /// How many lines that fold it can change. + pub lines: usize, + /// The angle they all fold at (their own or their role's); `None` when they differ or there + /// are none. + pub angle: Option, + /// How many of them have an angle of their own. + pub own: usize, + /// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away. + pub stored: usize, +} + +/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them +/// with no `ids` (nothing, while it would refuse the selection). +pub fn selection_fold_angles(s: &Session) -> FoldAngles { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots), + _ => FoldAngles::default(), + } +} + +/// The [`FoldAngles`] of the outermost objects `roots` of `d`. +pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { + let table = RoleTable::of(d); + let editable = d.editable(); + let mut f = FoldAngles::default(); + for n in role_targets(d, &editable_members(d, roots.to_vec()).0, false).0.iter().filter_map(|id| d.node(*id)) { + // The role first: whether an object can be edited can take its bounds to find out. + if let Some(role) = table.role_of(n) + && folds(role) + && editable(n.id) + { + f.add(n, role); + } + } + f +} + +impl FoldAngles { + /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. + pub(super) fn add(&mut self, n: &Node, role: Role) { + let Some(default) = kind(role).fold_angle() else { return }; + let own = own_angle(n); + let a = own.unwrap_or(default); + self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) }; + self.lines += 1; + self.own += usize::from(own.is_some()); + self.stored += usize::from(stored(n).is_some()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -0,0 +1,409 @@ +//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it. + +use serde_json::{Value, json}; + +use super::{KEY, fold_angles, own_angle}; +use crate::*; + +const SET: &str = "addon.packaging.setFoldAngle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(SET, &p).unwrap_err().to_string() +} + +/// The text object `id`'s data holds under the fold angle key. +fn stored(s: &Session, id: u64) -> Option { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone())) +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases: top, right, bottom, left). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of +/// its outline's points (absolute moves and lines only) is above the base. +fn top_wall(p: &Value) -> bool { + let d = p["outline"].as_str().unwrap(); + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + (ys.0 + ys.1) / 2.0 < 140.0 +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +#[test] +fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + assert_eq!(steps(&s), before + 1, "one undo step"); + // The same angle again changes nothing and records no undo step. + let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // An angle is kept to the millionth of a degree, so one closer to 45 than that is 45. + let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}"); + s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap(); + assert_eq!(stored(&s, creases[3]).as_deref(), Some("180")); + s.execute("edit.undo", &json!({})).unwrap(); + // A number as text, and the selection when ids is left out; -0 is kept as 0. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + let r = s.execute(SET, &json!({"angle": "-0"})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "{r}"); + assert_eq!(stored(&s, creases[1]).as_deref(), Some("0")); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}"); + assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None)); + // Nothing left to reset: no undo step. + let at = steps(&s); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at)); + // Undo brings the angle back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); +} + +#[test] +fn bad_angles_and_targets_are_refused() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let plain = path(&mut s, "M10 10 L50 50"); + let before = steps(&s); + let ids = json!([creases[0]]); + assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`")); + assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both")); + assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false")); + // A cut line and a path without a role do not fold. + assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation")); + // An id of no object is named as such, alone or beside a crease. + assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999")); + assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); + // The ends of the range are allowed; cut lines and plain paths among fold lines are skipped. + let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}"); + s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("180")); + assert_eq!(stored(&s, outline), None); +} + +#[test] +fn set_fold_angle_is_dimmed_without_a_line_it_can_change() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok(); + assert!(!enabled(&s), "nothing selected"); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!(!enabled(&s), "a cut line does not fold"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap(); + assert!(enabled(&s)); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed"); + // A group holding a crease is enough. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + assert!(enabled(&s)); + // A layer selected with a crease in it: the crease is inside the layer, which is left out, as + // Set Fold Angle itself leaves them out. + let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap(); + s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert!(!enabled(&s), "dimmed as the command refuses it"); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); + // With nothing selected the counts are the document's, but Set Fold Angle takes no line. + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute(SET, &json!({"angle": 30})).is_err()); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!(r["scope"].as_str(), Some("document"), "{r}"); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}"); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); +} + +#[test] +fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold"); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(1), "{r}"); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line"); +} + +#[test] +fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap(); + let f = crate::cmd::selection_fold_angles(&s); + assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}"); +} + +#[test] +fn a_locked_crease_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(stored(&s, creases[1]), None); +} + +#[test] +fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320")); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + role(&mut s, "crease", &[compound]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(NodeId(a)) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation")); + // Named twice, it is skipped once. + let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, compound), None); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + assert_eq!(stored(&s, compound), None); + // With its compound, given or selected, the locked path is part of the compound, not skipped. + let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute("select.set", &json!({"ids": [compound, a]})).unwrap(); + let r = s.execute(SET, &json!({"angle": 25})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap(); + // The compound named by id takes the angle; its other path, not locked, names it too. + let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap(); + assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}"); + assert_eq!(stored(&s, compound).as_deref(), Some("30")); +} + +#[test] +fn a_damaged_angle_reads_as_none_of_its_own() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap(); + for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] { + n.edit_attrs(|a| { + a.data.retain(|(k, _)| k != KEY); + a.data.push((KEY.into(), text.into())); + }); + assert_eq!(own_angle(&n), want, "{text:?}"); + } +} + +#[test] +fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let id = NodeId(creases[0]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into()))); + } + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0")); + s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]), None); + // A reset also removes text that is not an angle. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}"); +} + +#[test] +fn a_line_keeps_its_own_angle_through_a_role_change() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + role(&mut s, "partialCut", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); + role(&mut s, "none", &[creases[0]]); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + role(&mut s, "crease", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); +} + +#[test] +fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned()); + assert!(svg.contains(" = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + assert!(angles.contains(&120.0), "{r}"); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // The top wall (y 100 to 140) folds at 45°. + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut angles: Vec = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + angles.sort_by(f64::total_cmp); + assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]); + for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) { + let z = vector(&p["frame"]["z"]); + let top = top_wall(p); + let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}"); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut up = 0; + for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) { + // The top wall folds toward the print, so its printed side faces back over the base + // (toward -y in the y-up frame); the other walls stand square to the base as before. + let top = top_wall(p); + let z = vector(&p["frame"]["z"]); + if top { + assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}"); + up += 1; + } else { + assert!(z[2].abs() < 1e-9, "{p}"); + } + } + assert_eq!(up, 1); +} + +#[test] +fn roles_reports_the_angle_the_selected_fold_lines_share() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}"); + s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap(); + assert!(r["foldAngle"].is_null(), "{r}"); + // A partial cut folds at -90° unless it has an angle of its own. + role(&mut s, "partialCut", &[creases[2]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}"); +} + +#[test] +fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap(); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}"); + assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}"); + // So Reset has nothing to change, as the panel shows it. + let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + let (lines, angle, own) = { + let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]); + (f.lines, f.angle, f.own) + }; + assert_eq!((lines, angle, own), (1, Some(90.0), 0)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::angle::own_angle; use super::roles::{Role, RoleTable, can_carry, role_targets}; use crate::{Result, Session}; @@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) } -fn kind(role: Role) -> LineKind { +/// The kind of fold line a line with `role` is. +pub(super) fn kind(role: Role) -> LineKind { match role { Role::Cut => LineKind::Cut, Role::Crease => LineKind::Crease, @@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) }); } Lines { scope, lines, non_printing } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..00e857540d 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fold", [], None, - "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", has_doc, fold_command )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use super::super::super::edit::{outermost, refuse_symbol_part, roots_of}; use super::super::super::overprint::edit_counted; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{Result, Session}; @@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool { } } +/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of +/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that +/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out +/// before it stands for its compound, and how many such paths were left out, each once. +pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec, usize)> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + let roots = checked_ids_or_selection(s, p, command)?; + return Ok(editable_members(&s.doc()?.doc, roots)); + } + refuse_symbol_part(s)?; + let st = s.doc()?; + // An object inside another selected one is left out first, as it is from `ids`. + let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc))); + Ok((roots_of(&st.doc, kept), left)) +} + +/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or +/// hidden group or layer, or on a locked artboard), and how many different ones were left out. +pub(super) fn editable_members(d: &Document, ids: Vec) -> (Vec, usize) { + let ok = d.editable(); + let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let mut left = std::collections::HashSet::new(); + let kept = ids + .into_iter() + .filter(|id| { + let out = member(*id) && !ok(*id); + if out { + left.insert(*id); + } + !out + }) + .collect(); + (kept, left.len()) +} + /// The objects under the outermost objects `roots` that can carry a role, through groups and clip /// groups, each once, and /// how many of `roots` and their members can't (text, images, symbol instances and other objects). @@ -257,7 +293,7 @@ pub fn specs() -> Vec { "Make Fold Line", ["Object", "Plug-ins", "Packaging Tools"], None, - "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", has_selection, set_role ), @@ -266,7 +302,7 @@ pub fn specs() -> Vec { "Fold Lines", [], None, - "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes", has_doc, roles ), @@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai fn set_role(s: &mut Session, p: &Value) -> Result { let role = role_param(p, SET_ROLE, true)?; let overprint = switch_or(p, "overprint", true, SET_ROLE)?; - let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (roots, left) = taken_roots(s, p, SET_ROLE)?; let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + let skipped = skipped + left; if ids.is_empty() { return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); } @@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result { fn roles(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, ROLES)?; - let d = &s.doc()?.doc; + // The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand + // for its compound there. They are the objects the counts are of unless such a path was left + // out, and only then are those found apart. + let (taken, left) = taken_roots(s, p, ROLES)?; + let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) }; + let st = s.doc()?; + let d = &st.doc; let (scope, ids) = match (given, roots.is_empty()) { (true, _) => ("ids", role_targets(d, &roots, false).0), (false, false) => ("selection", role_targets(d, &roots, false).0), (false, true) => ("document", document_targets(d)), }; + let whole = scope == "document"; + // The lines Set Fold Angle can change are those of the objects it takes: with nothing selected, + // or a selection that holds no such object (only a layer and what is in it), it takes none, + // though the counts are the document's. + let angles_of_all = given || !roots.is_empty(); let table = RoleTable::of(d); let mut counts = [0usize; 4]; - for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + let editable = d.editable(); + let mut angles = super::angle::FoldAngles::default(); + for n in ids.iter().filter_map(|id| d.node(*id)) { + let Some(r) = table.role_of(n) else { continue }; if let Some(c) = counts.get_mut(r.index()) { *c += 1; } + if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) { + angles.add(n, r); + } + } + if !whole && left > 0 { + angles = super::angle::fold_angles(d, &angle_roots); } let rows: Vec = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) }) .collect(); - Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) + Ok(json!({ + "roles": rows, "scope": scope, "selected": roots.len(), + "foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored, + })) } fn set_role_swatch(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() { let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // A locked member named by id is skipped, and its compound keeps its role. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(a) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden")); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden")); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // Named twice, it is skipped once. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}"); } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5a10ae3d9c..dbd4941748 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..ae3075f9be 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1411,7 +1411,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|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; 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)", + "{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|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, 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)", ), ( "ui.widthPointEdit", diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..14bc32fa6d 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -79,14 +98,17 @@ impl Panel { /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is -/// ([`LineKind::fold_angle`]). +/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most +/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle +/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its +/// pieces may not have at the middle of `from` to `to`. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, + pub on: Point, pub keys: Vec, pub straight: bool, pub angle: f64, @@ -1297,9 +1319,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1368,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } @@ -1331,7 +1378,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option { mod pose; pub mod raster; -pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon}; #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs index 650ab54291..91a6cdfb12 100644 --- a/crates/three-d/src/fold/pose.rs +++ b/crates/three-d/src/fold/pose.rs @@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in}; /// test and the preview. pub const MAX_POLYGON_POINTS: usize = 1 << 16; +/// How far apart two placements of a panel may turn a unit direction and still be one placement: +/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth +/// of a degree from another ([`super::kept_angle`], 1.7e-8). +const TURNED: f64 = 1e-10; + type V3 = [f64; 3]; fn sub(a: V3, b: V3) -> V3 { @@ -105,14 +110,24 @@ impl Pose { let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } } + + /// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the + /// flat blank's own terms. + fn about(&self, origin: V3) -> Pose { + Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) } + } } -/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no -/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it -/// and the base. +/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold +/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where +/// it is) and how many hinges lie between it and the base. #[derive(Clone, Debug)] pub struct FoldedPanel { pub pose: Pose, + /// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less + /// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a + /// blank far from the document's origin to the size of the blank. + pub local: Pose, pub parent: Option, pub depth: usize, } @@ -141,6 +156,28 @@ pub struct Folded { pub hinges: Vec, /// Pairs of panels (`a` < `b`) that pass through each other. pub collisions: Vec<(usize, usize)>, + /// The fold tree that panels folded flat onto each other stack by. + pub stack: Stack, + /// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about. + pub origin: [f64; 3], +} + +/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its +/// `root`), whichever panel is the base, so choosing another base moves the folded blank without +/// changing which panel shows where they lie flat on each other. The base's own tree when the two +/// join different panels. +#[derive(Clone, Debug, Default)] +pub struct Stack { + pub root: usize, + /// Each panel's parent in this tree. + pub parent: Vec>, + /// The panels in breadth-first order from `root`, the panels not joined to it last. + pub order: Vec, + /// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector + /// in the parent's plane, across the hinge to the side the fold took the parent to be on, as + /// long as the corners of the parent's bounds reach that way. `None` for `root` and the + /// panels not joined to it. + pub toward_parent: Vec>, } /// The panel of `blank` that `p` (document coordinates) lies in. @@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }); } let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); - let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // The corners of each panel's bounds (flat). + let corners: Vec> = blank + .panels + .iter() + .map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y))))) + .collect(); + let origin = corners + .iter() + .flatten() + .flatten() + .fold(None, |b: Option<(V3, V3)>, c| { + Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0]))) + }) + .map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5)); + let placing = Placing { blank, by_panel: &by_panel, centers: ¢ers, corners: &corners, origin }; + let (panels, tree, order, toward_parent) = place(&placing, base, amount); // Closing hinges are measured with every hinge at its full angle, so a blank that closes when // folded is not reported open part of the way there. - let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) }; let measured = full.as_deref().unwrap_or(&panels); let hinges = blank .hinges @@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }) .collect(); let collisions = collisions(blank, &panels, tolerance); - Some(Folded { base, panels, order, hinges, collisions }) + let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent }; + let stack = match base_panel(&blank.panels) { + Some(root) if root != base => { + let (placed, root_tree, root_order, toward) = place(&placing, root, amount); + // Whether the root's tree puts every panel where the base's does, moved with the root + // (which lies at the identity in its own): the same hinges do, and around a loop of + // panels another tree can leave out a fold that placed them. Each panel's turn is + // compared to within `TURNED` whatever its size or place, and its inside point by the + // poses about `origin` (`local`), to rounding at that distance from it. + let agrees = |r: &FoldedPanel| { + let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b))); + placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| { + let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some()); + let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin)); + let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + .into_iter() + .all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED); + joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at)))) + }) + }; + match panels.get(root) { + // The root's tree in the base's terms. + Some(r) if root_tree == tree || agrees(r) => Stack { + root, + parent: placed.iter().map(|p| p.parent).collect(), + order: root_order, + toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(), + }, + _ => own, + } + } + _ => own, + }; + Some(Folded { base, panels, order, hinges, collisions, stack, origin }) } -/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its -/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not -/// joined to the base last). -fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { +/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and +/// [`Stack::toward_parent`]. +type Tree = (Vec, Vec, Vec, Vec>); + +/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and +/// bounds corners (flat), and the point the panels' local poses are about. +struct Placing<'a> { + blank: &'a Blank, + by_panel: &'a [Vec], + centers: &'a [Option], + corners: &'a [Option<[V3; 4]>], + origin: V3, +} + +/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined +/// to the base last), and [`Stack::toward_parent`]. +fn place(placing: &Placing, base: usize, amount: f64) -> Tree { + let Placing { blank, by_panel, centers, corners, origin } = *placing; let n = blank.panels.len(); - let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut toward_parent: Vec> = vec![None; n]; let mut reached = vec![false; n]; let mut tree = vec![false; blank.hinges.len()]; let mut order = Vec::with_capacity(n); @@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u // The parent on the left of the hinge's direction, the child on its right. The side is // read next to the hinge, so a parent with a notch or an arm past the hinge's line still // turns the child the right way; the panel's inside point is the fallback. - let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) { Some(left) => left, None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), }; @@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u continue; } if let Some(slot) = panels.get_mut(child) { - *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + let local = parent.local.turned_about(sub(from, origin), axis, theta); + *slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 }; + } + // Across the hinge, to its left: into the parent, as far as the corners of its bounds + // reach that way. + let into = [-axis[1], axis[0], 0.0]; + let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max)); + if let Some(slot) = toward_parent.get_mut(child) { + *slot = Some(parent.pose.turn(scale(into, reach))); } if let Some(r) = reached.get_mut(child) { *r = true; @@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u } } order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); - (panels, tree, order) + (panels, tree, order, toward_parent) } /// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) -/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and -/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset -/// tells them apart. The nearest offset is tried first. -fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { +/// next to it: `true` when a point just off the line on the left is inside it and the matching +/// point on the right is not, `false` the other way round. `on` (a point of the line where the +/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an +/// eighth of the way along, each with the nearest offset first; `None` when no point tells the +/// sides apart. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option { let bp = outline.to_bezpath(); - let mid = scale(add(from, to), 0.5); let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; let doc = |v: V3| Point::new(v[0], -v[1]); let mut offsets = [1e-3, 0.25, len * 0.01]; offsets.sort_by(f64::total_cmp); - offsets.into_iter().find_map(|off| { - let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); - (l != r).then_some(l) + let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t))); + std::iter::once(on).chain(along).find_map(|at| { + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0); + (l != r).then_some(l) + }) }) } diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 9cccbaf6d9..4db9cd728f 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096; pub const MAX_PIXELS: u32 = 1 << 21; /// The share of the eye's distance a panel is cut at in front of the eye. const NEAREST: f64 = 1e-3; -/// How far apart (points of view depth) two panels may be and still tie. +/// How far apart (points of view depth) two panels in one plane may be and still tie. const TIE: f64 = 1e-4; +/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one +/// plane. +const PARALLEL: f64 = 1e-9; +/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding, +/// as this many times the precision of a number at their distance from the origin for each hinge +/// that placed them. +const COPLANAR: f64 = 16.0 * f64::EPSILON; +/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count +/// as along it. +const ALONG: f64 = 1e-6; /// The light's direction: above, to the left of and toward the viewer. const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; @@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) } -fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { +fn map_panel(camera: &Camera, pose: &super::Pose) -> Option { let r = camera.rotation(); - let turn = |v: V3| mul(&r, f.pose.turn(v)); + let turn = |v: V3| mul(&r, pose.turn(v)); let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); - let o = camera.to_view(f.pose.t); + let o = camera.to_view(pose.t); let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); let normal = turn([0.0, 0.0, 1.0]); let (w, k, printed) = match camera.eye() { @@ -326,18 +336,23 @@ struct Target { panel: Vec, } -/// One panel's fill: its map, rank (for ties), panel number and colors. +/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as +/// [`planes`] gives them), panel number and colors. struct Fill<'a> { mapped: &'a Mapped, rank: u16, + planes: &'a [u16], panel: u16, print: Option<&'a Print>, + /// The flat point the map is about ([`Folded::origin`]): a flat point less it is what + /// `mapped` maps. + origin: [f64; 2], inside: [f32; 4], outside: [f32; 4], } impl Fill<'_> { - /// The document point under pixel center `(x, y)`, or `None` behind the eye. + /// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye. fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) @@ -346,7 +361,7 @@ impl Fill<'_> { /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { let base = if self.mapped.printed { - let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint)); let under = 1.0 - p[3] / 255.0; [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] } else { @@ -370,8 +385,12 @@ impl Fill<'_> { let [a, b, c] = self.mapped.depth; let z = u * a + v * b + c; let i = row * target.width + col; - let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; - let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue }; + // Panels in one plane tie within `TIE` and stack by rank; panels in different planes + // that pass this close go by depth alone. Panel numbers count from 1. + let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p)); + let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a)); + let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb }; if !wins { continue; } @@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option>> { Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) } +/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each +/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed +/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are +/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so +/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between +/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the +/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later +/// one nearer seen from one side of their plane and the earlier one seen +/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other +/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel +/// it branched from, after leaving it, takes the side of that plane it came back from for every +/// step up to the one it left by: the side the nearest panel out of the plane lies on from the +/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as +/// [`planes`] does. +fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec { + let n = folded.panels.len(); + // Each panel's layer holds a step per fold up to the base: past the panels a blank can have, + // the order alone decides. So it does when every panel lies where it lies flat (a fold amount + // of 0), as panels there do not overlap. + if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) { + return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(); + } + // The step each panel takes off its parent: the parent's printed side, negated for a positive + // angle; none for a 0° hinge or a panel without a parent. + // The parents are those of [`Folded::stack`], so the panels stack the same about any base. + let stack = &folded.stack; + let parent_of = |c: usize| stack.parent.get(c).copied().flatten(); + let mut step: Vec> = vec![None; n]; + for c in 0..n { + let Some(p) = parent_of(c) else { continue }; + let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue }; + let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue }; + let [x, y, z] = parent.pose.normal(); + *slot = match h.angle { + a if a > 0.0 => Some([-x, -y, -z]), + a if a < 0.0 => Some([x, y, z]), + _ => None, + }; + } + // Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's + // plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next + // to its parent, before any later step, however many folds deep. + // Each panel's place in the stack's order. + let mut place = vec![0usize; n]; + for (i, &pi) in stack.order.iter().enumerate() { + if let Some(slot) = place.get_mut(pi) { + *slot = i; + } + } + // Each step also carries the place in `folded.order` of the panel that took it, so panels whose + // steps match up to a fold that branches stack by that branch: the later panel nearer seen from + // one side of their plane, the earlier one seen from the other, so the two sides show opposite + // panels. The rest of a branch stays with it. + // Whether the view sees each panel's printed side. + let sees_print: Vec = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect(); + // The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it + // lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1 + // the other; `None` when every panel on the way lies in the plane. The plane is the one + // [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it + // and a stack folded a hair short of flat goes by depth instead. + let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> { + let (mut child, mut up) = (pi, parent_of(pi)); + for _ in 0..n { + let c = up?; + if planes.get(c) != planes.get(pi) + && let Some(Some(way)) = stack.toward_parent.get(child) + { + let d = dot(*way, n_view); + if d != 0.0 { + return Some((c, if d > 0.0 { 1 } else { -1 })); + } + } + (child, up) = (c, parent_of(c)); + } + None + }; + let layer = |pi: usize| -> Vec<(i8, i64)> { + let Some(f) = folded.panels.get(pi) else { return vec![] }; + let printed = sees_print.get(pi).copied().unwrap_or(true); + let n_view = { + let [x, y, z] = f.pose.normal(); + if printed { [x, y, z] } else { [-x, -y, -z] } + }; + let mut out = vec![]; + let mut at = Some(pi); + // From the nearest panel out of the plane on the way to the base, every step counts as on + // the side of the plane that panel lies on: a panel that comes round onto the plane of a + // panel it branched from lies on the side it came back from, whatever its folds before. + let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s)); + let mut returned = false; + // A panel's chain to the base is at most the panel count long. + for _ in 0..n { + let Some(c) = at else { break }; + returned |= Some(c) == back_at; + if let Some(Some(s)) = step.get(c) { + let d = if returned { f64::from(back_side) } else { dot(*s, n_view) }; + // Branches off one panel stack one way seen from that panel's printed side and the + // other way from its back, so the panels of one plane that compare a step off one + // parent agree, however the parent is turned. + let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX)); + // A parent seen edge on gives no side: the panel that took the step gives it, and + // when that is edge on too, the largest part of the view's normal does. Each choice + // gives two panels of one plane the same sign however an edge-on dot rounds, and + // each turns over with the side of the plane the view is on. + let faces = |f: &super::FoldedPanel| { + let d = dot(f.pose.normal(), n_view); + (d.abs() > ALONG).then_some(d >= 0.0) + }; + // The view's normal in the root's flat terms, so this too is the same about any base. + let largest = || { + let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m); + let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::()); + local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0) + }; + let parent = parent_of(c).and_then(|p| folded.panels.get(p)); + let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest); + let branch = if parent_faces { branch } else { -branch }; + // Any step that is not along the plane counts whole, so a step seen from two panels + // of one plane counts the same for both. + out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch)); + } + at = parent_of(c); + } + out.reverse(); + out + }; + // Layers compared step by step, a missing step as none. + let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| { + (0..a.len().max(b.len())) + .map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0)))) + .find(|o| o.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }; + // A panel alone in its plane ties with no other, so its layer is not worked out. + let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)]; + for &p in planes { + if let Some(c) = in_plane.get_mut(usize::from(p)) { + *c += 1; + } + } + let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1); + let mut keys: Vec<(Vec<(i8, i64)>, usize)> = + folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect(); + // Then by the stack's order, for panels that stack as one. + let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX); + keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1))); + let mut ranks = vec![0u16; folded.order.len()]; + for (r, &(_, i)) in keys.iter().enumerate() { + if let Some(slot) = ranks.get_mut(i) { + *slot = u16::try_from(r + 1).unwrap_or(u16::MAX); + } + } + ranks +} + /// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more /// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than /// [`super::MAX_POLYGON_POINTS`] points, are left out. @@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option { Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); - for (rank, &pi) in scene.folded.order.iter().enumerate() { + let planes = planes(scene.folded, scene.blank); + let ranks = tie_ranks(scene.folded, &camera, &planes); + // Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat + // points and the view's center moved to match. + let o = scene.folded.origin; + let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera }; + for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; - let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(mapped) = map_panel(&local, &f.local) else { continue }; let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let rings: Vec> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect(); let projected: Vec> = rings .iter() .map(|r| match near { @@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option { .collect(); let fill = Fill { mapped: &mapped, - rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + rank, + planes: &planes, panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), print: scene.print, + origin: [o[0], o[1]], inside, outside, }; @@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option { Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) } +/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their +/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them +/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the +/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is +/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`] +/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the +/// planes. Past [`super::MAX_PANELS`] panels, one plane for all. +fn planes(folded: &Folded, blank: &Blank) -> Vec { + let n = folded.panels.len(); + if n > super::MAX_PANELS { + return vec![0; n]; + } + let length = |v: V3| dot(v, v).sqrt(); + // Each plane's normal, a point of it, the size of the coordinates that point came from and the + // hinges that placed it. + let mut kinds: Vec<(V3, V3, f64, usize)> = vec![]; + folded + .panels + .iter() + .enumerate() + .map(|(i, f)| { + let o = folded.origin; + let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]); + let (normal, at) = (f.local.normal(), f.local.apply(middle)); + let size = length(at).max(length(middle)); + let same = |(m, p, s, d): &(V3, V3, f64, usize)| { + let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]]; + let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs(); + // Saturating: a `Folded` built by a caller may carry any depth. + let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX)); + length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s)) + }; + let k = kinds.iter().position(same).unwrap_or_else(|| { + kinds.push((normal, at, size, f.depth)); + kinds.len() - 1 + }); + u16::try_from(k).unwrap_or(u16::MAX) + }) + .collect() +} + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 8639615a53..b6251985ca 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; -use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose, Stack}; use super::*; fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { @@ -16,10 +18,12 @@ fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { let n = panels.len(); let folded = Folded { base: 0, - panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + panels: poses.into_iter().map(|pose| FoldedPanel { pose, local: pose, parent: None, depth: 0 }).collect(), order: (0..n).collect(), hinges: vec![], collisions: vec![], + stack: Stack { root: 0, parent: vec![None; n], order: (0..n).collect(), toward_parent: vec![None; n] }, + origin: [0.0; 3], }; (Blank { panels, hinges: vec![], holes: vec![] }, folded) } @@ -135,6 +139,1025 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); } +#[test] +fn of_two_parallel_panels_the_nearer_shows_however_close() { + // 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE` + // equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn + // first. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + for (near, poses) in [(1, vec![moved(2.0), moved(2.0001)]), (0, vec![moved(2.0001), moved(2.0)])] { + let (b, f) = scene_of(vec![whole(), whole()], poses); + assert_eq!(planes(&f, &b).iter().collect::>().len(), 2, "two planes"); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), Some(near)); + } +} + +#[test] +fn a_scene_whose_panels_claim_any_depth_still_draws() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, mut f) = scene_of(vec![whole(), whole()], vec![moved(5.0), moved(5.0)]); + for p in &mut f.panels { + p.depth = usize::MAX; + } + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert!(img.panel_at(50, 50).is_some()); +} + +#[test] +fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() { + // A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // Folds a hair short of flat lie on the same side, everywhere within a tie of the base. + for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] { + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(60.0, 0.0), (60.0, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(angle), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = 1 - f.base; + let views = [ + (front(), true), + (Camera { rotate_y: 180.0, ..front() }, false), + (Camera { perspective: 60.0, ..front() }, true), + (Camera { rotate_y: 180.0, perspective: 60.0, ..front() }, false), + ]; + for (camera, seen_from_print) in views { + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // The point x 40, y 30 of the blank, where the flap lies over the base. + let x = if seen_from_print { 40 } else { 60 }; + let want = if flap_in_front == seen_from_print { flap } else { f.base }; + assert_eq!(img.panel_at(x, 30), Some(want), "{angle}°, seen from the print: {seen_from_print}, {camera:?}"); + } + } +} + +#[test] +fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() { + // A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to + // 100) folded back at 180°, which lies behind the base from x 30 to 60. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2, 0.0), + crease(65.0, 3, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(45, 30), Some(f.base), "the base is in front of the flap behind it"); +} + +#[test] +fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() { + // A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at + // 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at + // x 20 to 30. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = f.panels.iter().position(|p| p.parent == Some(f.base)).expect("the panel folded from the base"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(25, 30), Some(f.base), "the base, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(75, 30), Some(middle), "the folded panel, from the back"); + // Folded about the flap instead, the blank only moves: the flap (x 100 to 110 now) still lies + // between the other two, the 60 pt panel over it on the printed side. + let tip = super::super::panel_at(b, Point::new(105.0, 30.0)).expect("the flap"); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [105.0, -30.0, 0.0], ..front() }; + let wide = super::super::panel_at(b, Point::new(30.0, 30.0)).expect("the 60 pt panel"); + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() { + // The strip of the test above turned 45° and moved to about (3,000,000, 3,000,000) pt, folded + // about its 10 pt flap: the 60 pt panel still lies over the flap on the printed side. + let s = std::f64::consts::FRAC_1_SQRT_2; + let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s); + let poly = + |pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::>(), closed)); + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let panel = |x: f64, y: f64| super::super::panel_at(b, at(x, y)).expect("a panel"); + let (wide, middle, tip) = (panel(30.0, 30.0), panel(80.0, 30.0), panel(105.0, 30.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let c = at(105.0, 30.0); + let at_tip = Camera { center: [c.x, -c.y, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_flat_stack_far_from_the_origin_stays_in_one_plane() { + // A strip from x = 3,000,000 pt: the base (60 pt wide), a 40 pt panel folded back under it at + // 180° and a 35 pt flap folded back at 180° between the two. + let x0 = 3_000_000.0; + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let middle = super::super::panel_at(b, Point::new(x0 + 80.0, 30.0)).expect("the middle panel"); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(planes(&f, b).iter().collect::>().len(), 1, "one plane"); + let draw = |rotate_y| { + let camera = Camera { rotate_y, center: [x0 + 40.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 50) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(middle))); +} + +#[test] +fn a_panel_parallel_to_the_base_a_hair_behind_it_goes_by_depth() { + // A strip 30 pt tall: the base (x 0 to 100), a 20 pt panel folded back at 179.9999° and a 30 pt + // flap at 0.0001° off it, parallel to the base and about 0.000035 pt behind it; then the same + // strip 100,000 pt to the right; then at 179.999999° and 0.000001°, about 0.00000035 pt behind, + // 3,000,000 pt to the right; then with a 1 pt middle panel, about 0.0000000175 pt behind, at the + // origin and 3,000,000 pt to the right. + for (dx, back, w) in + [(0.0, 0.0001, 20.0), (100_000.0, 0.0001, 20.0), (3_000_000.0, 0.000001, 20.0), (0.0, 0.000001, 1.0), (3_000_000.0, 0.000001, 1.0)] + { + parallel_a_hair_behind(dx, back, w); + } +} + +fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(100.0, 2, 180.0 - back), + crease(100.0 + w, 3, back), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = Point::new(115.0 + w + dx, 15.0); + let flap = super::super::panel_at(b, at).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let m = f.panels[flap].pose.place(at); + assert!(m[2] < 0.0 && m[2] > -1e-4, "the flap lies a hair behind the base: {m:?}"); + let draw = |rotate_y| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(flap)), "at x + {dx}, a {w} pt middle panel"); +} + +#[test] +fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() { + // A 4 pt strip, its second half folded back at 179.999999° so it lies a hair behind the first, + // seen at a three-quarter turn with and without perspective: every pixel shows the same panel + // at the origin and 3,000,000 pt right and down. + let draw = |at: f64, perspective: f64| { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::>(), closed)) + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(2.0, 0.0), (2.0, 1.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(179.999999), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let base = super::super::panel_at(b, Point::new(0.5 + at, 0.5 + at)).expect("the base"); + let f = super::super::fold(b, Some(base), 1.0, 0.0001).expect("folds"); + let camera = Camera { rotate_x: 35.0, rotate_y: 40.0, scale: 40.0, perspective, center: [1.0 + at, -0.5 - at, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown: Vec> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.panel_at(x, y).map(|p| p == base)).collect(); + assert!(shown.contains(&Some(true)), "the base shows"); + shown + }; + for perspective in [0.0, 40.0] { + assert!(draw(0.0, perspective) == draw(3_000_000.0, perspective), "perspective {perspective}"); + } +} + +#[test] +fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() { + // A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no + // layer is worked out. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for i in 1..64u32 { + let x = f64::from(i) * 10.0; + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 10.0)], false), + kind: super::super::LineKind::Crease, + key: u64::from(i) + 1, + angle: Some(180.0), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let f = super::super::fold(&blanks[0], None, 0.0, 0.1).expect("folds"); + let ranks = tie_ranks(&f, &front(), &planes(&f, &blanks[0])); + assert_eq!(ranks, (1..=64).collect::>()); +} + +#[test] +fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() { + // A 100 × 100 blank cut into four 50 pt squares by four creases, one per side of the middle + // point. The crease that closes the loop when folded about the largest panel folds at 180° and + // the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap + // lies flat behind the panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let lines = |flat_key: Option| { + let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }), + }; + vec![ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (blanks, issues) = super::super::blanks(&lines(None), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let level = super::super::fold(&blanks[0], None, 1.0, 0.1).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = *blanks[0].hinges[closing].keys.first().expect("a line"); + let (blanks, issues) = super::super::blanks(&lines(Some(key)), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let h = &b.hinges[closing]; + assert_eq!(h.keys, [key]); + let f = super::super::fold(b, Some(h.a), 1.0, 0.1).expect("folds"); + assert!(f.hinges[closing].tree); + // The panel's middle, in pixels: the blank's top left square is pixels 0 to 50. + let middle = |p: usize| { + let c = b.panels[p].outline.bounds().expect("bounds").center(); + (c.x as u32, c.y as u32) + }; + let (x, y) = middle(h.a); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(x, y), Some(h.a), "the panel, from its printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(100 - x, y), Some(h.b), "the flap, from the back"); +} + +#[test] +fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() { + // A 2 × 2 grid of panels joined by 0° creases (the largest at the bottom left), and two flaps + // folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the + // tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way, + // and the stack stays as it is about the largest panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((60.0, 0.0), (60.0, 40.0), 2, 0.0), + crease((60.0, 40.0), (60.0, 100.0), 3, 0.0), + crease((0.0, 40.0), (60.0, 40.0), 4, 0.0), + crease((60.0, 40.0), (100.0, 40.0), 5, 0.0), + crease((100.0, 0.0), (100.0, 40.0), 6, 180.0), + crease((130.0, 0.0), (130.0, 40.0), 7, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = |x: f64, y: f64| super::super::panel_at(b, Point::new(x, y)).expect("a panel"); + let (corner, under, tip) = (at(80.0, 20.0), at(115.0, 20.0), at(135.0, 20.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [135.0, -20.0, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(corner), "the top right panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(under), "the first flap, from the back"); +} + +#[test] +fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() { + // The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the + // left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(52.0, 20.0), (58.0, 20.0), (58.0, 40.0), (52.0, 40.0)], true, Cut, 2, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(80.0, 0.0), (80.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let through_window = draw(front()).panel_at(55, 30); + let from_back = draw(Camera { rotate_y: 180.0, ..front() }).panel_at(45, 30); + let flaps: Vec = (0..b.panels.len()).filter(|&i| i != f.base).collect(); + assert!(through_window.is_some_and(|p| flaps.contains(&p)), "{through_window:?}"); + assert!(from_back.is_some_and(|p| flaps.contains(&p)), "{from_back:?}"); + assert_ne!(through_window, from_back); +} + +#[test] +fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { + // The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to + // 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(90.0, 0.0), (90.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(15.0, 0.0), (15.0, 60.0)], false, Crease, 4, Some(0.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 140 - x in the image. + let right_flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 90.0).abs() < 1e-6)).expect("the right flap"); + let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); + assert_eq!(near == Some(right_flap), far == Some(right_flap), "{near:?} {far:?}"); +} + +#[test] +fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() { + // Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap + // (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and + // the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(20.0, 0.0), (20.0, 60.0)], false, Crease, 2, Some(-180.0)), + line(&[(70.0, 0.0), (70.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (tip, left, right) = (starts_at(0.0), starts_at(20.0), starts_at(140.0)); + let camera = Camera { width: 210, center: [105.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 210 - x in the image. + let (flaps_only, with_tip) = (img.panel_at(210 - 90, 30), img.panel_at(210 - 110, 30)); + if flaps_only == Some(right) { + assert_eq!(with_tip, Some(right), "the right flap covers the left flap and the tip on it"); + } else { + assert_eq!((flaps_only, with_tip), (Some(left), Some(tip)), "the left flap, and the tip on it, cover the right flap"); + } +} + +#[test] +fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() { + // The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to + // 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + // The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base. + for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] { + let base = middle + 20.0; + let end = base + middle + 10.0; + let lines = [ + line(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(base, 0.0), (base, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(base + middle, 0.0), (base + middle, 60.0)], false, Crease, 3, Some(tip_angle)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let tip = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (base + middle)).abs() < 1e-6)).expect("the tip"); + let back = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: back }).expect("drawn"); + assert_eq!(img.panel_at(100 - 25, 30), Some(tip), "{middle} pt, {tip_angle}°"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(25, 30), Some(f.base), "{middle} pt, {tip_angle}°"); + } +} + +#[test] +fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_lid() { + // A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to + // 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps + // meet in one plane 40 pt below the base and overlap from x 140 to 160. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0)); + let lines = [ + line(&[(0.0, 0.0), (300.0, 0.0), (300.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + crease(60.0, 2), + crease(100.0, 3), + crease(200.0, 4), + crease(240.0, 5), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + // Looking up at the lid from below, a little to one side and then the other, at its middle. + let shown = |rotate_y: f64| { + let camera = Camera { width: 200, rotate_y, center: [150.0, -30.0, -40.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(100, 50) + }; + let (left, right) = (shown(175.0), shown(185.0)); + assert!(left.is_some_and(|p| p != f.base), "{left:?}"); + assert_eq!(left, right); +} + +#[test] +fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() { + // The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100, + // with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded + // at -180° onto the panel's printed side, where they overlap from y 20 to 40. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let shown = |tilt: f64| { + let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(100.0, -40.0), (100.0, 0.0)], false, Cut, 2, None), + line(&[(100.0, 60.0), (100.0, 100.0)], false, Cut, 3, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 4, Some(tilt)), + line(&[(100.0, 0.0), (200.0, 0.0)], false, Crease, 5, Some(-180.0)), + line(&[(100.0, 60.0), (200.0, 60.0)], false, Crease, 6, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 200, center: [150.0, -30.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0)); + let shown = img.panel_at(100, 50); + if shown == flap(-40.0) { + "above" + } else if shown == flap(60.0) { + "below" + } else { + "neither" + } + }; + let (up, down) = (shown(1.0), shown(-1.0)); + assert_ne!(up, "neither"); + assert_eq!(up, down); +} + +#[test] +fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() { + // The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180° + // onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(60.0, 0.0), (60.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 3, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(60.0), starts_at(100.0)); + let mut sides = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the wall from one side and then the other, the middle row of the view. + let camera = Camera { width: 200, height: 100, rotate_y, center: [60.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[wall].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = |p: usize| (0..img.width).filter(|&x| img.panel_at(x, 50) == Some(p)).count(); + let (walls, flaps) = (count(wall), count(flap)); + if printed { + assert!(flaps > 25 && walls < 15, "from the wall's printed side the flap covers it: wall {walls} px, flap {flaps} px"); + } else { + assert!(flaps == 0 && walls > 35, "from the back the wall covers the flap: wall {walls} px, flap {flaps} px"); + } + sides.push(printed); + } + assert_ne!(sides[0], sides[1], "both sides of the wall are looked at"); +} + +#[test] +fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_side() { + // The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each + // with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover + // the same 100 pt. Looking straight through that end, the base and walls are edge on. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(40.0, 0.0), (40.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(90.0)), + line(&[(0.0, 60.0), (40.0, 60.0)], false, Crease, 4, Some(90.0)), + line(&[(140.0, 60.0), (180.0, 60.0)], false, Crease, 5, Some(90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6 && r.y0 > 59.0)).expect("a flap"); + let (left, right) = (flap(0.0), flap(140.0)); + let shown = |rotate_x: f64| { + let camera = Camera { width: 300, height: 300, rotate_x, center: [90.0, -60.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = + |p: usize| (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(p)).count(); + (count(left), count(right)) + }; + let (one, other) = (shown(90.0), shown(-90.0)); + // Each view shows one flap over (nearly) the whole of the other. + let winner = |(l, r): (usize, usize)| { + if l > 10 * r.max(1) { + Some(left) + } else if r > 10 * l.max(1) { + Some(right) + } else { + None + } + }; + assert!(winner(one).is_some() && winner(other).is_some(), "the flaps cover the same end: {one:?} {other:?}"); + assert_ne!(winner(one), winner(other), "{one:?} {other:?}"); +} + +#[test] +fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() { + // A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90° + // and -90°, so the last one comes round and lies on the base's plane over part of it. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(-90.0)), + line(&[(200.0, 0.0), (200.0, 60.0)], false, Crease, 4, Some(-90.0)), + line(&[(240.0, 0.0), (240.0, 60.0)], false, Crease, 5, Some(-90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 240.0).abs() < 1e-6)).expect("the flap"); + // The panels between the base and the flap all lie behind the base's printed side. + for (i, (panel, folded)) in b.panels.iter().zip(&f.panels).enumerate() { + let r = panel.outline.bounds().expect("bounds"); + let z = folded.pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0))[2]; + if i != f.base && i != flap { + assert!(z < -1.0, "panel {i} at z {z}"); + } + } + // At x 90 the flap lies on the base: from the front the base covers it, from the back it + // covers the base. + let at = |rotate_y: f64, x: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(x, 50) + }; + assert_eq!(at(0.0, 200 - 10), Some(f.base)); + assert_eq!(at(180.0, 200 + 10), Some(flap)); +} + +#[test] +fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from() { + // A strip 60 pt tall: the base (x 0 to 100) and panels 20, 20, 40, 40 and 20 pt wide, then a + // flap (240 to 270, y 0 to 30), folded 90°, -90°, -90°, -90°, -90° and 90°. The 20 pt wall the + // flap folds from stands on the printed side of the base, and the flap lands on the base at x + // 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60), + // through the base's plane, which moves its middle to the other side of that plane. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with + // a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side. + let shown = |tab: bool, cutout: f64| { + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = if tab { + vec![ + line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (340.0, 30.0), (340.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(240.0, 30.0), (270.0, 30.0)], false, Cut, 2, None), + ] + } else { + vec![line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (0.0, 60.0)], true, Cut, 1, None)] + }; + let creases = + [(100.0, 60.0, 90.0), (120.0, 60.0, -90.0), (140.0, 60.0, -90.0), (180.0, 60.0, -90.0), (220.0, 60.0, -90.0), (240.0, 30.0, 90.0)]; + for (i, (x, high, a)) in creases.into_iter().enumerate() { + let key = 10 * (i as u64 + 1); + if cutout > 0.0 { + let (lo, hi) = if cutout > 5.0 { (2.0, high - 2.0) } else { (high / 2.0 - 5.0, high / 2.0 + 5.0) }; + let w = cutout.min(5.0); + lines.push(line(&[(x - w, lo), (x + w, lo), (x + w, hi), (x - w, hi)], true, Cut, key, None)); + lines.push(line(&[(x, 0.0), (x, lo)], false, Crease, key + 1, Some(a))); + lines.push(line(&[(x, hi), (x, high)], false, Crease, key + 2, Some(a))); + } else { + lines.push(line(&[(x, 0.0), (x, high)], false, Crease, key, Some(a))); + } + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(220.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let m = middle(flap); + assert!(m[2].abs() < 1e-6 && (m[0] - 65.0).abs() < 1e-6, "the flap lies on the base: {m:?}"); + assert_eq!(middle(wall)[2] > 0.0, !tab, "the wall's middle is on the printed side without the tab only"); + // The flap's row at y 5, at x 65, from the front and from the back (mirrored). + let at = |rotate_y: f64, px: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(px, 25) + }; + let named = |p: Option| match p { + Some(p) if p == f.base => "base", + Some(p) if p == flap => "flap", + _ => "other", + }; + (named(at(0.0, 200 - 35)), named(at(180.0, 200 + 35))) + }; + assert_eq!(shown(false, 0.0), ("flap", "base")); + assert_eq!(shown(true, 0.0), ("flap", "base"), "the side next to the hinge decides, not the wall's middle"); + assert_eq!(shown(false, 5.0), ("flap", "base"), "a hinge broken by a cutout"); + assert_eq!(shown(true, 5.0), ("flap", "base"), "both"); + assert_eq!(shown(true, 6.0), ("flap", "base"), "hinges joined only near their ends"); +} + +#[test] +fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_came_from() { + // A strip 30 pt tall: the base (x 0 to `base`), a panel 10 pt wide folded down behind it, one + // 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp + // `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that + // lies on the base from where the ramp ends. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let shown = |base: f64, ramp: f64, drop: f64| { + // To the millionth of a degree a line keeps, and the drop that ramp comes down by. + let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees()); + let drop = ramp * tilt.to_radians().sin(); + let up = base + 30.0; + let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)]; + let end = up + 10.0 + drop + ramp + 30.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (end - 30.0)).abs() < 1e-6)).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let r = b.panels[flap].outline.bounds().expect("bounds"); + let m = f.panels[flap].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)); + let x = base + 20.0 - ramp - 15.0; + assert!(m[2].abs() < 1e-6 && (m[0] - x).abs() < 1e-2 && x > 0.0, "the flap lies on the base at {x}: {m:?}"); + // The flap's middle, from the front and from the back. + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + (at(0.0) == Some(flap), at(180.0) == Some(f.base)) + }; + assert_eq!(shown(100.0, 40.0, 0.01), (true, true), "a 40 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.01), (true, true), "a 500 pt ramp 0.01 pt high"); + assert_eq!(shown(2100.0, 2000.0, 0.01), (true, true), "a 2,000 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.001), (true, true), "a 500 pt ramp 0.001 pt high"); +} + +#[test] +fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_from() { + // A strip 30 pt tall: the base (x 0 to 1,000) and panels 100, 300, 200 and 50 pt wide, folded + // `tilt`, 180°, -2 `tilt` and `tilt`: at 0.04° the 200 pt panel comes back down onto the base's + // plane from about 0.14 pt off it, at 0.00001° from 0.00004 pt, and the last panel lies on the + // base. + for tilt in [0.04, 0.00001] { + flap_brought_back_by_folds_all_near_flat(tilt); + } +} + +fn flap_brought_back_by_folds_all_near_flat(tilt: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)]; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (ramp, flap) = (starts_at(1400.0), starts_at(1600.0)); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let (m, above) = (middle(flap), middle(ramp)[2]); + assert!(m[2].abs() < 1e-3 && (0.0..1000.0).contains(&m[0]) && above.abs() > tilt * 0.25, "the flap lies on the base: {m:?}, the ramp at {above}"); + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + let (from_front, from_back) = (at(0.0), at(180.0)); + if above > 0.0 { + assert_eq!((from_front, from_back), (Some(flap), Some(f.base)), "{tilt}°"); + } else { + assert_eq!((from_front, from_back), (Some(f.base), Some(flap)), "{tilt}°"); + } +} + +#[test] +fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() { + // The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's + // first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)]; + lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0))); + for (i, (x, a)) in [(100.0, 90.0), (120.0, -90.0), (140.0, -90.0), (180.0, -90.0), (220.0, -90.0)].into_iter().enumerate() { + lines.push(line(&[(x, 0.0), (x, 60.0)], false, Crease, 3 + i as u64, Some(a))); + } + lines.push(line(&[(240.0, 0.0), (240.0, 30.0)], false, Crease, 9, Some(90.0))); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (panel, flap) = (starts_at(0.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(f.base, starts_at(-150.0)); + let mut seen = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the panel from one side and then the other: how many pixels show the flap. + let camera = Camera { width: 400, height: 200, rotate_y, center: [0.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[panel].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flaps = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(flap)).count(); + seen.push((printed, flaps)); + } + let (from_print, from_back) = if seen[0].0 { (seen[0].1, seen[1].1) } else { (seen[1].1, seen[0].1) }; + assert_ne!(seen[0].0, seen[1].0, "both sides of the panel are looked at"); + assert!(from_print > 600 && from_back == 0, "the flap shows on the panel's printed side only: {seen:?}"); +} + +#[test] +fn a_strip_rolled_up_45_times_keeps_the_base_in_front() { + // A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so + // each panel rolls under the one before it and all of them lie behind the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let end = 60.0 + 45.0 * 50.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| { + let x = 60.0 + 50.0 * f64::from(i); + super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 10 + u64::from(i), + angle: Some(180.0), + } + })); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(40, 30), Some(f.base)); +} + +#[test] +fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() { + // A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to + // 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies + // behind the flat strips at x 65 to 75. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0))); + lines.push(crease(105.0, 2, 180.0)); + lines.push(crease(145.0, 3, 180.0)); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (strip, middle, flap) = (starts_at(70.0), starts_at(105.0), starts_at(145.0)); + let camera = Camera { width: 160, center: [80.0, -50.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown = img.panel_at(70, 30); + assert_eq!(shown, Some(strip), "a flat strip, not the flap ({flap}) or the folded panel ({middle})"); +} + #[test] fn a_hole_in_a_panel_is_left_empty() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..6781a2c64d 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() { + // A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes + // the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest + // panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the + // origin and 3,000,000 pt to the right. + let own_tree = |dx: f64| { + let lines = |closing: Option| { + let crease = |a: (f64, f64), b: (f64, f64), key: u64| { + let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key); + l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 }); + l + }; + vec![ + cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1), + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (b, issues) = check(&lines(None)); + assert!(issues.is_empty(), "{issues:?}"); + let level = fold(&b[0], None, 1.0, TOL).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = b[0].hinges[closing].keys[0]; + let (b, issues) = check(&lines(Some(key))); + assert!(issues.is_empty(), "{issues:?}"); + let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds"); + f.stack.root == f.base + }; + assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree"); + assert!(own_tree(3_000_000.0), "far from the origin too"); +} + +#[test] +fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() { + // A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the + // grid's right squares. Every crease is at 0° but the one between the two left squares, at a + // millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out + // and places the other square at most 0.0000001 pt from where the fold's own tree does. + let mut lines = vec![ + cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1), + crease((5.0, 0.0), (5.0, 5.0), 2), + crease((5.0, 5.0), (5.0, 10.0), 3), + crease((0.0, 5.0), (5.0, 5.0), 4), + crease((5.0, 5.0), (10.0, 5.0), 5), + crease((10.0, 0.0), (10.0, 10.0), 6), + ]; + for l in &mut lines { + l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 }); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge"); + let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds"); + assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4])); + assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns"); +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 3f4d2e4551..e43aed7ec8 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -1,8 +1,10 @@ //! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected -//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu +//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold +//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold +//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches… +//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each //! with a Select button; each document's list is kept until that document changes. Its Fold Preview //! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). @@ -27,6 +29,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that sets or resets the fold angle of fold lines. +pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees. +pub const FOLD_ANGLES: std::ops::RangeInclusive = -180.0..=180.0; +/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is +/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the +/// place the field's fine steps (a tenth of a degree) round to. +pub fn angle_places(angle: Option) -> usize { + // f64's Display is the shortest text that reads back as the same number, without an exponent. + angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1) +} /// The command that shows the Fold Preview window. pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. @@ -50,6 +64,7 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Cmd("Set Fold Angle…", SET_FOLD_ANGLE, Value::Null), Item::Sep, Item::Cmd("Fold Preview", PREVIEW, json!({})), ] @@ -211,15 +226,23 @@ struct Rows { /// What they were read for: the document, its revision and its selection. key: Option<(u64, u64, Vec)>, rows: Vec, + /// Whether the rows count the selection (not the whole document). + selection: bool, + /// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change. + fold_lines: u64, + /// The angle they all fold at (`None`: they differ, or there are none). + angle: Option, + /// How many of them hold a stored angle, readable or not: what Reset takes away. + stored_angles: u64, } /// The rows for the active document as it is now, read again only when it changed. -fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; +fn read_rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Rows { + let Some(st) = app.session.active() else { return Rows::default() }; let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); let mut kept: Rows = pstate(ctx, STATE); if kept.key.as_ref() == Some(&key) { - return kept.rows; + return kept; } let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); let d = app.session.active().map(|st| st.doc.clone()); @@ -228,9 +251,55 @@ fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) }; - kept = Rows { key: Some(key), rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect() }; + kept = Rows { + key: Some(key), + rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(), + selection: answer["scope"] == "selection", + fold_lines: answer["foldLines"].as_u64().unwrap_or(0), + angle: answer["foldAngle"].as_f64(), + stored_angles: answer["storedAngles"].as_u64().unwrap_or(0), + }; set_pstate(ctx, STATE, kept.clone()); - kept.rows + kept +} + +/// The role rows for the active document as it is now. +fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + read_rows(app, ctx).rows +} + +/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle +/// the selected lines that it can change all fold at, else 90°. The command's reason while it +/// can't change any. +pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result { + let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; + (command.enabled)(&app.session)?; + let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); + Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle })) +} + +/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle +/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which +/// takes away the angles of their own. +fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { + if !kept.selection || kept.fold_lines == 0 { + return; + } + let mut call = None; + ui.horizontal(|ui| { + widgets::field_label(ui, tl!("Fold Angle")); + if let Some(a) = widgets::mixed_field_within(ui, "fold-angle", kept.angle, "°", angle_places(kept.angle), 64.0, FOLD_ANGLES) { + call = Some(json!({ "angle": a })); + } + if ui.add_enabled_ui(kept.stored_angles > 0, |ui| widgets::flat_button_fit(ui, tl!("Reset"), 56.0)).inner.clicked() { + call = Some(json!({ "reset": true })); + } + }); + if let Some(p) = call + && let Err(e) = app.run(SET_FOLD_ANGLE, p) + { + app.status(e); + } } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -244,7 +313,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); } let mut picked = None; - for (role, swatch, paint, count) in rows(app, ui.ctx()) { + let kept = read_rows(app, ui.ctx()); + for (role, swatch, paint, count) in kept.rows.iter().cloned() { let label = ROLES.iter().find(|(_, id)| *id == role).map_or(role.as_str(), |(l, _)| *l); let clicked = ui .add_enabled_ui(selected, |ui| { @@ -267,6 +337,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_angle(app, ui, &kept); show_check(app, ui); } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index c3c69c3f31..79d6ba345a 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -470,6 +470,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { order: vec![], hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], collisions: vec![(0, 1)], + stack: Default::default(), + origin: [0.0; 3], }; let lines = status(3, Some((&Blank::default(), &f)), true); assert_eq!( diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 2ce5643fc3..4ee1334759 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_engine::Session; -use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use super::{CHECK, ID, ROLES, SET_FOLD_ANGLE, SET_ROLE, SET_ROLE_SWATCH, show}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -274,12 +274,167 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { + let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } } +#[test] +fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Set Fold Angle…").expect("listed"); + assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE)); + let opened = |app: &mut VectorcraftApp| { + let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params); + menus::invoke(app, &target, p); + let d = app.ui.dialog.take().expect("a dialog"); + assert_eq!((d.kind.as_str(), d.str("__command")), ("command", SET_FOLD_ANGLE.to_string())); + d.fields["angle"].as_f64() + }; + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(opened(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own"); + app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap(); + assert_eq!(opened(&mut app), Some(45.0)); + // The cut line does not fold, so the crease's angle is still the one shown. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(opened(&mut app), Some(45.0)); + // Lines that differ open on 90°. + let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap(); + app.run("select.set", json!({"ids": [a, c]})).unwrap(); + assert_eq!(opened(&mut app), Some(90.0)); + // With only a cut line selected there is nothing to set: no dialog opens. + app.run("select.set", json!({"ids": [b]})).unwrap(); + let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params); + menus::invoke(&mut app, &target, p); + assert!(app.ui.dialog.is_none()); + // ui.menuDialog gives the command's reason. + let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err(); + assert!(e.contains("select a crease, partial cut or perforation line"), "{e}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap(); + assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(45.0)); + // The options dialog opened with an angle keeps it. + menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}})); + assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(30.0)); +} + +/// Set Fold Angle… keeps the angle typed into its dialog within -180° to 180°, so OK applies the +/// nearest end instead of closing on an angle the command refuses. +#[test] +fn set_fold_angle_s_dialog_keeps_the_angle_within_its_range() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("181"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(180.0)); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}"); + // An angle typed with more places than the field shows is kept as typed, as the panel keeps it. + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("179.9999"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(179.9999)); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(179.9999), "{r}"); + // Opened on an angle with more places than that, the dialog shows them all, so typing 180 sets 180. + h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap(); + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("180"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}"); + // A fine step from a whole angle steps a tenth of a degree. + h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 90, "ids": [a]})).unwrap(); + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::ArrowUp); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(90.1)); +} + +#[test] +fn a_fold_angle_field_shows_every_place_the_angle_has() { + use super::angle_places; + assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]); +} + +#[test] +fn the_panel_shows_and_resets_the_selected_lines_fold_angle() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let text = painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("Fold Angle") && text.contains("135"), "{text}"); + click_row(&mut app, "Reset"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "{r}"); + // Stored text that is not an angle: the field shows the role's angle, and Reset removes the text. + app.session + .edit("Test", |d, _| { + if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) { + n.edit_attrs(|at| at.data.push(("vc-fold-angle".into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64(), r["storedAngles"].as_u64()), (Some(90.0), Some(0), Some(1)), "{r}"); + click_row(&mut app, "Reset"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["storedAngles"].as_u64(), Some(0), "{r}"); +} + #[test] fn the_panel_without_a_document_asks_for_one() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index de7836f0a5..5f57750cf8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -163,6 +163,15 @@ pub(super) fn length_range(command: &str, key: &str) -> Option Option> { + match (command, key) { + (crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES), + _ => None, + } +} + /// The order the fields of the commands this dialog edits come in, where the order of their /// names isn't it (the rest follow, by name). fn order(command: &str) -> &'static [&'static str] { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index b46f35a79f..b2c2b3cb61 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -510,6 +510,14 @@ pub(super) fn param_fields( changed = true; } } + Value::Number(n) if let Some(range) = super::command::number_range(&d.str("__command"), &k) => { + // Kept within the range as typed, and shown to the places a fold angle keeps. + let places = crate::addons::packaging::angle_places(n.as_f64()); + if let Some(x) = crate::widgets::mixed_field_within(ui, ("fx-num", &k), n.as_f64(), "", places, 140.0, range) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + } Value::Number(n) => { // A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language. let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() }; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d371a5f1e4..5b99e36d20 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7653,6 +7653,11 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Fold Angle Ъгъл на сгъване + Set Fold Angle… Задай ъгъл на сгъване… + Set Fold Angle Задай ъгъл на сгъване + Reset Fold Angle Нулирай ъгъла на сгъване +@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита Check Провери Check Fold Lines Провери линиите на сгъване @msg No cut lines are in the selection. В селекцията няма линии за рязане. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 00d07d469d..09e931ff5c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7708,6 +7708,11 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Fold Angle Ugao savijanja + Set Fold Angle… Postavi ugao savijanja… + Set Fold Angle Postavi ugao savijanja + Reset Fold Angle Poništi ugao savijanja +@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena Check Provjeri Check Fold Lines Provjeri linije savijanja @msg No cut lines are in the selection. U odabiru nema linija rezanja. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 78e5a77c9e..b5dbfa65ca 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8610,6 +8610,11 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Fold Angle Angle de plegat + Set Fold Angle… Defineix l’angle de plegat… + Set Fold Angle Defineix l’angle de plegat + Reset Fold Angle Restableix l’angle de plegat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada Check Comprova Check Fold Lines Comprova les línies de plegat @msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bd3e76ec50..dd629eba4b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -10406,6 +10406,11 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Fold Angle Úhel skladu + Set Fold Angle… Nastavit úhel skladu… + Set Fold Angle Nastavit úhel skladu + Reset Fold Angle Obnovit úhel skladu +@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá Tap Krátký stisk Clear Hold Vymazat podržení Hold Shortcuts Zkratky podržením diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3fb128a27a..c1263a2f8e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10498,6 +10498,11 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Fold Angle Foldevinkel + Set Fold Angle… Angiv foldevinkel… + Set Fold Angle Angiv foldevinkel + Reset Fold Angle Nulstil foldevinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult Check Kontrollér Check Fold Lines Kontrollér foldelinjer @msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6ad4e3850b..2309e2d1dd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -10019,6 +10019,11 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Fold Angle Faltwinkel + Set Fold Angle… Faltwinkel festlegen… + Set Fold Angle Faltwinkel festlegen + Reset Fold Angle Faltwinkel zurücksetzen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist Tap Kurz drücken Clear Hold Halten löschen Hold Shortcuts Halte-Tastaturbefehle diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7d2e5b6363..0e17bbc511 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8584,6 +8584,11 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Fold Angle Γωνία δίπλωσης + Set Fold Angle… Ορισμός γωνίας δίπλωσης… + Set Fold Angle Ορισμός γωνίας δίπλωσης + Reset Fold Angle Επαναφορά γωνίας δίπλωσης +@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή Check Έλεγχος Check Fold Lines Έλεγχος γραμμών δίπλωσης @msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 30678f8a13..49bcbf2730 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -10330,6 +10330,11 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Fold Angle Ángulo de plegado + Set Fold Angle… Definir ángulo de plegado… + Set Fold Angle Definir ángulo de plegado + Reset Fold Angle Restablecer ángulo de plegado +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta Check Comprobar Check Fold Lines Comprobar líneas de plegado @msg No cut lines are in the selection. No hay líneas de corte en la selección. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 873d339833..056fc15f8b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8667,6 +8667,11 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Fold Angle Taittokulma + Set Fold Angle… Aseta taittokulma… + Set Fold Angle Aseta taittokulma + Reset Fold Angle Palauta taittokulma +@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu Check Tarkista Check Fold Lines Tarkista taittoviivat @msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68bcc455b2..985f343e7a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -10391,6 +10391,11 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Fold Angle Angle de pliage + Set Fold Angle… Définir l’angle de pliage… + Set Fold Angle Définir l’angle de pliage + Reset Fold Angle Réinitialiser l’angle de pliage +@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée Tap Appui bref Clear Hold Effacer le maintien Hold Shortcuts Raccourcis de maintien diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index d7bb081e02..ffbd2bd3fb 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5396,6 +5396,11 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Fold Angle ફોલ્ડ ખૂણો + Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો… + Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો + Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો +@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય Check ચેક કરો Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો @msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2837a15b67..c9363394c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10012,6 +10012,11 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Fold Angle फ़ोल्ड कोण + Set Fold Angle… फ़ोल्ड कोण सेट करें… + Set Fold Angle फ़ोल्ड कोण सेट करें + Reset Fold Angle फ़ोल्ड कोण रीसेट करें +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो Tap जल्दी दबाना Clear Hold होल्ड साफ़ करें Hold Shortcuts होल्ड शॉर्टकट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fbc2e30bd1..82af3ad6b8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -10394,6 +10394,11 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Fold Angle Hajtásszög + Set Fold Angle… Hajtásszög beállítása… + Set Fold Angle Hajtásszög beállítása + Reset Fold Angle Hajtásszög visszaállítása +@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve Tap Rövid lenyomás Clear Hold Nyomva tartás törlése Hold Shortcuts Nyomva tartásos billentyűparancsok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ab48475d3d..51f9b7b34c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7668,6 +7668,11 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Fold Angle Sudut lipat + Set Fold Angle… Atur sudut lipat… + Set Fold Angle Atur sudut lipat + Reset Fold Angle Atur ulang sudut lipat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden pilih garis lekuk, garis potong sebagian, atau garis perforasi yang tidak terkunci dan tidak tersembunyi Check Periksa Check Fold Lines Periksa garis lipat @msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a3b493cd1d..43c01df826 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -10052,6 +10052,11 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Fold Angle Angolo di piega + Set Fold Angle… Imposta angolo di piega… + Set Fold Angle Imposta angolo di piega + Reset Fold Angle Reimposta angolo di piega +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleziona una linea di cordonatura, di taglio parziale o di perforazione che non sia bloccata né nascosta Tap Pressione breve Clear Hold Cancella pressione prolungata Hold Shortcuts Scorciatoie a pressione prolungata diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5de0cae50c..8a88738a10 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10116,6 +10116,11 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Fold Angle 折り角度 + Set Fold Angle… 折り角度を設定… + Set Fold Angle 折り角度を設定 + Reset Fold Angle 折り角度をリセット +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ロックも非表示もされていない筋入れ線、半抜き線またはミシン目線を選択してください Tap 短押し Clear Hold 長押しを消去 Hold Shortcuts 長押しショートカット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 81fc06870d..24a4e6b853 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10746,6 +10746,11 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მარკირებისთვის. Remove Fold Line Role ხაზის ტიპის მოხსნა + Fold Angle მოკეცვის კუთხე + Set Fold Angle… მოკეცვის კუთხის დაყენება… + Set Fold Angle მოკეცვის კუთხის დაყენება + Reset Fold Angle მოკეცვის კუთხის ჩამოყრა +@msg select a crease, partial cut or perforation line that is neither locked nor hidden მონიშნეთ ბიგის, ნაწილობრივი ჭრის ან პერფორაციის ხაზი, რომელიც არც ჩაკეტილია და არც დამალული Check შემოწმება Check Fold Lines მოკეცვის ხაზების შემოწმება @msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4a6963bbd2..56a0a96573 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -10015,6 +10015,11 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Fold Angle 접는 각도 + Set Fold Angle… 접는 각도 설정… + Set Fold Angle 접는 각도 설정 + Reset Fold Angle 접는 각도 재설정 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 잠기거나 숨겨지지 않은 오시선, 하프 컷 선 또는 미싱선을 선택하세요 Tap 짧게 누르기 Clear Hold 길게 누르기 지우기 Hold Shortcuts 길게 누르기 단축키 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 894c7096f6..18bc758d8c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10443,6 +10443,11 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Fold Angle Vouwhoek + Set Fold Angle… Vouwhoek instellen… + Set Fold Angle Vouwhoek instellen + Reset Fold Angle Vouwhoek herstellen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecteer een rillijn, halve snijlijn of perforatielijn die niet vergrendeld of verborgen is Tap Kort drukken Clear Hold Vasthouden wissen Hold Shortcuts Vasthoudsneltoetsen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c69ed2cf28..d660ec1acd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -10269,6 +10269,11 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Fold Angle Kąt zgięcia + Set Fold Angle… Ustaw kąt zgięcia… + Set Fold Angle Ustaw kąt zgięcia + Reset Fold Angle Resetuj kąt zgięcia +@msg select a crease, partial cut or perforation line that is neither locked nor hidden zaznacz linię bigowania, nacięcia lub perforacji, która nie jest zablokowana ani ukryta Tap Krótkie naciśnięcie Clear Hold Wyczyść przytrzymanie Hold Shortcuts Skróty przytrzymania diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6bae5e26f1..b52732995d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10478,6 +10478,11 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Fold Angle Ângulo de Dobra + Set Fold Angle… Definir Ângulo de Dobra… + Set Fold Angle Definir Ângulo de Dobra + Reset Fold Angle Redefinir Ângulo de Dobra +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecione uma linha de vinco, de meio-corte ou de perfuração que não esteja bloqueada nem oculta Tap Toque Rápido Clear Hold Limpar Pressionamento Longo Hold Shortcuts Atalhos de Pressionamento Longo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 74156da429..0a5172c786 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10492,6 +10492,11 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Fold Angle Угол сгиба + Set Fold Angle… Задать угол сгиба… + Set Fold Angle Задать угол сгиба + Reset Fold Angle Сбросить угол сгиба +@msg select a crease, partial cut or perforation line that is neither locked nor hidden выделите линию биговки, надреза или перфорации, которая не закреплена и не скрыта Check Проверить Check Fold Lines Проверить линии сгиба @msg No cut lines are in the selection. В выделении нет линий реза. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4d683cb1ea..a4013cc169 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10096,6 +10096,11 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Fold Angle Falsvinkel + Set Fold Angle… Ange falsvinkel… + Set Fold Angle Ange falsvinkel + Reset Fold Angle Återställ falsvinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markera en biglinje, halvskärlinje eller perforeringslinje som varken är låst eller dold Check Kontrollera Check Fold Lines Kontrollera falslinjer @msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d0e30b8fdc..07fb929d7d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10364,6 +10364,11 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Fold Angle Katlama Açısı + Set Fold Angle… Katlama Açısını Ayarla… + Set Fold Angle Katlama Açısını Ayarla + Reset Fold Angle Katlama Açısını Sıfırla +@msg select a crease, partial cut or perforation line that is neither locked nor hidden kilitli ya da gizli olmayan bir pilyaj, yarım kesim veya perforaj çizgisi seçin Tap Kısa Basma Clear Hold Basılı Tutmayı Temizle Hold Shortcuts Basılı Tutma Kısayolları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 82ba9af243..2541e72109 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -10028,6 +10028,11 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Fold Angle Кут згину + Set Fold Angle… Задати кут згину… + Set Fold Angle Задати кут згину + Reset Fold Angle Скинути кут згину +@msg select a crease, partial cut or perforation line that is neither locked nor hidden виділіть лінію біговки, надрізу або перфорації, яка не закріплена й не прихована Tap Коротке натискання Clear Hold Очистити утримання Hold Shortcuts Клавіші утримання diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 04ebd9992d..dfe76ef3de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8137,6 +8137,11 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Fold Angle Góc gấp + Set Fold Angle… Đặt góc gấp… + Set Fold Angle Đặt góc gấp + Reset Fold Angle Đặt lại góc gấp +@msg select a crease, partial cut or perforation line that is neither locked nor hidden hãy chọn một đường cấn, đường cắt một phần hoặc đường đục lỗ không bị khóa và không bị ẩn Check Kiểm tra Check Fold Lines Kiểm tra đường gấp @msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d20ae8d9e8..a1ae040aec 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -10253,6 +10253,11 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Fold Angle 折叠角度 + Set Fold Angle… 设置折叠角度… + Set Fold Angle 设置折叠角度 + Reset Fold Angle 重置折叠角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 请选择未锁定且未隐藏的压痕线、半切线或打孔线 Check 检查 Check Fold Lines 检查折线 @msg No cut lines are in the selection. 所选内容中没有切割线。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5fde762f9..56855c3a66 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -10068,6 +10068,11 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Fold Angle 摺疊角度 + Set Fold Angle… 設定摺疊角度… + Set Fold Angle 設定摺疊角度 + Reset Fold Angle 重設摺疊角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 請選取未鎖定且未隱藏的壓痕線、半切線或打孔線 Check 檢查 Check Fold Lines 檢查摺線 @msg No cut lines are in the selection. 選取範圍中沒有切割線。 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 42c6da3a10..f48cf11dae 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -75,6 +75,8 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + // Set Fold Angle… opens on the angle the selected fold lines fold at, while it can change one. + crate::addons::packaging::SET_FOLD_ANGLE => ("command", crate::addons::packaging::dialog_fields(app).ok()?), crate::addons::pathtools::set_corners::COMMAND => { (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..931a66b52c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -963,6 +963,11 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::envelope::open(app, c), + // Set Fold Angle's dialog says why it can't open, as the command does. + Some(crate::addons::packaging::SET_FOLD_ANGLE) => crate::addons::packaging::dialog_fields(app).map(|fields| { + app.ui.dialog = Some(crate::state::Dialog::new("command", fields)); + Value::Null + }), c => match c.and_then(|c| menu_dialog(app, c)) { Some((kind, fields)) => { app.ui.dialog = Some(crate::state::Dialog::new(kind, fields)); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fbfd12b24e..ddb4bc3939 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1412,7 +1412,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|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; 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)", + "{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|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, 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)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d6a0f7c50e..7f44f2bbca 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -60,7 +60,7 @@ pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_labe pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ - SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, + SpinPick, mixed_field, mixed_field_named, mixed_field_within, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, num_field_within_empty, opt_field, opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_length_within, spin_plain, spin_plain_named, spin_range, diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index a9d4020ab3..efdbf64006 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -842,6 +842,21 @@ pub fn mixed_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option, su mixed_field_named(ui, id, None, value, suffix, decimals, width) } +/// [`mixed_field`] whose value is kept within `bounds`: steps stop at its ends, and a typed value +/// past one is brought to it. +pub fn mixed_field_within( + ui: &mut Ui, + id: impl std::hash::Hash, + value: Option, + suffix: &str, + decimals: usize, + width: f32, + bounds: RangeInclusive, +) -> Option { + let label = take_previous_label(ui); + bounded_field(ui, id, label, None, value, suffix, decimals, width, &bounds, None, false, false).map(|v| within(v, &bounds)) +} + /// [`mixed_field`] for a row named explicitly instead of by an adjacent label widget. pub fn mixed_field_named( ui: &mut Ui, diff --git a/docs/mcp.md b/docs/mcp.md index 5bc273289c..f4fd4ced7d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14304,10 +14304,11 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and -`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, -Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the -selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check`, +`addon.packaging.setFoldAngle` and `addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold +Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run +`addon.packaging.setRole` on the selection, Check Fold Lines runs `addon.packaging.check`, Set Fold Angle… opens the +options of `addon.packaging.setFoldAngle`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -14338,11 +14339,17 @@ the color it shows, no longer linked to the swatch, and stops overprinting. Text objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. -`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's -swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object -of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are -counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows -these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so. +`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected, foldLines, +foldAngle, ownAngles, storedAngles}`: each role's swatch, whether the document has it, and how many of the objects have +the role. It counts the selection, or every object of the document while nothing is selected and `ids` is left out +(`scope` says which). Locked and hidden objects are counted in every scope, and an object is counted once when both it +and its group are given. `foldLines` is how many of the Crease, Partial Cut and Perforation lines among them +`addon.packaging.setFoldAngle` can change, which leaves out locked and hidden lines; it is 0 while nothing is selected +and `ids` is left out, and while the selection holds only a layer and objects in it. `foldAngle` is the angle in degrees +those lines all fold at (see Fold angles), or null when they fold at different angles or there are none; `ownAngles` is +how many of them have an angle of their own, and `storedAngles` how many hold stored angle text, an angle or not, which +`reset: true` removes. The Fold Lines panel shows these counts; clicking a role gives the selected paths that role. With +nothing selected the panel says so. `addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or @@ -14403,17 +14410,47 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold angles + +A Crease or a Perforation folds 90° away from the printed side, so the print ends up outside, and a Partial Cut folds +90° toward it. A Crease, Partial Cut or Perforation line can have an angle of its own instead, from -180° to 180°: a +positive angle folds away from the printed side and a negative one toward it. The angle is stored in the line's data +under `vc-fold-angle` as a number of degrees, rounded to the millionth of a degree (a stored value with more places +folds at it rounded the same way). Native files keep it. SVG export leaves it out of the path's attributes; an SVG with +`preserveEditing` keeps it in the document the SVG carries. A value that is not a number from -180 to 180 counts as no +angle of its own. A cut line ignores it. A line keeps its own angle when `addon.packaging.setRole` gives it another +role, or `none`, so a line made a Partial Cut after it was given 45° still folds at 45°; `reset: true` takes the angle +away. In the Fold Preview window, a panel folded flat onto another (180°) is drawn behind that panel's printed side, and +at -180° in front of it. Panels folded flat onto each other stack as they do when the blank is folded about its largest +panel, whichever panel the window folds about. + +`addon.packaging.setFoldAngle` (`{angle?: -180..180, reset?: false, ids?}`) gives each Crease, Partial Cut and +Perforation line among the objects (the selection by default), through groups and clip groups, the angle, or with +`reset: true` takes the line's own angle away. Give exactly one of `angle` and `reset: true`. Locked and hidden objects +are skipped as `addon.packaging.setRole` skips them; cut lines and objects without a role are skipped and counted. The +command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside +the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. + +Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the +angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. +While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection +holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it, and the Reset button beside it takes their own angles away. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.setFoldAngle","params":{"angle":135}}} +``` + ### Fold Preview `addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it -to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from -the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of -panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, -whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of -hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything -else is an error. The command does not change the document. +to the base, each by its angle times `amount` (0 is flat, 1 is folded). A hinge's angle is the fold angle of the line +with the most length in it (see Fold angles), the one with the lowest id among lines of equal length. A hinge that closes +a loop of panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all +the way, whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no +chain of hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; +anything else is an error. The command does not change the document. Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document From 4875606bb7d7a42a8f786fac505e77a66ad3596b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 02:47:00 -0800 Subject: [PATCH 07/84] Live Corners: a Corners link opens the corner settings of the picked corners The Control bar and the Properties panel show a Corners link beside the radius field of the picked corners. It opens a pop-up with the corner kind, the radius (blank while the picked corners differ) and Relative or Absolute rounding. Each change sets the picked corners of every selected path in one object.setLiveShape call with items, one undo step: the corners holding a Direct-Selected anchor, or every corner of a path selected whole. The Properties panel shows the link while a corner is Direct-Selected; its corner rows now cover several selected paths too, and a live rectangle or polygon selected alone, which keeps its own radius and kind rows, shows the link for the pop-up. object.setLiveShape with relativeRadii: true now works on a plain path with corners: the path keeps its outline as the base of its Live Corners. Before, it did nothing, and relativeRadii: false added an empty undo step. A Relative path whose corners are all uncut again keeps its rounding, and Absolute on one with no corner cut makes it a plain path again. With Relative rounding, a radius is now compared as the fraction it would store, so typing the radius the field shows, or a radius past the corner's maximum again, adds no undo step. Before, it was compared with the radius as drawn. Part of #1232. Reported by XTRECY-BD. --- crates/doc/src/corners.rs | 7 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 38 +++++- crates/engine/src/tests/livecorners.rs | 63 +++++++++ crates/ui-egui/src/chrome/control_bar.rs | 47 ++----- crates/ui-egui/src/chrome/tests.rs | 41 ++++++ crates/ui-egui/src/panels.rs | 112 ++++++++++++++++ crates/ui-egui/src/panels/properties.rs | 46 ++++--- crates/ui-egui/src/panels/properties/tests.rs | 125 +++++++++++++++++- crates/ui-egui/tests/control_bar_corners.rs | 2 +- docs/mcp.md | 15 ++- docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 13 files changed, 432 insertions(+), 68 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 24228604a6..3810bbb1f5 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -205,8 +205,8 @@ impl<'a> LiveCorners<'a> { /// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of /// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again. /// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a -/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they -/// are. +/// plain path again once no corner is cut, unless its rounding is Relative. Ellipses and lines +/// have no corners: they stay as they are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { fn edit( base: &PathData, @@ -268,7 +268,8 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, } match live.as_deref_mut() { - Some(LiveShape::Path { base, radii, kinds, .. }) if radii.is_empty() && kinds.is_empty() => { + // A path with Relative rounding keeps its record, and with it the rounding. + Some(LiveShape::Path { base, radii, kinds, radii_relative: false }) if radii.is_empty() && kinds.is_empty() => { *path = std::mem::take(base); *live = None; } diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..98b5579cbb 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole path: a live rectangle, a live polygon or any path with a corner, which keeps its outline as the base of its Live Corners; a path without Live Corners is Absolute, and a path whose anchors are edited loses its Live Corners and is Absolute again; ellipses and lines are left as they are), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut, unless its rounding is Relative; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index a4cec6253c..24274782d8 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,6 +99,17 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Whether `relativeRadii` applies to a path drawn as `path` with live shape `live`: a live +/// rectangle, a live polygon, a path with Live Corners, or a plain path with a corner. A plain +/// path's rounding is Absolute. +fn takes_rounding(path: &PathData, live: Option<&LiveShape>) -> bool { + match live { + Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }) => true, + Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => false, + None => LiveCorners::new(path, None).is_some_and(|c| !c.all().is_empty()), + } +} + /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about /// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { @@ -277,7 +288,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { + if relative_radii.is_some_and(|on| takes_rounding(path, live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -291,10 +302,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { && picked.iter().all(|k| { *k < c.base.anchor_count() // A radius stored in document units can be larger than it draws; a relative - // one is a fraction, so it is compared as drawn. + // one is compared as the fraction `set_corners` would store for it, to a + // precision of 1e-9 pt on a corner whose maximum is 1 pt or more. && radius.is_none_or(|r| { - let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) }; - (now - r.max(0.0)).abs() < 1e-9 + let r = r.max(0.0); + if c.radii_relative() { + let max = c.corner(*k).map_or(0.0, |c| c.max_radius()); + let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 }; + (c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9 + } else { + (c.radius(*k) - r).abs() < 1e-9 + } }) && kind.is_none_or(|kd| c.kind(*k) == kd) }) @@ -348,11 +366,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *l = new.clone(); *path = l.to_path(); } + // A path with corners and no Live Corners yet keeps its outline as their base, so that + // Relative rounding has a record to go in. + if relative_radii == Some(true) && live.is_none() && takes_rounding(path, None) { + *live = Some(Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![], radii_relative: false })); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { convert_radii_relative(l, on); *path = l.to_path(); + // Absolute with no corner cut: a plain path again, as `set_corners` leaves one. + if let LiveShape::Path { radii, kinds, radii_relative: false, .. } = l + && radii.is_empty() + && kinds.is_empty() + { + *live = None; + } } if radius.is_none() && kind.is_none() { continue; diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 288f0236d1..35d4f061ec 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,6 +910,69 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } +/// Relative rounding on a path with corners and no Live Corners yet takes effect in one undo step, +/// a radius set afterwards is stored as a fraction, and the rounding stays when no corner is cut +/// any more. Absolute, which such a path already has, and Relative on an ellipse, which has no +/// corners, add no undo step. +#[test] +fn relative_rounding_takes_on_a_plain_path() { + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.expandShape", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + assert_eq!(steps(&s), n, "Absolute: no change"); + run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); + assert_eq!(steps(&s), n + 1, "Relative: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(LiveCorners::of(node).unwrap().radii_relative()); + let max = LiveCorners::of(node).unwrap().corner(0).unwrap().max_radius(); + run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": max / 2.0})); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!(c.radii_relative() && (c.radius(0) - 0.5).abs() < 1e-9, "stored fraction: {}", c.radius(0)); + // With no corner cut again, the path keeps its Relative rounding. + run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": 0})); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!(c.radii_relative() && c.radius(0) == 0.0, "still Relative"); + // Absolute again with no corner cut: a plain path again. + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path again"); + let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let n = steps(&s); + run(&mut s, json!({"ids": [e], "relativeRadii": true})); + assert_eq!(steps(&s), n, "an ellipse: no change"); +} + +/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the +/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a +/// smaller one adds one. +#[test] +fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + let n = steps(&s); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "past the maximum: one undo step"); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0)); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "the same radius again: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max})); + assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max / 2.0})); + assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step"); + // On a large shape a small radius is a fraction below 1e-9, and still a change. + let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap(); + run(&mut s, json!({"ids": [big], "relativeRadii": true})); + let n = steps(&s); + run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001})); + assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step"); +} + /// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round, /// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag. #[test] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ce7f95808d..8831816527 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -78,45 +78,18 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } -/// The selected paths' eligible corners, as document lengths, beside the anchor controls. -/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). -fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, reserve: f32) { - let Some(st) = app.session.active() else { return }; - let mut items = Vec::new(); - let mut radius: Option = None; - let mut mixed = false; - for &id in &st.selection.objects { - let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; - let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); - if corners.is_empty() { - continue; - } - for &k in &corners { - // Keep absolute requested radii, even when their drawing is fitted smaller. Relative - // storage is a fraction, but the field and setLiveShape both consume document lengths. - let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; - if let Some(first) = radius { - mixed |= (first - value).abs() >= 1e-9; - } else { - radius = Some(value); - } - } - items.push(json!({"id": id, "corners": corners})); - } - if items.is_empty() { +/// The Corners link and the radius of the selected paths' picked corners +/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners +/// pop-up for those corners. +fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { + let Some(picked) = crate::panels::picked_corners(app) else { return }; + if ui.available_width() < row_width(ui, &[crate::panels::corners_link_width(ui), INLINE_FIELD_WIDTH]) + reserve { return; } - let label = tl!("Corner Radius:"); - let text = egui::RichText::new(label).size(12.0).color(t.text); - if ui.available_width() < row_width(ui, &[widgets::text_width(ui, text.clone()), INLINE_FIELD_WIDTH]) + reserve { - return; - } - widgets::field_label(ui, text); - let shown = if mixed { None } else { radius }; + crate::panels::corners_link(app, ui, "cb-corners"); let unit = app.session.general_unit(); - if let Some(radius) = widgets::num_field_named(ui, "cb-corner-radius", Some(label), shown, unit, INLINE_FIELD_WIDTH) { - // App::run reports any command failure in the status bar, as the other inline fields do. - app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + if let Some(radius) = widgets::num_field_named(ui, "cb-corner-radius", Some(tl!("Corner Radius:")), picked.radius, unit, INLINE_FIELD_WIDTH) { + crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)})); } } @@ -1083,7 +1056,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); let reserve = transform_reserve(app, ui, count > 0); - corner_radius(app, ui, t, reserve); + corner_radius(app, ui, reserve); } let object_options = group_on(app, "objectOptions"); if object_options { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b6c7a47015 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -4383,6 +4383,47 @@ fn the_anchor_points_group_holds_convert_and_anchors() { assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); } +/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners +/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step. +#[test] +fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { + use vectorcraft_geom::shapes::CornerKind; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame(app, &ctx, events); + let click = |frame: &mut dyn FnMut(&mut crate::VectorcraftApp, Vec) -> Vec, + app: &mut crate::VectorcraftApp, + name: &str| { + let at = node_center(&frame(app, vec![]), name).unwrap_or_else(|| panic!("{name} shows")); + frame(app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(app, vec![press_at(at, false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + assert!(node_center(&nodes, "Chamfer").is_none(), "the pop-up starts closed"); + let nodes = click(&mut frame, &mut app, "Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius:", "Relative", "Absolute"] { + assert!(node_center(&nodes, name).is_some(), "the pop-up has {name}"); + } + let depth = app.session.doc().unwrap().history.undo.len(); + click(&mut frame, &mut app, "Chamfer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); +} + /// Menus stop above a Control bar docked at the bottom when the status bar is hidden, above the /// status and hint bars when they show, and at the bottom of the window when the bar is docked at /// the top or a screen mode hides it. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6c4d7860e7..d7f4c6327a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -216,6 +216,118 @@ pub(crate) fn corner_radius_field(app: &mut VectorcraftApp, ui: &mut Ui, n: &Nod } } +/// The corners that the Corners link, its pop-up and the Corner Radius field beside it edit: +/// [`picked_corners`]. +pub(crate) struct PickedCorners { + /// `object.setLiveShape`'s `items`: `{id, corners}` for each path. + pub items: Vec, + /// The radius the corners share, as a document length; None when they differ. + pub radius: Option, + /// The kind the corners share; None when they differ. + pub kind: Option, + /// Whether their paths store relative radii; None when the paths differ. + pub relative: Option, +} + +/// The picked corners of the selection: for each selected path with Live Corners, the corners +/// holding a Direct-Selected anchor, or every corner of a path selected whole. A path whose +/// selected anchors hold no corner adds none. None when no path adds a corner. +pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option { + fn shared(values: &[T], same: impl Fn(T, T) -> bool) -> Option { + let (&first, rest) = values.split_first()?; + rest.iter().all(|v| same(*v, first)).then_some(first) + } + let st = app.session.active()?; + let (mut items, mut radii, mut kinds, mut relative) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for &id in &st.selection.objects { + let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) else { continue }; + let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); + if corners.is_empty() { + continue; + } + for &k in &corners { + // The radius asked for, even where it draws smaller. A relative radius is stored as a + // fraction of the corner's largest; the field and `object.setLiveShape` take lengths. + radii.push(if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }); + kinds.push(lc.kind(k)); + } + relative.push(lc.radii_relative()); + items.push(json!({"id": id, "corners": corners})); + } + if items.is_empty() { + return None; + } + Some(PickedCorners { + items, + radius: shared(&radii, |a, b| (a - b).abs() < 1e-9), + kind: shared(&kinds, |a, b| a == b), + relative: shared(&relative, |a, b| a == b), + }) +} + +/// Run `object.setLiveShape` with `p` (a `kind`, `radius` or `relativeRadii`) on `picked`'s +/// corners: one undo step, or none when nothing changes. `App::run` reports a failure in the +/// status bar. +pub(crate) fn set_picked_corners(app: &mut VectorcraftApp, picked: &PickedCorners, mut p: Value) { + p["items"] = json!(picked.items); + app.run("object.setLiveShape", p).ok(); +} + +/// The Corners link's text, as [`corners_link`] draws it and [`corners_link_width`] measures it. +fn corners_link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Corners")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The width of [`corners_link`] in `ui`, with the point that the underline can add at its end. +pub(crate) fn corners_link_width(ui: &Ui) -> f32 { + crate::widgets::text_width(ui, corners_link_text(ui)) + 1.0 +} + +/// The Corners link of the Control bar and the Properties panel: a click on it opens or closes +/// [`corners_popup`] under it. `id` tells the two places apart. +pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { + let resp = ui.link(corners_link_text(ui)); + crate::widgets::popover(&resp, resp.clicked(), |ui| corners_popup(app, ui, id)); +} + +/// The Corners pop-up: the corner kind, the radius (blank while the picked corners differ) and +/// the rounding, Relative or Absolute (neither while their paths differ), of the picked corners +/// ([`picked_corners`]). Each change sets them on those corners alone, in one undo step. +fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { + let Some(picked) = picked_corners(app) else { return }; + let unit = app.session.general_unit(); + let mut set = None; + egui::Grid::new((id, "corners-popup")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + dim_label(ui, tl!("Corner:")); + ui.vertical(|ui| { + for k in CornerKind::ALL { + if crate::widgets::radio(ui, crate::dialogs::corners::kind_label(k), picked.kind == Some(k), true) { + set = Some(json!({"kind": k})); + } + } + }); + ui.end_row(); + dim_label(ui, tl!("Radius:")); + if let Some(r) = crate::widgets::num_field_named(ui, (id, "radius"), Some(tl!("Radius:")), picked.radius, unit, 100.0) { + // A negative radius typed in rounds nothing: the command takes 0 or more. + set = Some(json!({"radius": r.max(0.0)})); + } + ui.end_row(); + ui.label(""); + ui.horizontal(|ui| { + for (label, on) in [(tl!("Relative"), true), (tl!("Absolute"), false)] { + if crate::widgets::radio(ui, label, picked.relative == Some(on), true) { + set = Some(json!({"relativeRadii": on})); + } + } + }); + ui.end_row(); + }); + if let Some(p) = set { + set_picked_corners(app, &picked, p); + } +} + /// Number of selected objects. pub(crate) fn selection_len(app: &VectorcraftApp) -> usize { app.session.active().map(|d| d.selection.len()).unwrap_or(0) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 94b4edc638..0c2313c8f0 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -202,38 +202,50 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { }) } -/// The Corners of the one path whose corners Direct Selection has selected: their kind and radius, -/// which `object.setLiveShape` sets on those corners. The Properties panel overview shows the -/// control while the Direct Selection tool is chosen and a corner of an object is selected -/// (). -/// A live rectangle's and a live polygon's own rows already set the selected corners. +/// The Corners of the paths whose corners Direct Selection has selected: their kind, and the +/// Corners link with their radius, which `object.setLiveShape` sets on those corners +/// ([`super::picked_corners`]); the link opens the Corners pop-up for them. The Properties panel +/// overview shows the control while the Direct Selection tool is chosen and a corner of an object +/// is selected +/// (), +/// and the Corners link opens the corner settings +/// (). One live +/// rectangle or live polygon selected alone has its own kind and radius rows, which already set +/// the selected corners: it shows the Corners link alone. fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.tool_id() != "directSelection" { return; } let Some(st) = app.session.active() else { return }; - let [id] = st.selection.objects[..] else { return }; - let Some(n) = st.doc.node(id) else { return }; - if matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })) { + let own_rows = matches!(st.selection.objects[..], [id] + if st.doc.node(id).is_some_and(|n| matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })))); + // A corner of a path is Direct-Selected. + let corner_selected = st.selection.objects.iter().any(|id| { + st.doc.node(*id).and_then(LiveCorners::of).is_some_and(|lc| st.selection.partial(*id).is_some_and(|a| !lc.corners_of(a).is_empty())) + }); + if !corner_selected { return; } - let Some(lc) = LiveCorners::of(n) else { return }; - if st.selection.partial(id).is_none_or(|a| lc.corners_of(a).is_empty()) { + let Some(picked) = super::picked_corners(app) else { return }; + if own_rows { + ui.horizontal(|ui| super::corners_link(app, ui, "props-corners")); return; } - let n = n.clone(); - let kind = super::corner_style(app, &n).1; let kinds: Vec<&str> = vectorcraft_geom::shapes::CornerKind::ALL.iter().map(|k| crate::dialogs::corners::kind_label(*k)).collect(); let fw = super::field_width(ui); + let unit = app.session.general_unit(); egui::Grid::new("props-corners").num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { dim_label(ui, tl!("Corner:")); - let picked = widgets::dropdown_names(ui, ("props-corners", "kind"), kind.map_or("", crate::dialogs::corners::kind_label), &kinds, fw); - if let Some(k) = picked.and_then(|i| vectorcraft_geom::shapes::CornerKind::ALL.get(i)) { - app.run("object.setLiveShape", json!({"kind": k})).ok(); + let kind = widgets::dropdown_names(ui, ("props-corners", "kind"), picked.kind.map_or("", crate::dialogs::corners::kind_label), &kinds, fw); + if let Some(k) = kind.and_then(|i| vectorcraft_geom::shapes::CornerKind::ALL.get(i)) { + super::set_picked_corners(app, &picked, json!({"kind": k})); } ui.end_row(); - dim_label(ui, tl!("Corner Radius:")); - super::corner_radius_field(app, ui, &n, ("props-corners", "radius"), fw); + super::corners_link(app, ui, "props-corners"); + let name = Some(tl!("Corner Radius:")); + if let Some(r) = widgets::num_field_named(ui, ("props-corners", "radius"), name, picked.radius, unit, fw) { + super::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } ui.end_row(); }); } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index bc41fef557..668bb97d2a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1548,14 +1548,14 @@ fn direct_selected_corners_show_their_kind_and_radius() { app.select_tool("directSelection"); app.run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); - assert!(shows(&texts, "Corner:") && shows(&texts, "Corner Radius:"), "{texts:?}"); + assert!(shows(&texts, "Corner:") && shows(&texts, "Corners"), "{texts:?}"); let corners = |app: &VectorcraftApp| { let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(star)).unwrap().clone(); let lc = LiveCorners::of(&n).unwrap(); (lc.radius(0), lc.radius(2), lc.kind(0), lc.kind(2)) }; - // The radius: the field right of its label. - let label = text_at(&texts, "Corner Radius:"); + // The radius: the field right of the Corners link. + let label = text_at(&texts, "Corners"); let field = texts.iter().find(|(t, r)| t == "0 pt" && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0).unwrap().1; press(&mut app, &ctx, field.center()); let depth = undo_depth(&app); @@ -1581,6 +1581,125 @@ fn direct_selected_corners_show_their_kind_and_radius() { let texts = tall(&mut app, &ctx, vec![]); assert_eq!(texts.iter().filter(|(t, _)| t == "Corner:").count(), 1, "{texts:?}"); assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}"); + // And the Corners link, for the pop-up's rounding: Relative on the picked corner's rectangle. + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. +fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { + let id = rect(app, x, 50.0, 100.0, 100.0); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + id.as_u64().unwrap() +} + +/// The radius and kind of each corner of path `id`, from the top-left clockwise. +fn path_corners(app: &VectorcraftApp, id: u64) -> Vec<(f64, vectorcraft_geom::shapes::CornerKind)> { + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let lc = LiveCorners::of(&n).unwrap(); + (0..4).map(|k| (lc.radius(k), lc.kind(k))).collect() +} + +/// Types `text` into the field under `at` and presses Enter → the texts of the frame after. +fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, text: &str) -> Vec<(String, Rect)> { + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + press(app, ctx, at); + tall(app, ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]); + tall(app, ctx, vec![Event::Text(text.into())]); + tall(app, ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]); + tall(app, ctx, vec![]) +} + +/// The Corners link opens a pop-up with the corner kind, the radius and the rounding of the +/// Direct-Selected corners. A radius typed there, or a kind or rounding picked, sets the three +/// picked corners and leaves the fourth as it is, each in one undo step. +#[test] +fn the_corners_link_opens_the_settings_of_the_picked_corners() { + let mut app = new_app(); + let id = square_path(&mut app, 50.0); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(!shows(&texts, "Relative") && !shows(&texts, "Chamfer"), "closed: {texts:?}"); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + for t in ["Inverted Round", "Chamfer", "Radius:", "Relative", "Absolute"] { + assert!(shows(&texts, t), "{t} in {texts:?}"); + } + // The radius field, right of its label in the pop-up. + let label = text_at(&texts, "Radius:"); + let field = texts.iter().find(|(t, r)| t == "0 pt" && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0).unwrap().1; + let depth = undo_depth(&app); + let texts = type_into(&mut app, &ctx, field.center(), "18"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let (round, chamfer) = (vectorcraft_geom::shapes::CornerKind::Round, vectorcraft_geom::shapes::CornerKind::Chamfer); + assert_eq!(path_corners(&app, id), vec![(18.0, round), (18.0, round), (18.0, round), (0.0, round)]); + // A kind, picked in the pop-up. + let texts = press(&mut app, &ctx, text_at(&texts, "Chamfer").center()); + assert_eq!(undo_depth(&app), depth + 2, "one undo step"); + assert_eq!(path_corners(&app, id), vec![(18.0, chamfer), (18.0, chamfer), (18.0, chamfer), (0.0, round)]); + // Relative rounding, for the path the corners are on. + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + assert_eq!(undo_depth(&app), depth + 3, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// With a corner of each of two paths Direct-Selected and their radii different, the pop-up's +/// radius is blank; a radius typed there sets both corners, and no other, in one undo step. +#[test] +fn the_corners_pop_up_sets_picked_corners_across_paths() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + app.run("select.anchors", json!({"id": b, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let label = text_at(&texts, "Radius:"); + // Blank: no value right of the label. + assert!(!texts.iter().any(|(t, r)| t.ends_with("pt") && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0), "{texts:?}"); + let depth = undo_depth(&app); + type_into(&mut app, &ctx, egui::pos2(label.right() + 40.0, label.center().y), "7"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&app, a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&app, b), vec![(0.0, round), (7.0, round), (0.0, round), (0.0, round)]); +} + +/// With a corner of one path Direct-Selected and a second path selected whole, the pop-up picks +/// that corner and every corner of the second path. While one path is Relative and the other +/// Absolute, no rounding is chosen; picking Absolute sets both paths in one undo step. +#[test] +fn the_corners_pop_up_takes_every_corner_of_a_whole_path_and_mixed_rounding() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [a], "relativeRadii": true})).unwrap(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let picked = crate::panels::picked_corners(&app).unwrap(); + assert_eq!(picked.relative, None, "no rounding while the paths differ"); + assert_eq!(picked.items.len(), 2); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let depth = undo_depth(&app); + let texts = press(&mut app, &ctx, text_at(&texts, "Absolute").center()); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + assert_eq!(crate::panels::picked_corners(&app).unwrap().relative, Some(false), "both Absolute"); + let label = text_at(&texts, "Radius:"); + type_into(&mut app, &ctx, egui::pos2(label.right() + 40.0, label.center().y), "7"); + assert_eq!(undo_depth(&app), depth + 2, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&app, a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&app, b), vec![(7.0, round); 4], "every corner of the path selected whole"); } /// One effect on the one selected object shows its name and a Delete icon beside the fx button, diff --git a/crates/ui-egui/tests/control_bar_corners.rs b/crates/ui-egui/tests/control_bar_corners.rs index 7386e44a8c..2f7189efdc 100644 --- a/crates/ui-egui/tests/control_bar_corners.rs +++ b/crates/ui-egui/tests/control_bar_corners.rs @@ -127,7 +127,7 @@ fn corner_radius_existing_anchor_controls_and_properties_remain_available() { assert!(bar.has_text("Convert:") && bar.has_text("Anchors:"), "{:?}", bar.texts); assert!(bar.nodes.iter().any(|node| node.label() == Some("Remove Anchor Points"))); let properties = Frames::new(360.0, true).settled(&mut app); - assert!(properties.has_text("Corner Radius:"), "{:?}", properties.texts); + assert!(properties.has_text("Corners"), "{:?}", properties.texts); assert!(properties.texts.iter().any(|(text, _)| text == "0 pt")); } diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..a4b4a75882 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7682,8 +7682,8 @@ polygon's from its first vertex clockwise; a star's from its first tip; an index Each corner keeps its own radius and kind (the shape's `live` in queries has `radii` and, when a corner isn't round, `kinds`); a corner with no radius is one anchor, a cut one two, and Direct-Selected corners stay selected as that changes. A path that isn't a live shape keeps its uncut outline (`live` `{"shape": "path", "base", "radii"}`) so its -corners stay editable, and is a plain path again once no corner is cut; a polygon stays a live polygon, its corners -keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius +corners stay editable, and is a plain path again once no corner is cut, unless its rounding is Relative; a polygon +stays a live polygon, its corners keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform @@ -7702,6 +7702,17 @@ and those shape tools: hidden widgets are not drawn, and those tools do not answ on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. +In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with +Direct Selection, while a corner is selected) opens the Corners pop-up for the picked corners of every selected path: +the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors +hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the +rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the +paths differ). A path without Live Corners is Absolute, and Relative on a path with a corner keeps its outline as the +base of its Live Corners, as a radius does; ellipses and lines are left as they are. Editing a path's anchors (for +example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. With Relative rounding, a radius is +compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius +shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one +`object.setLiveShape` with `items`, one undo step, and the corners that were not picked keep their radius and kind. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"id":12,"corners":[1],"radius":16}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..bf9ca2c662 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1481,6 +1481,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules. Relative rounding also works on a plain path with corners (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_takes_on_a_plain_path`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..c0d8d424ff 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -490,6 +490,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | +| Control bar and Properties panel: Corners link and pop-up for the picked corners (part of #1232) | done | the link opens the corner kind, the radius (blank while the picked corners differ) and the Relative or Absolute rounding; each change sets the picked corners of every selected path in one `object.setLiveShape {items}`, one undo step | | Control bar: numeric Corner Radius for eligible selected ordinary and live corners (part of #7238, request 3 only) | done | Anchor Points visibility group; common/mixed values, general document units and multi-object edits through `object.setLiveShape`, one Undo. A partial selection containing no eligible corners contributes no target. Corner kind and relative mode are retained; existing corner-widget selection, widget visibility and maximum-radius behavior are unchanged. Requests 1/2 remain open. | | Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | From 4daef561c8d148f1a2237c43a9ea85c00741ec47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 05:30:30 -0800 Subject: [PATCH 08/84] Live Corners: a live rectangle or polygon selected whole shows the Corners link With Direct Selection, one live rectangle or live polygon selected whole now shows the Corners link in the Properties panel beside its own rows. Before, the panel showed the link only while an anchor of the shape was selected. The pop-up sets every corner of the shape. A path with Live Corners selected whole still shows no corner rows. --- crates/ui-egui/src/panels/properties.rs | 4 +-- crates/ui-egui/src/panels/properties/tests.rs | 32 +++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 0c2313c8f0..26b4729f8f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -211,7 +211,7 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { /// and the Corners link opens the corner settings /// (). One live /// rectangle or live polygon selected alone has its own kind and radius rows, which already set -/// the selected corners: it shows the Corners link alone. +/// the selected corners: it shows the Corners link alone, also while it is selected whole. fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.tool_id() != "directSelection" { return; @@ -223,7 +223,7 @@ fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { let corner_selected = st.selection.objects.iter().any(|id| { st.doc.node(*id).and_then(LiveCorners::of).is_some_and(|lc| st.selection.partial(*id).is_some_and(|a| !lc.corners_of(a).is_empty())) }); - if !corner_selected { + if !own_rows && !corner_selected { return; } let Some(picked) = super::picked_corners(app) else { return }; diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 668bb97d2a..8d2ef2973e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1588,6 +1588,38 @@ fn direct_selected_corners_show_their_kind_and_radius() { assert!(LiveCorners::of(&n).unwrap().radii_relative()); } +/// With Direct Selection, a live rectangle or live polygon selected whole keeps its own rows and +/// shows the Corners link, whose pop-up sets every corner of the shape. A path with Live Corners +/// selected whole shows no corner rows. +#[test] +fn a_whole_live_shape_with_direct_selection_shows_the_corners_link() { + let mut app = new_app(); + let ctx = egui::Context::default(); + app.select_tool("directSelection"); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + let polygon = app.run("shape.polygon", json!({"cx": 200, "cy": 150, "radius": 50, "sides": 5})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [polygon]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corners").count(), 1, "polygon: {texts:?}"); + app.run("select.set", json!({"ids": [r]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corners").count(), 1, "rectangle: {texts:?}"); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}"); + // The pop-up's rounding: Relative on the rectangle. + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let depth = undo_depth(&app); + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); + // A plain path selected whole: no corner selected. + let path = square_path(&mut app, 200.0); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [path]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(!shows(&texts, "Corner:") && !shows(&texts, "Corners"), "{texts:?}"); +} + /// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { let id = rect(app, x, 50.0, 100.0, 100.0); diff --git a/docs/mcp.md b/docs/mcp.md index a4b4a75882..e3f051ddc4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7703,7 +7703,7 @@ on them. `on`, when given and not `null`, must be `true` or `false` and sets the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with -Direct Selection, while a corner is selected) opens the Corners pop-up for the picked corners of every selected path: +Direct Selection, while a corner is selected or one live rectangle or polygon is selected) opens the Corners pop-up for the picked corners of every selected path: the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the From 073a654e6a3fce3f1b0cda098751f3b3b3ca2900 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:39:07 -0800 Subject: [PATCH 09/84] Packaging Tools: list Set Fold Angle's angle with the angles that are not turns The turn-direction test asks every angle param to say whether it turns clockwise or counter-clockwise. A fold angle folds a panel out of the page; the command's description says a positive angle folds it away from the printed side and a negative one toward it. The test now lists the param with the other angles that are not turns. --- crates/engine/src/tests/turn_direction.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), From 3768dd08291c5463400270ca7f64098102ed26cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:00:47 -0800 Subject: [PATCH 10/84] Packaging Tools: Set Fold Angle's OK changes the lines its dialog opened on The dialog keeps the lines it opened on as the command's ids, with the uid of their document. OK changes those lines even when the selection changes while the dialog is open, and changes nothing once another document is the active one. The split flap raster test now requires a flap at both samples: the right flap at both, or the left flap's inner part at the near sample and its outer part at the far one. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/addons.rs | 2 +- crates/engine/src/cmd/addons/packaging.rs | 2 +- .../engine/src/cmd/addons/packaging/angle.rs | 36 +++++++++++---- crates/three-d/src/fold/raster/tests.rs | 11 ++++- crates/ui-egui/src/addons/packaging.rs | 10 ++-- crates/ui-egui/src/addons/packaging/tests.rs | 46 +++++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 10 +++- 8 files changed, 100 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8622497c6a..c75e06c776 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -844,7 +844,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 32f8cfa645..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 779b044358..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -11,7 +11,7 @@ mod check; mod fold; mod roles; -pub use angle::{FoldAngles, selection_fold_angles}; +pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs index b458a3e410..f38645774f 100644 --- a/crates/engine/src/cmd/addons/packaging/angle.rs +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -216,23 +216,39 @@ pub fn selection_fold_angles(s: &Session) -> FoldAngles { } } +/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes +/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the +/// lines it changes. +pub fn selection_fold_lines(s: &Session) -> Vec { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(), + _ => Vec::new(), + } +} + /// The [`FoldAngles`] of the outermost objects `roots` of `d`. pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { - let table = RoleTable::of(d); - let editable = d.editable(); let mut f = FoldAngles::default(); - for n in role_targets(d, &editable_members(d, roots.to_vec()).0, false).0.iter().filter_map(|id| d.node(*id)) { - // The role first: whether an object can be edited can take its bounds to find out. - if let Some(role) = table.role_of(n) - && folds(role) - && editable(n.id) - { - f.add(n, role); - } + for (n, role) in changeable(d, roots) { + f.add(n, role); } f } +/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change, +/// with their roles, in order. +fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> { + let table = RoleTable::of(d); + let editable = d.editable(); + let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0; + // The role first: whether an object can be edited can take its bounds to find out. + targets + .iter() + .filter_map(|id| d.node(*id)) + .filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r))) + .collect() +} + impl FoldAngles { /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. pub(super) fn add(&mut self, n: &Node, role: Role) { diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index b6251985ca..014cf010d7 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -616,9 +616,16 @@ fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); // From the back the image is mirrored: x on the blank is 140 - x in the image. - let right_flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 90.0).abs() < 1e-6)).expect("the right flap"); + let starting_at = |x0: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x0).abs() < 1e-6)); + let right_flap = starting_at(90.0).expect("the right flap"); + // Folded back about x 30, the left flap's part from 15 to 30 lies at 30 to 45 and its part from + // 0 to 15 at 45 to 60. + let (inner, outer) = (starting_at(15.0).expect("the left flap's inner part"), starting_at(0.0).expect("its outer part")); let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); - assert_eq!(near == Some(right_flap), far == Some(right_flap), "{near:?} {far:?}"); + // Either flap may be in front, but the same one at both samples. + let right = (near, far) == (Some(right_flap), Some(right_flap)); + let left = (near, far) == (Some(inner), Some(outer)); + assert!(right || left, "{near:?} {far:?}: right flap {right_flap}, left flap {inner} and {outer}"); } #[test] diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index e43aed7ec8..01d038bd72 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -269,13 +269,17 @@ fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { } /// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle -/// the selected lines that it can change all fold at, else 90°. The command's reason while it -/// can't change any. +/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK +/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is +/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is +/// the active one. The command's reason while it can't change any. pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result { let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; (command.enabled)(&app.session)?; let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); - Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle })) + let ids: Vec = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect(); + let doc = app.session.active().map(|st| st.uid); + Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle, "__params": { "ids": ids }, "__doc": doc })) } /// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 4ee1334759..81d7338be3 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -324,6 +324,52 @@ fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(30.0)); } +/// Set Fold Angle…'s OK changes the lines the dialog opened on, even when the selection changes +/// while it is open (a remote command can change it): the other crease keeps its angle. +#[test] +fn set_fold_angle_s_ok_changes_the_lines_the_dialog_opened_on() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a, b]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("angle".into(), json!(30.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the dialog"); + let angle = |app: &mut VectorcraftApp, id: u64| { + app.run("select.set", json!({"ids": [id]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + }; + assert_eq!(angle(&mut app, a), Some(30.0), "the line the dialog opened on"); + assert_eq!(angle(&mut app, b), Some(90.0), "the line selected later keeps its role's angle"); +} + +/// Set Fold Angle…'s OK changes nothing once another document is the active one, even a line there +/// with the same id as the line the dialog opened on. +#[test] +fn set_fold_angle_s_ok_changes_nothing_in_another_document() { + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "the same id in the other document"); + app.run(SET_ROLE, json!({"role": "crease", "ids": [other]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("angle".into(), json!(30.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the dialog"); + let angle = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [a]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + }; + assert_eq!(angle(&mut app), Some(90.0), "the other document's line keeps its role's angle"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(angle(&mut app), Some(90.0), "the first document's line is left as it was"); +} + /// Set Fold Angle… keeps the angle typed into its dialog within -180° to 180°, so OK applies the /// nearest end instead of closing on an angle the command refuses. #[test] diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 16befd8f4b..cca99c9d6c 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -282,8 +282,16 @@ const FIRST_BASELINE: form::Choices = &[ const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; /// Closes before running, so a dialog the command opens stays open. A previewed one keeps its -/// preview as the one undo step. +/// preview as the one undo step. A dialog opened on one document's objects (`__doc`, its uid) +/// closes as Cancel does and runs nothing once another document is the active one, as Delete +/// Brush's question does (`brush_delete.rs`, `confirm`). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if let Some(doc) = d.fields.get("__doc") + && doc.as_u64() != app.session.active().map(|st| st.uid) + { + app.ui.dialog = None; + return Ok(json!({})); + } let (cmd, params) = call(d); if previews(d) { return form::commit_preview(app, &cmd, params); From 6209f84bcfa7a0bf9b9eb201c45dca6a01d4ebf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:03:49 -0800 Subject: [PATCH 11/84] Document Setup: the grid preview test edits the open dialog in one context The grid preview tests drew each edit in a new egui context, so they would pass if an open dialog kept drawing the old colors' texture. A new test draws one context through a color edit, a size edit and a preset edit, and checks the pixels of the texture the preview's mesh draws. --- crates/ui-egui/src/dialogs/document_setup.rs | 51 +++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 575603e926..a27e6cae40 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -1153,32 +1153,50 @@ mod tests { /// The grid preview Document Setup draws, in a fresh context: its rect, the texture /// coordinates of its bottom-right corner (two cells per unit) and the tile's four pixels. fn grid_preview(app: &mut VectorcraftApp) -> (Rect, egui::Vec2, Vec) { + grid_preview_in(app, &preview_context(), &mut Default::default()) + } + + /// A new context with the app's fonts and theme, for drawing the grid preview. + fn preview_context() -> egui::Context { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx, Default::default()); - let (mut mesh, mut pixels) = (None, None); + ctx + } + + /// The grid preview Document Setup draws in `ctx`: its rect, the texture coordinates of its + /// bottom-right corner (two cells per unit) and the four pixels of the texture its mesh draws. + /// `tiles` holds the pixels of each grid texture uploaded so far in `ctx`, so every frame drawn + /// in `ctx` goes through this function. + fn grid_preview_in( + app: &mut VectorcraftApp, + ctx: &egui::Context, + tiles: &mut std::collections::HashMap>, + ) -> (Rect, egui::Vec2, Vec) { + let mut mesh = None; for _ in 0..3 { let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); - let tiles: Vec = + let grids: Vec = ctx.tex_manager().read().allocated().filter(|(_, m)| m.name == crate::canvas::TRANSPARENCY_GRID).map(|(id, _)| *id).collect(); for (id, deltas) in &out.textures_delta.set { - if tiles.contains(id) + if grids.contains(id) && let Some(d) = deltas.last() { let egui::ImageData::Color(img) = &d.image; - pixels = Some(img.pixels.clone()); + tiles.insert(*id, img.pixels.clone()); } } out.textures_delta.clear(); mesh = out.shapes.iter().find_map(|c| match &c.shape { - egui::Shape::Mesh(m) if tiles.contains(&m.texture_id) => Some(m.clone()), + egui::Shape::Mesh(m) if grids.contains(&m.texture_id) => Some(m.clone()), _ => None, }); } let mesh = mesh.unwrap_or_else(|| panic!("no grid preview")); let uv = mesh.vertices.iter().fold(vec2(0.0, 0.0), |a, v| a.max(v.uv.to_vec2())); - (mesh.calc_bounds(), uv, pixels.unwrap_or_else(|| panic!("no tile"))) + let pixels = tiles.get(&mesh.texture_id).cloned().unwrap_or_else(|| panic!("no tile for {:?}", mesh.texture_id)); + (mesh.calc_bounds(), uv, pixels) } /// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells. @@ -1219,6 +1237,27 @@ mod tests { assert_eq!(undo_steps(&app), 0); } + /// In an open dialog, the preview follows each edit of Grid Colors and Grid Size: after a + /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. + #[test] + fn the_grid_preview_follows_edits_in_the_open_dialog() { + let (mut app, _) = transparency_tab(); + let (ctx, mut tiles) = (preview_context(), Default::default()); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!(["#ff0000", "#0000ff"])); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridSize".into(), json!("large")); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("Dark")); + let (_, _, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); + } + /// The grid preview sits beside Grid Size, Grid Colors and the color boxes, inside the dialog, /// and covers none of the tab's text or color boxes. #[test] From c6bea78bdf2beca24e46c919c10c613488a42b76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:19 -0800 Subject: [PATCH 12/84] Shapes: Curvature Circle Tool Options set its reach, label, anchors and arc rule Double-clicking the Curvature Circle tool opens Curvature Circle Tool Options (`tool.options {tool: "curvatureCircle"}`, dialog `curvatureCircleOptions`). OK sets the options with `tool.setOption`, and the preferences keep them: - Snap Tolerance (`snapTolerance`, 1 to 40 screen points, 5) is how near a path pulls the pointer; Smart Guides' Snapping Tolerance applies when it is larger. - Snap with Smart Guides Off (`snapWithoutGuides`) unchecked keeps the reach within Selection & Anchor Display's Tolerance while Smart Guides are off. - Annotate Radius (`annotateRadius`) unchecked hides the radius label. - Anchors at Standard Positions (`standardAnchors`) unchecked draws a path with an anchor where the circle touches the path and one every 90 degrees from there (`shape.curvatureCircle {anchors: "touch"}`). - Use the Radius of Circular Arcs (`constantRadius`) unchecked gives the cubic's own curvature on the cubic of a circular arc too (`shape.curvatureCircle {constantRadius: false}`). The range, the default and the Snap with Smart Guides Off rule are VectorCraft's own. Every switch is on by default, so the tool draws as before until an option is changed. The canvas check measures the path drawn, whose cubics reach a little past the circle when its anchors are where it touches. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 27 +++- crates/engine/src/tests/curvature_circle.rs | 83 ++++++++++ crates/geom/src/curvature.rs | 28 +++- crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/curvature_circle.rs | 150 +++++++++++++++--- crates/tools/src/curvature_circle/tests.rs | 95 +++++++++++ crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/curvature_circle_options.rs | 143 +++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 6 +- docs/mcp.md | 27 +++- 13 files changed, 530 insertions(+), 38 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/curvature_circle_options.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..911a24f40e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -144,6 +144,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 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. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..90e04db1a6 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Curvature Circle", [], None, - "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + "{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", has_doc, curvature_circle ), @@ -518,7 +518,8 @@ fn selected_anchor_points(s: &Session) -> Result>> { } /// A live ellipse that touches a path at a point with the path's curvature there -/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor +/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is. fn curvature_circle(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.curvatureCircle"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -529,6 +530,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`t` must be from 0 to 1")); } let convex = switch_or(p, "convex", false, C)?; + let arcs = switch_or(p, "constantRadius", true, C)?; + let key = "anchors"; + let at_touch = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("touch")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))), + }; let found = { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -540,7 +548,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { if seg >= sp.segment_count() { return Err(bad(C, "no such segment")); } - curvature::curvature_circle_on(sp, seg, t, convex) + curvature::curvature_circle_on_with(sp, seg, t, convex, arcs) }; let circle = found.map_err(|e| match e { NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), @@ -549,12 +557,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { })?; let (center, radius) = (circle.center, circle.radius); let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + let (path, live) = if at_touch { + (shapes::circle_with_anchors_at(center, radius, &[circle.at]), None) + } else { + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + (live.to_path(), Some(live)) + }; + // The bounds of the path drawn: started where it touches, its cubics reach a little past the + // circle. + if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) { return Err(bad(C, "the circle that matches the path there would reach past the canvas")); } - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays on the path. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index e862a03aaf..a5eed3aed6 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -224,3 +224,86 @@ fn the_next_click_passes_over_the_circle_the_tool_drew() { let third = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); } + +/// The anchors of `id`'s path. +fn anchors_of(s: &Session, id: NodeId) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect() +} + +/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path; +/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle +/// is; anything else is an error that draws nothing. +#[test] +fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap(); + let id = id_of(&v); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}"); + let anchors = anchors_of(&s, id); + assert_eq!(anchors.len(), 4); + assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}"); + assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0))); + + let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap()); + let upright = anchors_of(&s, upright); + s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap(); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(anchors_of(&s, id_of(&v)), upright); + + let count = object_count(&s); + for bad in [json!("points"), json!(4), json!(true)] { + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err()); + } + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err()); + assert_eq!(object_count(&s), count); +} + +/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the +/// circle with standard anchors, or with its anchors where it touches at a standard position, fits, +/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge. +#[test] +fn the_canvas_check_measures_the_path_drawn() { + let mut s = session(); + let edge = vectorcraft_doc::MAX_COORD - 0.05; + let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap(); + let path = id_of(&v); + let count = object_count(&s); + let near_right = json!({"id": path.0, "segment": 1, "t": 0.79}); + assert!(s.execute(C, &near_right).is_ok()); + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok()); + let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err(); + assert!(e.to_string().contains("past the canvas"), "{e}"); + assert_eq!(object_count(&s), count + 2); +} + +/// The tool's options are saved with the preferences and come back in the next session. +#[test] +fn the_tool_options_are_saved_with_the_preferences() { + let mut s = session(); + s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + let changed = + json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false}); + for (k, v) in changed.as_object().unwrap() { + s.set_tool_option(k, v); + } + s.select_tool("selection", ViewInfo::default()).unwrap(); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + assert_eq!(next.tool_options(), changed); +} + +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, larger than +/// the circle's at an anchor, and the result is not nominal. +#[test] +fn without_constant_radius_an_arc_gives_its_own_curvature() { + let mut s = session(); + let path = circle(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap(); + assert_eq!(v["nominal"], json!(false)); + assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}"); +} diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 304f20557e..eec3a72876 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; /// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to /// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + curvature_circle_with(c, t, convex, true) +} + +/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a +/// circular arc too. +pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result { let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); if !finite || !(0.0..=1.0).contains(&t) { return Err(NoCircle::Cusp); } let at = c.eval(t); - let (center, radius, nominal) = match circular_arc(c) { + let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) { Some((center, radius)) => { let out = at - center; let len = out.hypot(); @@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result Result { + curvature_circle_on_with(sp, seg, t, convex, true) +} + +/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`. +pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result { let n = sp.segment_count(); if seg >= n { return Err(NoCircle::Cusp); @@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re if corner { return Err(NoCircle::Corner); } - curvature_circle(c, t, convex) + curvature_circle_with(c, t, convex, arcs) } /// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether @@ -260,6 +271,19 @@ mod tests { } } + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is larger + /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. + #[test] + fn without_arcs_a_circle_segment_gives_its_own_curvature() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let sp = &pd.subpaths[0]; + let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap(); + let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap(); + assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}"); + assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}"); + assert_eq!(own.at, sp.segment(0).eval(0.0)); + } + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..f29ad291ce 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1175,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index b484651181..2df7ef0a48 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -13,21 +13,34 @@ //! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws //! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an //! edit, Undo or Redo is made outside the tool. +//! +//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the +//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); +//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › +//! Tolerance while Smart Guides are off; `annotateRadius` off hides the radius label; +//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every +//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off +//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every +//! switch is on by default. use std::collections::HashSet; -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::{MAX_COORD, NodeId}; -use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with}; +use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes}; +use crate::option_check; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub const ID: &str = "curvatureCircle"; -/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance -/// is larger. -const SNAP_PX: f64 = 5.0; +/// The range of `snapTolerance` (screen points). +pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0); +/// `snapTolerance` by default (screen points). +pub const DEFAULT_SNAP: f64 = 5.0; +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]; /// How far (screen points) the pointer travels from a press before the press counts as a drag. const DRAG_PX: f64 = 2.0; /// Half the length (screen points) of each arm of the cross at the circle's center. @@ -51,8 +64,37 @@ enum Found { Refused(&'static str, Point), } +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Options { + snap_tolerance: f64, + snap_without_guides: bool, + annotate_radius: bool, + standard_anchors: bool, + constant_radius: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "snapWithoutGuides" => &mut self.snap_without_guides, + "annotateRadius" => &mut self.annotate_radius, + "standardAnchors" => &mut self.standard_anchors, + "constantRadius" => &mut self.constant_radius, + _ => return None, + }) + } +} + #[derive(Default)] pub struct CurvatureCircleTool { + options: Options, /// The point under the pointer, and whether Shift was held. hover: Option<(Hit, bool)>, /// The press in progress, where the pointer was pressed: what a release draws. @@ -62,10 +104,20 @@ pub struct CurvatureCircleTool { drawn: HashSet, } -/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides › +/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no +/// further than Selection & Anchor Display › Tolerance. +fn reach(cx: &ToolContext, o: &Options) -> f64 { + let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol()); + if !cx.smart_guides && !o.snap_without_guides { + return snap.min(cx.pick_tol()); + } + snap +} + +/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. -fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { - let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); +fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet) -> Option { let mut best: Option<(Hit, f64)> = None; for id in crate::draw2::candidate_paths(cx) { if skip.contains(&id) { @@ -88,14 +140,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { /// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the /// path or segment is gone. -fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { +fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option { let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; if hit.segment >= sp.segment_count() { return None; } let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); - Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { - Ok(c) if on_canvas(&c) => Found::Circle(c), + Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) { + Ok(c) if on_canvas(&c, o) => Found::Circle(c), Ok(_) => Found::Refused("Circle too large", at), Err(NoCircle::Straight) => Found::Refused("Straight segment", at), Err(NoCircle::Cusp) => Found::Refused("Cusp", at), @@ -103,10 +155,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { }) } -/// Does the circle stay on the canvas? -fn on_canvas(c: &CurvatureCircle) -> bool { +/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors +/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path. +fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData { let (p, r) = (c.center, c.radius); - [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) + if !o.standard_anchors { + return shapes::circle_with_anchors_at(p, r, &[c.at]); + } + shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r)) +} + +/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it? +fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool { + drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) } impl Tool for CurvatureCircleTool { @@ -118,13 +179,14 @@ impl Tool for CurvatureCircleTool { if !ev.pos.is_finite() { return vec![]; } + let (o, tol) = (self.options, reach(cx, &self.options)); match ev.kind { PointerKind::Move => { - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); vec![] } PointerKind::Down => { - self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); self.hover = self.press; self.from = ev.pos; vec![] @@ -139,12 +201,21 @@ impl Tool for CurvatureCircleTool { } PointerKind::Up => { let press = self.press.take(); - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); let Some((hit, convex)) = press else { return vec![] }; - if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) { return vec![]; } - let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + let anchors = if o.standard_anchors { "standard" } else { "touch" }; + let p = json!({ + "id": hit.id.0, + "subpath": hit.subpath, + "segment": hit.segment, + "t": hit.t, + "convex": convex, + "constantRadius": o.constant_radius, + "anchors": anchors, + }); vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -210,10 +281,10 @@ impl Tool for CurvatureCircleTool { let Some((hit, convex)) = self.hover else { return vec![] }; let color = crate::draw2::FEEDBACK; let mut o = vec![]; - match found(cx, hit, convex) { + match found(cx, hit, convex, &self.options) { Some(Found::Circle(c)) => { let r = c.radius; - let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + let path = drawn_path(&c, &self.options).to_bezpath(); // The outline is drawn solid when it is longer than DASHED_PX on screen. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); @@ -222,7 +293,7 @@ impl Tool for CurvatureCircleTool { o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); - if cx.measurement_labels { + if cx.measurement_labels && self.options.annotate_radius { let star = if c.nominal { "*" } else { "" }; o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); } @@ -236,6 +307,39 @@ impl Tool for CurvatureCircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + json!({ + "snapTolerance": o.snap_tolerance, + "snapWithoutGuides": o.snap_without_guides, + "annotateRadius": o.annotate_radius, + "standardAnchors": o.standard_anchors, + "constantRadius": o.constant_radius, + }) + } + + /// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "snapTolerance" { + option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1) + } else if SWITCHES.contains(&key) { + option_check::boolean(key, value) + } else { + Err(option_check::unknown(key)) + } + } + + /// Sets one option; a value the option does not take leaves it as it was. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "snapTolerance" { + if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) { + self.options.snap_tolerance = v; + } + } else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) { + *switch = on; + } + } } #[cfg(test)] diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index d417af58dc..81c88cc4d0 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -284,3 +284,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() { let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); assert_eq!(ids.get(circle + 1), Some(&ID)); } + +/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart +/// Guides off the pointer reaches no further than the selection tolerance, and never further than +/// with the switch on; with Smart Guides on it reaches as far as before. +#[test] +fn the_snap_options_set_how_far_the_pointer_reaches() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]); + t.set_option("snapTolerance", &json!(10)); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2); + t.set_option("snapTolerance", &json!(5)); + t.set_option("snapWithoutGuides", &json!(false)); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2); + let guides = ToolContext { smart_guides: true, ..cx }; + assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2); + let wide = ToolContext { selection_tolerance: 8.0, ..cx }; + assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2); + assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]); +} + +/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius +/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends +/// `anchors: "touch"`. +#[test] +fn the_label_and_circle_options_change_what_is_shown_and_drawn() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let measure = |t: &CurvatureCircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard"))); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + assert!(measure(&t).is_some_and(|m| m.ends_with('*'))); + t.set_option("annotateRadius", &json!(false)); + assert_eq!(measure(&t), None); + t.set_option("annotateRadius", &json!(true)); + let arc = preview(&t.overlays(&cx)).unwrap(); + t.set_option("constantRadius", &json!(false)); + assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t)); + assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width()); + t.set_option("standardAnchors", &json!(false)); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch"))); +} + +/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle, +/// or with `standardAnchors` off starting where the circle touches the path. +#[test] +fn the_preview_follows_the_anchor_options() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let start = |t: &CurvatureCircleTool, cx: &ToolContext| { + t.overlays(cx).iter().find_map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default())); + let upright = start(&t, &cx).unwrap(); + let turned = ToolContext { constrain_angle: 30.0, ..cx }; + assert_eq!(start(&t, &turned), Some(upright)); + assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}"); + t.set_option("standardAnchors", &json!(false)); + let at = start(&t, &cx).unwrap(); + assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}"); +} + +/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are +/// errors, and `set_option` leaves the option as it was for them. +#[test] +fn invalid_options_are_refused() { + let mut t = CurvatureCircleTool::default(); + assert!(t.check_option("snapTolerance", &json!(0)).is_err()); + assert!(t.check_option("snapTolerance", &json!(41)).is_err()); + assert!(t.check_option("snapTolerance", &json!("5")).is_err()); + assert!(t.check_option("annotateRadius", &json!(1)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok()); + let before = t.options(); + t.set_option("snapTolerance", &json!(0)); + t.set_option("annotateRadius", &json!("no")); + assert_eq!(t.options(), before); +} diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..1086dd07aa 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -80,6 +80,8 @@ const ROWS: &[Row] = &[ (&["ellipse"], None, &["anchors"]), // Circle Tool Options (`circle::CircleTool`). (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), + // Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`). + (&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..a50bb4a46d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -34,6 +34,7 @@ mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod curvature_circle_options; pub mod custom_dictionary; pub mod dimension; mod document_setup; @@ -478,6 +479,7 @@ registry! { ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, CircleOptions: [circle_options::KIND] => circle_options::SPEC, + CurvatureCircleOptions: [curvature_circle_options::KIND] => curvature_circle_options::SPEC, ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/curvature_circle_options.rs b/crates/ui-egui/src/dialogs/curvature_circle_options.rs new file mode 100644 index 0000000000..3af2882b7f --- /dev/null +++ b/crates/ui-egui/src/dialogs/curvature_circle_options.rs @@ -0,0 +1,143 @@ +//! Curvature Circle Tool Options (double-click the Curvature Circle tool, or `tool.options`): Snap +//! Tolerance is how near, in screen points, a path pulls the pointer (Smart Guides' Snapping +//! Tolerance applies when it is larger); with Snap with Smart Guides Off unchecked, the pointer +//! reaches no further than the selection tolerance while Smart Guides are off; Annotate Radius +//! off hides the radius label; Anchors at Standard Positions off gives the circle an anchor where +//! it touches the path and one every 90° from there; Use the Radius of Circular Arcs off gives the +//! curve's own curvature on the curve of a circular arc too. OK sets them with +//! `tool.setOption {tool: "curvatureCircle", values}`; they last across tool switches and are saved +//! with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::curvature_circle::{DEFAULT_SNAP, ID as TOOL, SNAP_RANGE}; + +use super::{DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Curvature Circle Tool Options. +pub const KIND: &str = "curvatureCircleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// The switches the dialog edits, in the order it shows them, with their labels. +const SWITCHES: [(&str, &str); 4] = [ + ("snapWithoutGuides", "Snap with Smart Guides Off"), + ("annotateRadius", "Annotate Radius"), + ("standardAnchors", "Anchors at Standard Positions"), + ("constantRadius", "Use the Radius of Circular Arcs"), +]; + +/// Width of the label column. +const LABEL_W: f32 = 100.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// The option keys the dialog edits. +fn keys() -> impl Iterator { + ["snapTolerance"].into_iter().chain(SWITCHES.iter().map(|(key, _)| *key)) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let fields: Map = keys().filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let (min, max) = SNAP_RANGE; + let v = d.f64("snapTolerance", DEFAULT_SNAP); + widgets::label_row(ui, tl!("Snap Tolerance:"), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, "curvature-circle-snap", v, min..=max, "px", 1, 72.0) { + d.fields.insert("snapTolerance".into(), json!(x)); + } + }); + ui.add_space(6.0); + for (key, label) in SWITCHES { + form::check(ui, d, key, tl!(label)); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let values: Map = keys().filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Curvature Circle Tool Options", + "Snap Tolerance:", + "Snap with Smart Guides Off", + "Annotate Radius", + "Anchors at Standard Positions", + "Use the Radius of Circular Arcs", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for (key, _) in SWITCHES { + assert!(d.bool(key), "{key}"); + } + let before = d.f64("snapTolerance", 0.0); + d.fields.insert("snapTolerance".into(), json!(before + 3.0)); + for key in ["annotateRadius", "standardAnchors"] { + d.fields.insert(key.into(), json!(false)); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + assert_eq!(o["snapTolerance"], json!(before + 3.0)); + assert_eq!((&o["annotateRadius"], &o["standardAnchors"], &o["constantRadius"]), (&json!(false), &json!(false), &json!(true))); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("snapWithoutGuides")); + assert_eq!(d.f64("snapTolerance", 0.0), before + 3.0); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for values in [ + json!({"annotateRadius": false, "constantRadius": "no"}), + json!({"annotateRadius": false, "snapTolerance": 0}), + json!({"annotateRadius": false, "size": 3}), + ] { + assert!(app.run("tool.setOption", json!({"tool": TOOL, "values": values})).is_err(), "{values}"); + assert_eq!(app.session.tool_options_of(TOOL)["annotateRadius"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..6818e6ed5a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1176,7 +1176,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a4846cd35b..51a038b376 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -438,7 +438,8 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]), the Circle tool's ([`crate::dialogs::circle_options::open`]) and the +/// Curvature Circle tool's ([`crate::dialogs::curvature_circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -479,6 +480,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(crate::dialogs::circle_options::open(app)), + // The Curvature Circle tool: how near a path pulls the pointer, the radius label, where + // the circle's anchors go and whether a circular arc gives its own radius. + vectorcraft_tools::curvature_circle::ID => Ok(crate::dialogs::curvature_circle_options::open(app)), // The Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..2b4d76f339 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7238,13 +7238,18 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog ## Curvature circle -`shape.curvatureCircle {id, subpath?, segment, t, convex?}` draws the circle that touches path `id` at `t` (0 to 1) on -segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there (its circle of curvature), +`shape.curvatureCircle {id, subpath?, segment, t, convex?, constantRadius?, anchors?}` draws the circle that touches +path `id` at `t` (0 to 1) on segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there +(its circle of curvature), as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with `convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a -circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. The -result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. +circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. With +`constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at `t` instead. The +circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` +(`"standard"` when left out) the circle is a plain path with an anchor where it touches the path and one every 90° from +there. The result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes +the circle. The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle @@ -7264,6 +7269,20 @@ anchor, or where the circle would reach past the canvas, the pointer shows "Stra "Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until another tool is chosen or an edit, Undo or Redo is made outside the tool. +Curvature Circle Tool Options (`tool.options {tool: "curvatureCircle"}`, or a double-click on the tool, dialog +`curvatureCircleOptions`) sets the tool's options, which `tool.setOption {tool: "curvatureCircle", values}` also sets +and the preferences keep. The range, the default and the rule for Snap with Smart Guides Off are VectorCraft's own. +Every switch is on by default, and the tool draws as it did before the options existed until one is changed: + +- `snapTolerance` (Snap Tolerance, 1 to 40 screen points, 5 by default) is how near a path pulls the pointer. Smart + Guides › Snapping Tolerance applies when it is larger. +- `snapWithoutGuides` (Snap with Smart Guides Off) off makes the pointer reach no further than Selection & Anchor + Display › Tolerance while Smart Guides are off. +- `annotateRadius` (Annotate Radius) off hides the radius label. The label also needs Measurement Labels on. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "touch"`. +- `constantRadius` (Use the Radius of Circular Arcs) off draws with `constantRadius: false`, and the label has no + asterisk. + ```json {"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} ``` From c7eadb9656c547afbbae16ba797e284a69e5b05c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:08:47 -0800 Subject: [PATCH 13/84] Shapes: Curvature Circle docs say when Snap with Smart Guides Off has no effect docs/mcp.md and the tool's module comment say that unchecking Snap with Smart Guides Off does not change the reach when Selection & Anchor Display's Tolerance is as large as it. Two test comments now say the cubic's own curvature at the end of a quarter circle is smaller than the circle's, as their assertions check. --- crates/engine/src/tests/curvature_circle.rs | 4 ++-- crates/geom/src/curvature.rs | 2 +- crates/tools/src/curvature_circle.rs | 3 ++- docs/mcp.md | 21 ++++++++++----------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index a5eed3aed6..6290cb853f 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -297,8 +297,8 @@ fn the_tool_options_are_saved_with_the_preferences() { assert_eq!(next.tool_options(), changed); } -/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, larger than -/// the circle's at an anchor, and the result is not nominal. +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than +/// the circle's at an anchor, so a larger radius, and the result is not nominal. #[test] fn without_constant_radius_an_arc_gives_its_own_curvature() { let mut s = session(); diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index eec3a72876..aea7afde1d 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -271,7 +271,7 @@ mod tests { } } - /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is larger + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. #[test] fn without_arcs_a_circle_segment_gives_its_own_curvature() { diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index 2df7ef0a48..6d68f65a7d 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -17,7 +17,8 @@ //! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the //! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); //! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › -//! Tolerance while Smart Guides are off; `annotateRadius` off hides the radius label; +//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach +//! stays the same); `annotateRadius` off hides the radius label; //! `standardAnchors` off draws the circle with an anchor where it touches the path and one every //! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off //! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every diff --git a/docs/mcp.md b/docs/mcp.md index 2b4d76f339..e543ef72c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7240,16 +7240,14 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog `shape.curvatureCircle {id, subpath?, segment, t, convex?, constantRadius?, anchors?}` draws the circle that touches path `id` at `t` (0 to 1) on segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there -(its circle of curvature), -as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with -`convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two -ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a -circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. With -`constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at `t` instead. The -circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` -(`"standard"` when left out) the circle is a plain path with an anchor where it touches the path and one every 90° from -there. The result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes -the circle. +(its circle of curvature), as a live ellipse with the current paint, and selects it. The circle goes on the side the +path bends toward; with `convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc +of 90° or less (its two ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for +an arc of θ) gives a circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the +circle itself. With `constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at +`t` instead. The circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` (`"standard"` when left +out) the circle is a plain path with an anchor where it touches the path and one every 90° from there. The result is +`{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle @@ -7277,7 +7275,8 @@ Every switch is on by default, and the tool draws as it did before the options e - `snapTolerance` (Snap Tolerance, 1 to 40 screen points, 5 by default) is how near a path pulls the pointer. Smart Guides › Snapping Tolerance applies when it is larger. - `snapWithoutGuides` (Snap with Smart Guides Off) off makes the pointer reach no further than Selection & Anchor - Display › Tolerance while Smart Guides are off. + Display › Tolerance while Smart Guides are off. When that tolerance is as large as the reach above, turning the + switch off does not change the reach. - `annotateRadius` (Annotate Radius) off hides the radius label. The label also needs Measurement Labels on. - `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "touch"`. - `constantRadius` (Use the Radius of Circular Arcs) off draws with `constantRadius: false`, and the label has no From 88f496d873397729617a4bc707d2eb8fcbc4d191 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:54:54 -0800 Subject: [PATCH 14/84] Tangent Circle Tool: Add Points to Existing Paths adds anchors where the circle touches The tool gets an `addPoints` option (Add Points to Existing Paths in its options, off to start). When it is on, drawing a circle also adds an anchor point where the circle touches the first segment and the second segment, splitting them without changing their shape. The anchors and the circle are one undo step. A touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. When a touched path was not selected, the selection is put back before the circle is drawn, so Draw Behind places the circle behind the selected objects. The option label has a row in every complete catalog. Part of #7178. --- .../engine/src/cmd/addons/pathtools/tests.rs | 58 ++++ crates/tools/src/addons/tangent_circle.rs | 273 +++++++++++++++++- crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/addons/pathtools.rs | 4 + crates/ui-egui/src/addons/pathtools/tests.rs | 7 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 10 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 13 +- docs/target-app-parity.md | 2 + docs/ui-parity.md | 2 +- 37 files changed, 378 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..6bcfdbfc6c 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -1086,6 +1086,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); } +/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where +/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it +/// back. +#[test] +fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + let n = steps(&s); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1, "one undo step"); + let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(); + let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6) + }; + assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a)); + assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b)); + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap(); + assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2)); + assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too"); +} + +/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the +/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected. +#[test] +fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false); + select(&mut s, &[other]); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index)); + let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") }; + assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..22cbe4d6ba 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,9 +15,12 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at +//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the +//! segments the circle touches get an anchor point at each touch, which splits them without changing +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. -use kurbo::{CubicBez, Shape}; +use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_geom::{BezPath, ParamCurve, Point}; @@ -42,6 +45,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The label of the `addPoints` option in the tool's options. +pub const ADD_POINTS: &str = "Add Points to Existing Paths"; +/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in +/// effect, and its size. +const DOT_PX: f64 = 10.0; +const DOT_SIZE: f32 = 4.0; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -72,6 +81,11 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether drawing a circle adds anchor points where it touches the segments. + add_points: bool, + /// The keys held at the last pointer event, and whether the pointer is over the canvas. + mods: Mods, + over: bool, first: Option, hover: Option, press: Option, @@ -91,7 +105,20 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + add_points: false, + mods: Mods::default(), + over: false, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } @@ -120,6 +147,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() +} + +/// [`second_set`] with each segment's index on the second pick's subpath. +fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { return vec![]; } @@ -136,7 +168,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { indices.sort_unstable(); indices.dedup(); let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; - indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() +} + +/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either +/// end, where the segment already has an anchor point. +fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option { + if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol { + return None; + } + let t = curve.nearest(p, 1e-12).t; + (t > 0.0 && t < 1.0).then_some(t) +} + +/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment +/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath +/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the +/// anchor added before it does not move it along. +fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec { + let mut at: Vec<(NodeId, usize, usize, f64)> = vec![]; + if let Some(t) = split_at(&first.curve, c.first, tol) { + at.push((first.id, first.subpath, first.segment, t)); + } + let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq)); + if let Some((k, curve)) = nearest + && let Some(t) = split_at(curve, c.second, tol) + { + at.push((pick.id, pick.subpath, *k, t)); + } + at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2))); + at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect() } /// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot @@ -173,6 +234,14 @@ fn round_step(least: f64) -> f64 { /// distance from the origin, or too large, in floating point), or when the circle would reach past /// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { + circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p)) +} + +/// The command [`draw`] runs. +const CIRCLE: &str = "shape.circleThroughPoints"; + +/// The params of the [`CIRCLE`] command that [`draw`] runs. +fn circle_params(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -186,7 +255,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { return None; } let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); - Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) + Some(json!({ "points": points })) } fn segment_path(c: &CubicBez) -> BezPath { @@ -302,6 +371,8 @@ impl Tool for TangentCircleTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.pointer = ev.pos; + self.mods = ev.mods; + self.over = true; match ev.kind { PointerKind::Move => { self.hover = pick_at(cx, ev.pos); @@ -335,15 +406,34 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let Some(c) = self.found.take() else { return vec![] }; + let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; self.looked = false; - vec![action, Action::Notify(DRAWN.into())] + // Alt at the release turns `addPoints` the other way. + let steps = match &self.first { + Some(first) if self.add_points != ev.mods.alt => { + let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] }; + anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX)) + } + _ => vec![], + }; + if steps.is_empty() { + return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())]; + } + let mut commands = steps; + // A path that was not selected becomes the selection when it gets an anchor; the + // selection is put back before the circle, which Draw Behind places behind it. + if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) { + let ids: Vec = cx.selection.objects.iter().map(|id| id.0).collect(); + commands.push(json!({ "command": "select.set", "params": { "ids": ids } })); + } + commands.push(json!({ "command": CIRCLE, "params": params })); + // One undo step for the anchors and the circle, and none of them when a step fails. + vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -394,6 +484,7 @@ impl Tool for TangentCircleTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.over = false; if self.press.is_none() { self.found = None; self.looked = false; @@ -431,6 +522,11 @@ impl Tool for TangentCircleTool { // A label, which the canvas shows in the interface language. out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); } + // `addPoints` in effect, with Alt as it is now. + if (self.over || self.press.is_some()) && self.add_points != self.mods.alt { + let off = cx.tol(DOT_PX); + out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE }); + } out } @@ -439,14 +535,22 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ "radius": self.radius, "addPoints": self.add_points }) } fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + match key { + "radius" => { + if let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) { + self.radius = r; + } + } + "addPoints" => { + if let Some(on) = v.as_bool() { + self.add_points = on; + } + } + _ => {} } } @@ -454,6 +558,7 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "addPoints" => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -812,6 +917,144 @@ mod tests { assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + /// The steps of the `command.batch` an action list runs: (command, params) each. + fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN)); + p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect() + } + + /// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment. + fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) { + let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap()); + let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize]; + (id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap())) + } + + fn alt(mut e: PointerEvent) -> PointerEvent { + e.mods.alt = true; + e + } + + #[test] + fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y)).map(|p| p.id.0).unwrap(); + let (top, below) = (line_at(100.0), line_at(140.0)); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + assert_eq!(t.options()["addPoints"], json!(true)); + // The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter + // along each line, then the circle, in one batch. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}"); + let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + anchors.sort_by_key(|a| a.0); + let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))]; + want.sort_by_key(|a| a.0); + assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}"); + // The lines were not selected, so the selection (none) is put back before the circle. + assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}"); + let (cmd, params) = &steps[3]; + let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]); + assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}"); + assert!(t.first.is_none(), "ready for the next circle"); + // With both lines selected, the anchors leave the selection as it is: no step puts it back. + let mut both = Selection::default(); + both.add(NodeId(top)); + both.add(NodeId(below)); + let selected = self::cx(&d, &both, &p); + t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}"); + // Alt at the release turns it off for that circle, and with the option off turns it on. + for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] { + t.set_option("addPoints", &json!(on)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0))); + let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) }; + let released = up(&mut t, &cx, &release); + if adds { + assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}"); + } else { + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}"); + } + } + } + + #[test] + fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + t.set_option("radius", &json!(10)); + // The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310) + // on its second: the second segment's anchor comes first, so the first one's index holds. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + let l = pick_at(&cx, Point::new(300.0, 350.0)).map(|p| p.id.0); + let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))]; + assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}"); + assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE)); + // A circle touching both lines at their right ends: no anchor is added on top of an anchor, + // so only the circle is drawn, as without the option. + t.set_option("radius", &json!(36)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0)); + assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.options()["addPoints"], json!(false), "off to start"); + let dot = + |t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(!dot(&t)); + // Alt turns it on while held, and back off with the option on. + t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0))); + assert!(dot(&t)); + t.set_option("addPoints", &json!(true)); + assert!(!dot(&t)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(dot(&t)); + let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else { + panic!("no dot") + }; + assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}"); + // The pointer off the canvas: no dot left behind. + t.hover_ended(&cx); + assert!(!dot(&t)); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}"); + t.set_option("addPoints", &bad); + assert_eq!(t.options()["addPoints"], json!(true), "{bad}"); + } + assert_eq!(t.check_option("addPoints", &json!(false)), Ok(())); + } + #[test] fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..eab6c4d8c2 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..8e95ef0b35 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -245,6 +245,10 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("radius".into(), json!(x)); } }); + if widgets::check(ui, tangent_circle_tool::ADD_POINTS, d.bool("addPoints"), true) { + let on = !d.bool("addPoints"); + d.fields.insert("addPoints".into(), json!(on)); + } return false; } let rows = [ diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..41c7a083b5 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -99,14 +99,17 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + assert!(!app.ui.dialog.as_ref().unwrap().bool("addPoints")); let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:"), "{text}"); + assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:") && text.contains("Add Points to Existing Paths"), "{text}"); app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(12.5)); + app.ui.dialog.as_mut().unwrap().fields.insert("addPoints".into(), json!(true)); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..f0ab467d55 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7587,6 +7587,7 @@ breakText Glyphs Глифи Tangent Circle Допирателна окръжност Tangent Circle Tool Инструмент „Допирателна окръжност“ No tangent circle here Тук няма допирателна окръжност + Add Points to Existing Paths Добавяне на точки към съществуващите пътища Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..e44d6cf775 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7636,6 +7636,7 @@ shape Open Otvoren Tangent Circle Tangentna kružnica Tangent Circle Tool Alat tangentna kružnica No tangent circle here Ovdje nema tangentne kružnice + Add Points to Existing Paths Dodaj tačke postojećim putanjama Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..723ed98280 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifs Tangent Circle Cercle tangent Tangent Circle Tool Eina de cercle tangent No tangent circle here Aquí no hi ha cap cercle tangent + Add Points to Existing Paths Afegeix punts als traçats existents Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..2482c2a79f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8449,6 +8449,7 @@ breakText Glyphs Glyfy Tangent Circle Tečná kružnice Tangent Circle Tool Nástroj Tečná kružnice No tangent circle here Zde není žádná tečná kružnice + Add Points to Existing Paths Přidat body do existujících cest Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f45c4105ec 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10505,6 +10505,7 @@ breakText Glyphs Glyffer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkel-værktøj No tangent circle here Ingen tangentcirkel her + Add Points to Existing Paths Tilføj punkter til eksisterende stier Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d9d92b5777 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8074,6 +8074,7 @@ breakText Glyphs Glyphen Tangent Circle Tangentialkreis Tangent Circle Tool Tangentialkreis-Werkzeug No tangent circle here Hier kein Tangentialkreis + Add Points to Existing Paths Punkte zu vorhandenen Pfaden hinzufügen Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..34c2319db8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8440,6 +8440,7 @@ breakText Glyphs Γλύφοι Tangent Circle Εφαπτόμενος κύκλος Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ + Add Points to Existing Paths Προσθήκη σημείων σε υπάρχουσες διαδρομές Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..6eca1a8abe 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8426,6 +8426,7 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Herramienta Círculo tangente No tangent circle here No hay círculo tangente aquí + Add Points to Existing Paths Agregar puntos a trazados existentes Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..bb99ebe8e8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8516,6 +8516,7 @@ breakText Glyphs Merkit Tangent Circle Sivuava ympyrä Tangent Circle Tool Sivuava ympyrä -työkalu No tangent circle here Tässä ei ole sivuavaa ympyrää + Add Points to Existing Paths Lisää pisteitä olemassa oleviin polkuihin Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..da45f1758a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8445,6 +8445,7 @@ breakText Glyphs Glyphes Tangent Circle Cercle tangent Tangent Circle Tool Outil Cercle tangent No tangent circle here Aucun cercle tangent ici + Add Points to Existing Paths Ajouter des points aux tracés existants Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..eaaff584d8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4336,6 +4336,7 @@ arrowhead Feather પીંછું Tangent Circle સ્પર્શક વર્તુળ Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી + Add Points to Existing Paths હાલના પાથમાં બિંદુઓ ઉમેરો Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1c3714447f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5889,6 +5889,7 @@ arrowhead Feather पंख Tangent Circle स्पर्शी वृत्त Tangent Circle Tool स्पर्शी वृत्त टूल No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है + Add Points to Existing Paths मौजूदा पाथ में पॉइंट जोड़ें Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..78e5f306ea 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8435,6 +8435,7 @@ breakText Glyphs Glifák Tangent Circle Érintőkör Tangent Circle Tool Érintőkör eszköz No tangent circle here Itt nincs érintőkör + Add Points to Existing Paths Pontok hozzáadása a meglévő útvonalakhoz Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..a48310fbbe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8290,6 +8290,7 @@ breakText Glyphs Glif Tangent Circle Lingkaran singgung Tangent Circle Tool Alat lingkaran singgung No tangent circle here Tidak ada lingkaran singgung di sini + Add Points to Existing Paths Tambahkan titik ke jalur yang ada Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..02797ebe67 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8112,6 +8112,7 @@ breakText Glyphs Glifi Tangent Circle Cerchio tangente Tangent Circle Tool Strumento Cerchio tangente No tangent circle here Nessun cerchio tangente qui + Add Points to Existing Paths Aggiungi punti ai tracciati esistenti Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..5a92e57adc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10001,6 +10001,7 @@ breakText Glyphs 字形 Tangent Circle 接円 Tangent Circle Tool 接円ツール No tangent circle here ここに接円はありません + Add Points to Existing Paths 既存のパスにポイントを追加 Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..9f3cb89761 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10623,6 +10623,7 @@ breakText Glyphs გლიფები Tangent Circle მხები წრე Tangent Circle Tool მხები წრის ხელსაწყო No tangent circle here აქ მხები წრე არ არის + Add Points to Existing Paths არსებულ ტრაექტორიებზე წერტილების დამატება Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..1c5588142e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8084,6 +8084,7 @@ breakText Glyphs 글리프 Tangent Circle 접원 Tangent Circle Tool 접원 도구 No tangent circle here 여기에는 접원이 없음 + Add Points to Existing Paths 기존 패스에 포인트 추가 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..1ca547d523 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10343,6 +10343,7 @@ breakText Glyphs Glyphs Tangent Circle Raakcirkel Tangent Circle Tool Raakcirkel-gereedschap No tangent circle here Hier geen raakcirkel + Add Points to Existing Paths Punten toevoegen aan bestaande paden Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..554c02ee05 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8308,6 +8308,7 @@ breakText Glyphs Glify Tangent Circle Okrąg styczny Tangent Circle Tool Narzędzie Okrąg styczny No tangent circle here Brak okręgu stycznego w tym miejscu + Add Points to Existing Paths Dodaj punkty do istniejących ścieżek Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..deb2dd67c6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Ferramenta Círculo tangente No tangent circle here Nenhum círculo tangente aqui + Add Points to Existing Paths Adicionar Pontos aos Caminhos Existentes Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..59f7ef391c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8440,6 +8440,7 @@ breakText Glyphs Глифы Tangent Circle Касательная окружность Tangent Circle Tool Инструмент «Касательная окружность» No tangent circle here Здесь нет касательной окружности + Add Points to Existing Paths Добавить точки к существующим контурам Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..6c161e74d3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8484,6 +8484,7 @@ breakText Glyphs Glyfer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkelverktyget No tangent circle here Ingen tangentcirkel här + Add Points to Existing Paths Lägg till punkter i befintliga banor Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..81253fbab6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -937,6 +937,16 @@ fn tangent_circle_tool_note_is_in_complete_catalogs() { } } +/// The label of the Tangent Circle tool's Add Points to Existing Paths option, which its options +/// dialog takes from the tools crate. +#[test] +fn tangent_circle_tool_add_points_label_is_in_complete_catalogs() { + let label = vectorcraft_tools::addons::tangent_circle::ADD_POINTS; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } +} + /// The Artboard tool's add buttons take their tooltips from the tools crate, which the `tl!` scan /// does not read, so each complete catalog is checked for them here. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1b1a25a9c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10339,6 +10339,7 @@ breakText Glyphs Glifler Tangent Circle Teğet Daire Tangent Circle Tool Teğet Daire Aracı No tangent circle here Burada teğet daire yok + Add Points to Existing Paths Mevcut Yollara Nokta Ekle Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..faf64996bf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8094,6 +8094,7 @@ breakText Glyphs Гліфи Tangent Circle Дотичне коло Tangent Circle Tool Інструмент «Дотичне коло» No tangent circle here Тут немає дотичного кола + Add Points to Existing Paths Додати точки до наявних контурів Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..2903e0539e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8140,6 +8140,7 @@ breakText Glyphs Glyph Tangent Circle Đường tròn tiếp xúc Tangent Circle Tool Công cụ Đường tròn tiếp xúc No tangent circle here Không có đường tròn tiếp xúc ở đây + Add Points to Existing Paths Thêm điểm vào đường dẫn hiện có Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..08bd68d3e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8318,6 +8318,7 @@ breakText Glyphs 字形 Tangent Circle 相切圆 Tangent Circle Tool 相切圆工具 No tangent circle here 此处没有相切圆 + Add Points to Existing Paths 在现有路径上添加锚点 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..eae2ba19a1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8142,6 +8142,7 @@ breakText Glyphs 字符 Tangent Circle 相切圓 Tangent Circle Tool 相切圓工具 No tangent circle here 此處沒有相切圓 + Add Points to Existing Paths 在現有路徑上增加錨點 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..87eb6c5986 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14566,8 +14566,17 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. - Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` - gives an error for a value outside that range or one that is not a number, and for any other option. + With `addPoints` on, the circle also adds an anchor point to the first segment and to the second segment (or the + one beside it) where it touches them, with `path.insertAnchor` at that point, so the segments are split without + changing their shape; the anchors and the circle are one `command.batch` undo step, and one Undo removes all of them. + When a touched path was not selected, a `select.set` step puts the selection back before the circle is drawn, so + Draw Behind places the circle behind the objects that were selected. + A touch within 0.05 screen pixels of an existing anchor adds no anchor there; when neither touch adds one, only the + circle is drawn. Alt (Option on macOS) held at the release turns `addPoints` the other way for that circle, and a + dot right of and below the pointer shows while it is in effect, following Alt as it is pressed and let go. + Options (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36) and `addPoints` + (Add Points to Existing Paths, true or false, false). `tool.setOption` gives an error for a `radius` outside that + range or not a number, an `addPoints` that is not true or false, and any other option. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..fefd8b7352 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,6 +2997,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its options, off to start) also adds an anchor point where the circle touches each of the two segments, splitting them without changing their shape, in the circle's undo step; a touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. Tests: `addons::tangent_circle::tests::add_points_*` in `vectorcraft-tools`, `the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step` in `vectorcraft-engine`, and the options dialog and catalog tests in `vectorcraft-ui-egui`. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..37e1f716c7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -554,7 +554,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 › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (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; 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 › 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; 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 › 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 | From ea78ee5022c61e7435345391d8487f6c40ee25a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:59:11 -0800 Subject: [PATCH 15/84] Windows: the Paintbrush reads an airbrush pen's stylus wheel through Wintab Pointer messages carry no field for an airbrush pen's finger wheel, so a brush set to Stylus Wheel drew the half-way value on Windows. The new windows_wintab module reads the wheel from the tablet driver's Wintab interface as the tangential pressure of a cursor the driver reports as an airbrush, placed within its device's DVC_TPRESSURE range. - Wintab32.dll is loaded at run time from the system directory only (LoadLibraryExW with LOAD_LIBRARY_SEARCH_SYSTEM32). Without it, without one of its exports, or when a call fails, Windows pens read no wheel and draw as before. - The context is opened from the driver's default context with packet messages on and CXO_SYSTEM and CXO_PEN off, so it moves no cursor and makes no press. It follows the top-level window the pen is over. - WTInfoW answers are size-checked against a null-buffer call and read into a larger buffer; packets are read into a buffer larger than any packet and decoded from the fields the context asked for; a value outside the axis range reads as no wheel. - Pointer messages keep the pressure, end, tilt and rotation. A pen's message takes the airbrush's last wheel since it came near, or, when several cursors were read, the one whose latest packet came within 200 ms of the message, and none when more than one or none did. 0 counts as no wheel until the pen reports another value, as on macOS, and the readings start afresh on proximity, a cursor change, the other end, a canceled press and leaving the window. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/windows_stylus.rs | 71 ++- apps/vectorcraft/src/windows_wintab.rs | 816 +++++++++++++++++++++++++ crates/ui-egui/src/stylus.rs | 5 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 4 +- 6 files changed, 887 insertions(+), 17 deletions(-) create mode 100644 apps/vectorcraft/src/windows_wintab.rs diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..8ef7f04e6b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -79,6 +79,7 @@ mod windows_alt_codes; mod windows_cores; mod windows_screen_color; mod windows_stylus; +mod windows_wintab; mod xwayland; use vectorcraft_engine::Session; diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index e1ea35104d..15fcd4b9e2 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -24,6 +24,8 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come. +//! An airbrush pen's finger wheel comes from the tablet driver's Wintab interface instead, when it +//! has one ([`crate::windows_wintab`]). #![cfg_attr(not(windows), allow(dead_code))] use std::cell::RefCell; @@ -38,6 +40,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; /// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left /// detection range. const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; +/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. +const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; /// At most this many pointer contacts wait for their touch event. const MAX_PENDING: usize = 16; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. @@ -101,13 +105,19 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(feed) = FEED.get() else { return false; }; + crate::windows_wintab::msg_hook(msg); + if forgets_wheel(msg.message, msg.wParam.0) { + crate::windows_wintab::forget(); + } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; - let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); + let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); + let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation, wheel); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. @@ -134,12 +144,27 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po /// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is /// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the /// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no -/// field for an airbrush pen's finger wheel, so the pose has none. -fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { +/// field for an airbrush pen's finger wheel: `wheel` is the one the tablet driver's Wintab +/// interface reported for the message, if any ([`crate::windows_wintab`]). +fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Option) -> PenPose { let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); - PenPose { tilt, rotation, wheel: None }.sanitized() + PenPose { tilt, rotation, wheel }.sanitized() +} + +/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message +/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the +/// window. +fn forgets_wheel(message: u32, wparam: usize) -> bool { + let flags = wparam >> 16; + match message { + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { + flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0 + } + WM_POINTERLEAVE => true, + _ => false, + } } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -427,16 +452,42 @@ mod tests { #[test] fn a_pens_tilt_and_rotation_come_where_it_reports_them() { let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; - assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); - assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); - assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); - assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); - let wild = pen_pose(all, 400, i32::MIN, 720); + assert_eq!(pen_pose(all, 30, -45, 90, None), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); + assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90, None), PenPose::default(), "a pen that reports neither"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90, None), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359, None), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); + let wild = pen_pose(all, 400, i32::MIN, 720, None); assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges"); - let pose = pen_pose(all, 10, 20, 180); + let pose = pen_pose(all, 10, 20, 180, None); assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); } + #[test] + fn an_airbrush_wheel_goes_into_the_pose() { + let pose = pen_pose(PEN_MASK_PRESSURE, 0, 0, 0, Some(0.25)); + assert_eq!(pose, PenPose { wheel: Some(0.25), ..PenPose::default() }); + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + let pose = pen_pose(all, 10, 20, 180, Some(0.75)); + assert_eq!(pose, PenPose { tilt: Some([10.0, 20.0]), rotation: Some(180.0), wheel: Some(0.75) }, "with the tilt and rotation"); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, pose), PenSample { pressure: 0.5, eraser: false, pose }, "the pressure as before"); + assert_eq!(pen_pose(0, 0, 0, 0, Some(f32::NAN)).wheel, None, "not a number"); + } + + #[test] + fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!forgets_wheel(m, in_range), "{m:#x}"); + assert!(forgets_wheel(m, 7), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled), "canceled: {m:#x}"); + } + assert!(forgets_wheel(WM_POINTERLEAVE, in_range)); + // WM_MOUSEMOVE and WT_PACKET. + assert!(!forgets_wheel(0x0200, 0)); + assert!(!forgets_wheel(0x7FF0, 7)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..2c4166821a --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,816 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window. Without it, without one of its exports, or when a call fails, the pens +//! read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush read since the readings started +//! afresh, however long ago its last packet came, since a pen held still sends none. When +//! several cursors were read, it takes the one whose latest packet came within [`MAX_SKEW_MS`] of +//! the message, and none when two are that recent or none is ([`Readings::wheel_at`]). As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press is canceled, the pen leaves the window or detection range, or the +//! context closes. These rules are VectorCraft's own. +//! +//! The context closes when the driver closes it or its information changes (`WT_INFOCHANGE`), and +//! is dropped when its window no longer exists; a later pen message opens it again. +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. + eraser: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context, or after the queue overflowed, drops that cursor's reading. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & (TPS_PROXIMITY | TPS_QUEUE_ERR) != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, or the + /// context closed. + fn forget(&mut self) { + self.list.clear(); + self.eraser = None; + } + + /// The wheel for a pointer message of a pen at the message time `time` with its `eraser` end, + /// if the cursor it comes from is an airbrush: the one cursor read since the readings started + /// afresh, however long ago its last packet came (a pen held still sends none), or, when + /// several were, the one whose latest packet is within [`MAX_SKEW_MS`] of the message. `None` + /// when no cursor, or more than one, is that recent, or the cursor has read only 0 since the + /// readings started afresh. A turn to the other end starts them afresh first. + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + if self.eraser.is_some_and(|e| e != eraser) { + self.forget(); + } + self.eraser = Some(eraser); + let r = match self.list.as_slice() { + [one] => one, + list => { + let mut near_time = list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + } + }; + if !r.moved { + return None; + } + r.axis?.wheel(r.raw) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// The context step for a pen message to a window owned by `owner`: what happens to the open +/// context, whose window is `current` with whether that window still exists, and whether a context +/// is opened for `owner`. The context follows the window the pen draws in. An open is tried once +/// for a window until another window is tried or the driver closes or changes the context +/// (`tried`). +fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usize) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + (step, tried != Some(owner) || step != Current::Keep) +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + Other, +} + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::RefCell; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::HWND; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::UI::WindowsAndMessaging::{GA_ROOTOWNER, GetAncestor, IsWindow, MSG}; + use windows::core::{s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, + MAX_READINGS, Message, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, configure, decode, + device_of, message, next_context, wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for ([`next_context`]). + tried: Option<*mut c_void>, + /// Each cursor's wheel range, as the driver reported it. + cursors: Vec<(u32, Option)>, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`, `None` for a cursor without one or one the driver does not + /// describe. + fn cursor_axis(api: Api, cursor: u32) -> Option { + if cursor >= MAX_INDEX { + return None; + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE)?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA)?; + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES)?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + devices.push((info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR)?[0], info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES)?[0])); + } + let device = u32::try_from(device_of(cursor, &devices)?).ok()?; + wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + } + self.readings.forget(); + } + + /// Moves the context to the window that owns `hwnd` ([`next_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let (step, open) = next_context(current, self.tried.map(|w| w as usize), owner as usize); + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some(owner); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + if !handle.is_null() { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32) -> Option { + if let Some(&(_, axis)) = self.cursors.iter().find(|(c, _)| *c == cursor) { + return axis; + } + let axis = cursor_axis(api, cursor); + if self.cursors.len() >= MAX_READINGS * 4 { + self.cursors.remove(0); + } + self.cursors.push((cursor, axis)); + axis + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. It never consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + let Some(api) = api() else { return }; + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + if unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } == 0 { + return; + } + let Some(p) = decode(&buf.0, PACKET_DATA) else { return }; + let axis = s.axis(api, p.cursor); + s.readings.packet(p, axis, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { ctx } => { + if s.context.as_ref().is_some_and(|c| c.handle as usize == ctx) { + s.context = None; + s.tried = None; + s.readings.forget(); + } + } + Message::InfoChange => { + s.close(api); + s.tried = None; + s.cursors.clear(); + } + Message::Other => {} + } + }); + } + + /// The wheel for a pointer message of a pen to `hwnd` at the message time `time`, with its + /// `eraser` end ([`Readings::wheel_at`]), opening the context first when none is open. + pub fn pen_wheel(hwnd: HWND, time: u32, eraser: bool) -> Option { + let api = api()?; + STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.open_for(api, hwnd.0); + s.readings.wheel_at(time, eraser) + }) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. + pub fn forget() { + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.readings.forget(); + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + assert_eq!(next_context(None, None, main), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(next_context(Some((main, true)), Some(main), main), (Current::Keep, false), "the same window keeps it"); + assert_eq!(next_context(Some((main, true)), Some(main), doc), (Current::Close, true), "another document window"); + assert_eq!(next_context(Some((doc, true)), Some(doc), main), (Current::Close, true), "and back"); + assert_eq!(next_context(Some((main, false)), Some(main), doc), (Current::Drop, true), "a window that is gone"); + assert_eq!(next_context(Some((main, false)), Some(main), main), (Current::Drop, true), "its handle reused"); + assert_eq!(next_context(None, Some(main), main), (Current::Keep, false), "an open that failed is not tried again"); + assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0b27d24127..0b3eb92416 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -12,8 +12,9 @@ //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. //! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the -//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on -//! Windows, whose pointer messages have no field for it, or in the web build. +//! host reads it: from XInput2 on X11, from AppKit on macOS, and on Windows, whose pointer messages +//! have no field for it, from the tablet driver's Wintab interface when the driver has one. The app +//! does not read it in the web build. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..2515a3bc92 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4170,9 +4170,10 @@ already walks Image Trace. Short agent entry points: value goes from the value less the variation (a Scatter brush's first value, an Art brush's `width`) at 0 to the value plus the variation (the second value, `width_max`) at 1, and a stroke without a wheel draws the value half way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The - desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; - it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation - code 3. + desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and + on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` + is installed; without it a Windows pen reads no wheel. The web build does not read it. `.ai` brush definitions read + and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..6e53dbc469 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2057,7 +2057,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2065,7 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_pose` and `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` (vectorcraft). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 29fa62b46ce32c1a360c1075cd9dce95dcbac872 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:12:24 -0800 Subject: [PATCH 16/84] Windows: the Wintab wheel follows the driver's context notices The tablet driver sends WT_CTXCLOSE and WT_INFOCHANGE to the window procedure, and a sent message does not pass winit's message hook, so a context the driver closed kept its handle and the wheel stopped reading. The context's window now gets a window procedure in front of its own that notes both notices. The next Wintab or pen message drops a closed context or closes and reopens it after an information change, forgetting the cached cursor ranges. A notice the reader causes by closing its own context does not drop a later context with the same handle value. A packet that WTPacket cannot read now starts the readings afresh, so a pen message no longer takes a wheel value that may be stale. Only the pen whose message last read the wheel clears the readings when it leaves the window or detection range or its press is canceled; a touch or another pen leaving keeps them. --- apps/vectorcraft/src/windows_stylus.rs | 41 +++- apps/vectorcraft/src/windows_wintab.rs | 267 ++++++++++++++++++++++--- 2 files changed, 267 insertions(+), 41 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 15fcd4b9e2..1a75122ac9 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -70,6 +70,8 @@ const WM_POINTERLEAVE: u32 = 0x024A; thread_local! { static STROKES: RefCell = RefCell::new(BarrelStrokes::default()); + /// The pointer id of the pen whose message last read the Wintab wheel. + static WHEEL_PEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// The pen feed [`msg_hook`] writes, once [`start`] has made it. @@ -106,14 +108,16 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { return false; }; crate::windows_wintab::msg_hook(msg); - if forgets_wheel(msg.message, msg.wParam.0) { + if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) { crate::windows_wintab::forget(); } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); + let id = (msg.wParam.0 & 0xffff) as u32; // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. - unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; + unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; + WHEEL_PEN.set(Some(id)); let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); @@ -155,8 +159,12 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Optio /// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message /// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the -/// window. -fn forgets_wheel(message: u32, wparam: usize) -> bool { +/// window, when the pointer is `pen`, the pen whose message last read the wheel. A touch or another +/// pen leaving keeps the readings. +fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + if pen != Some((wparam & 0xffff) as u32) { + return false; + } let flags = wparam >> 16; match message { WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { @@ -477,15 +485,28 @@ mod tests { fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + let pen = Some(7); for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { - assert!(!forgets_wheel(m, in_range), "{m:#x}"); - assert!(forgets_wheel(m, 7), "out of range: {m:#x}"); - assert!(forgets_wheel(m, canceled), "canceled: {m:#x}"); + assert!(!forgets_wheel(m, in_range, pen), "{m:#x}"); + assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}"); } - assert!(forgets_wheel(WM_POINTERLEAVE, in_range)); + assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen)); // WM_MOUSEMOVE and WT_PACKET. - assert!(!forgets_wheel(0x0200, 0)); - assert!(!forgets_wheel(0x7FF0, 7)); + assert!(!forgets_wheel(0x0200, 0, Some(0))); + assert!(!forgets_wheel(0x7FF0, 7, pen)); + } + + #[test] + fn another_pointer_leaving_keeps_the_wheel() { + // A touch, pointer 9, leaves the window and detection range while pen 7 hovers. + let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9; + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7))); + assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range"); + let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9; + assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled"); + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel"); + assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); } #[test] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 2c4166821a..9075c5bd19 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -30,11 +30,15 @@ //! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the //! readings start afresh when a cursor //! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns -//! to its other end, a press is canceled, the pen leaves the window or detection range, or the -//! context closes. These rules are VectorCraft's own. +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. //! -//! The context closes when the driver closes it or its information changes (`WT_INFOCHANGE`), and -//! is dropped when its window no longer exists; a later pen message opens it again. +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`), and dropped when its window no longer exists; a later pen +//! message opens it again. The driver sends those two notices to the window procedure, where a +//! sent message does not pass winit's message hook, so the context's window gets a window procedure +//! in front of its own that notes them ([`Notices`]). A packet that `WTPacket` cannot read also +//! starts the readings afresh ([`Readings::read`]). #![cfg_attr(not(windows), allow(dead_code))] /// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. @@ -279,8 +283,18 @@ impl Readings { } } - /// Start afresh: the pen came near or left, another cursor came, a press was canceled, or the - /// context closed. + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, or the context closed. fn forget(&mut self) { self.list.clear(); self.eraser = None; @@ -341,6 +355,67 @@ fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usi (step, tried != Some(owner) || step != Current::Keep) } +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`) since they were last +/// taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, +} + +/// What the driver's notices do to the open context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Notice { + /// Nothing changed for it. + Keep, + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + Closed, + /// The driver's information changed: close it, forget each cursor's wheel range, and open a + /// context again at the next pen message. + Reopen, +} + +impl Notices { + /// Notes `message` if it is a closing or information-change notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + if notices.info_changed { + Notice::Reopen + } else if current.is_some_and(|c| notices.closed.contains(&c)) { + Notice::Closed + } else { + Notice::Keep + } + } +} + /// What a message does to the readings and the context. #[derive(Clone, Copy, Debug, PartialEq)] enum Message { @@ -385,15 +460,18 @@ mod win { use std::ffi::c_void; use std::sync::OnceLock; - use windows::Win32::Foundation::HWND; + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; - use windows::Win32::UI::WindowsAndMessaging::{GA_ROOTOWNER, GetAncestor, IsWindow, MSG}; - use windows::core::{s, w}; + use windows::Win32::UI::WindowsAndMessaging::{ + CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetPropW, GetWindowLongPtrW, IsWindow, MSG, RemovePropW, SetPropW, + SetWindowLongPtrW, WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, configure, decode, - device_of, message, next_context, wheel_axis, + MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, + configure, decode, device_of, message, next_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -432,6 +510,73 @@ mod win { thread_local! { static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window. The window's + /// property holds the procedure it replaced, and goes with the window. + fn subclass(hwnd: *mut c_void) { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } } /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. @@ -506,10 +651,34 @@ mod win { if let Some(c) = self.context.take() { // SAFETY: the handle came from `WTOpenW` and has not been closed. unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); } self.readings.forget(); } + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::Keep, |mut n| n.take(current))); + match notice { + Notice::Keep => {} + Notice::Closed => { + self.context = None; + self.tried = None; + self.readings.forget(); + } + Notice::Reopen => { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + } + } + /// Moves the context to the window that owns `hwnd` ([`next_context`]). fn open_for(&mut self, api: Api, hwnd: *mut c_void) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. @@ -535,6 +704,7 @@ mod win { let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; if !handle.is_null() { self.context = Some(Context { handle, hwnd: owner }); + subclass(owner); } } @@ -556,46 +726,35 @@ mod win { } /// winit's message hook for the Wintab messages: reads each packet of the context and starts - /// the readings afresh on a cursor's change or proximity. It never consumes the message. + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. pub fn msg_hook(msg: &MSG) { let what = message(msg.message, msg.wParam.0, msg.lParam.0); if what == Message::Other { return; } let Some(api) = api() else { return }; + note(what); STATE.with(|s| { let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); match what { Message::Packet { serial, ctx } => { let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; let mut buf = PacketBuffer([0; PACKET_BUFFER]); // SAFETY: the handle is the open context's, and `buf` holds more bytes than a // packet of every field. - if unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } == 0 { - return; - } - let Some(p) = decode(&buf.0, PACKET_DATA) else { return }; - let axis = s.axis(api, p.cursor); - s.readings.packet(p, axis, msg.time); + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor))); + s.readings.read(read, msg.time); } Message::Forget { ctx } => { if s.ours(msg.hwnd.0, ctx).is_some() { s.readings.forget(); } } - Message::Closed { ctx } => { - if s.context.as_ref().is_some_and(|c| c.handle as usize == ctx) { - s.context = None; - s.tried = None; - s.readings.forget(); - } - } - Message::InfoChange => { - s.close(api); - s.tried = None; - s.cursors.clear(); - } - Message::Other => {} + Message::Closed { .. } | Message::InfoChange | Message::Other => {} } }); } @@ -606,6 +765,7 @@ mod win { let api = api()?; STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); s.open_for(api, hwnd.0); s.readings.wheel_at(time, eraser) }) @@ -802,6 +962,51 @@ mod tests { assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); } + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), Notice::Keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), Notice::Keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice::Closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), Notice::Keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), Notice::Keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice::Reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), Notice::Reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), Notice::Keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), Notice::Closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + #[test] fn wintab_messages_name_their_context() { assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); From 7bf46c2101599b6ba5e4b93e3b7ca1e63dff60a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:54:18 -0800 Subject: [PATCH 17/84] Windows: the Wintab wheel drops a context the driver closed and clears readings on a queue overflow - A close notice and an information change in one batch now both count: the handle the driver closed is dropped without WTClose, and each cursor's wheel range is read again. - The window procedure that notes the driver's notices is put in front of the window's own before a context is opened. When it cannot be, no context is opened for that window. - A packet that reports the context's queue overflowed (TPS_QUEUE_ERR) starts every reading afresh, not only its own cursor's. - The first pen whose pointer message comes within 200 ms of an airbrush packet takes the readings. Another pen's messages read no wheel until they start afresh, and the taking pen's leaving starts them afresh. --- apps/vectorcraft/src/windows_stylus.rs | 10 +- apps/vectorcraft/src/windows_wintab.rs | 277 ++++++++++++++++++------- 2 files changed, 208 insertions(+), 79 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 1a75122ac9..a5d9b86271 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -70,7 +70,9 @@ const WM_POINTERLEAVE: u32 = 0x024A; thread_local! { static STROKES: RefCell = RefCell::new(BarrelStrokes::default()); - /// The pointer id of the pen whose message last read the Wintab wheel. + /// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that + /// took them, or the pen whose message last asked for the wheel when none has + /// ([`crate::windows_wintab::wheel_pen`]). static WHEEL_PEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } @@ -117,10 +119,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; - WHEEL_PEN.set(Some(id)); let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; - let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser); + WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id))); let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation, wheel); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; @@ -159,7 +161,7 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Optio /// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message /// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the -/// window, when the pointer is `pen`, the pen whose message last read the wheel. A touch or another +/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another /// pen leaving keeps the readings. fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { if pen != Some((wparam & 0xffff) as u32) { diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 9075c5bd19..ba4c784049 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -23,10 +23,12 @@ //! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, //! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 //! ([`Axis::wheel`]); a value outside it reads as none. -//! - A pointer message of a pen takes the wheel of the airbrush read since the readings started -//! afresh, however long ago its last packet came, since a pen held still sends none. When -//! several cursors were read, it takes the one whose latest packet came within [`MAX_SKEW_MS`] of -//! the message, and none when two are that recent or none is ([`Readings::wheel_at`]). As on +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on //! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the //! readings start afresh when a cursor //! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns @@ -34,11 +36,14 @@ //! range, or the context closes. These rules are VectorCraft's own. //! //! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's -//! information changes (`WT_INFOCHANGE`), and dropped when its window no longer exists; a later pen -//! message opens it again. The driver sends those two notices to the window procedure, where a -//! sent message does not pass winit's message hook, so the context's window gets a window procedure -//! in front of its own that notes them ([`Notices`]). A packet that `WTPacket` cannot read also -//! starts the readings afresh ([`Readings::read`]). +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). #![cfg_attr(not(windows), allow(dead_code))] /// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. @@ -257,14 +262,22 @@ struct Readings { list: Vec, /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. eraser: Option, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, } impl Readings { /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of - /// a cursor out of the context, or after the queue overflowed, drops that cursor's reading. + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } let at = self.list.iter().position(|r| r.cursor == p.cursor); - if p.status & (TPS_PROXIMITY | TPS_QUEUE_ERR) != 0 { + if p.status & TPS_PROXIMITY != 0 { if let Some(i) = at { self.list.remove(i); } @@ -294,25 +307,36 @@ impl Readings { } /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet - /// could not be read, or the context closed. + /// could not be read, the context's queue overflowed, or the context closed. fn forget(&mut self) { self.list.clear(); self.eraser = None; + self.pen = None; } - /// The wheel for a pointer message of a pen at the message time `time` with its `eraser` end, - /// if the cursor it comes from is an airbrush: the one cursor read since the readings started - /// afresh, however long ago its last packet came (a pen held still sends none), or, when - /// several were, the one whose latest packet is within [`MAX_SKEW_MS`] of the message. `None` - /// when no cursor, or more than one, is that recent, or the cursor has read only 0 since the - /// readings started afresh. A turn to the other end starts them afresh first. - fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the one cursor read since they started afresh, however long ago its last packet + /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, + /// or the cursor has read only 0 since the readings started afresh, or another pen's message + /// read a wheel first since then. A turn to the other end starts them afresh first. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } if self.eraser.is_some_and(|e| e != eraser) { self.forget(); } self.eraser = Some(eraser); let r = match self.list.as_slice() { - [one] => one, + [one] if self.pen == Some(pen) => one, list => { let mut near_time = list.iter().filter(|r| near(time, r.time)); let r = near_time.next()?; @@ -325,7 +349,9 @@ impl Readings { if !r.moved { return None; } - r.axis?.wheel(r.raw) + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + Some(wheel) } } @@ -369,17 +395,15 @@ struct Notices { info_changed: bool, } -/// What the driver's notices do to the open context. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Notice { - /// Nothing changed for it. - Keep, +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { /// The driver closed it: drop the handle without `WTClose`, and open a context again at the /// next pen message. - Closed, - /// The driver's information changed: close it, forget each cursor's wheel range, and open a - /// context again at the next pen message. - Reopen, + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, } impl Notices { @@ -406,16 +430,17 @@ impl Notices { /// Takes the notices: what they do to the open context `current`. fn take(&mut self, current: Option) -> Notice { let notices = std::mem::take(self); - if notices.info_changed { - Notice::Reopen - } else if current.is_some_and(|c| notices.closed.contains(&c)) { - Notice::Closed - } else { - Notice::Keep - } + Notice { closed: current.is_some_and(|c| notices.closed.contains(&c)), info_changed: notices.info_changed } } } +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own; otherwise opens none, and the window is not tried again +/// until another window is ([`next_context`]). +fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() { open() } else { None } +} + /// What a message does to the readings and the context. #[derive(Clone, Copy, Debug, PartialEq)] enum Message { @@ -451,7 +476,7 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel}; +pub use win::{forget, msg_hook, pen_wheel, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] @@ -471,7 +496,7 @@ mod win { use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, message, next_context, wheel_axis, + configure, decode, device_of, hooked_open, message, next_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -553,30 +578,33 @@ mod win { unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } } - /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window. The window's - /// property holds the procedure it replaced, and goes with the window. - fn subclass(hwnd: *mut c_void) { + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { let hwnd = HWND(hwnd); // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { - return; + return true; } // SAFETY: as above. let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; if prev == 0 { - return; + return false; } // SAFETY: the window is this thread's (winit's), and the property's value is a procedure // address, not memory the system frees. if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { - return; + return false; } type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { // SAFETY: as for `SetPropW`. let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; } + true } /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. @@ -663,19 +691,16 @@ mod win { /// Acts on the driver's notices since the last look ([`Notices::take`]). fn take_notices(&mut self, api: Api) { let current = self.context.as_ref().map(|c| c.handle as usize); - let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::Keep, |mut n| n.take(current))); - match notice { - Notice::Keep => {} - Notice::Closed => { - self.context = None; - self.tried = None; - self.readings.forget(); - } - Notice::Reopen => { - self.close(api); - self.tried = None; - self.cursors.clear(); - } + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); } } @@ -700,11 +725,17 @@ mod win { self.tried = Some(owner); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); - // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for the call. - let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; - if !handle.is_null() { + let handle = hooked_open( + || subclass(owner), + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { self.context = Some(Context { handle, hwnd: owner }); - subclass(owner); } } @@ -759,18 +790,25 @@ mod win { }); } - /// The wheel for a pointer message of a pen to `hwnd` at the message time `time`, with its - /// `eraser` end ([`Readings::wheel_at`]), opening the context first when none is open. - pub fn pen_wheel(hwnd: HWND, time: u32, eraser: bool) -> Option { + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { let api = api()?; STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); s.open_for(api, hwnd.0); - s.readings.wheel_at(time, eraser) + s.readings.wheel_for(time, pen, eraser) }) } + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + /// Start the readings afresh: the pen left the window or detection range, or a press was /// canceled. pub fn forget() { @@ -786,6 +824,15 @@ mod win { mod tests { use super::*; + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler /// when it has none, and the wider fields hold filler bytes. fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { @@ -976,37 +1023,117 @@ mod tests { #[test] fn the_drivers_notices_drop_or_reopen_the_context() { let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, info_changed: false }; + let reopen = Notice { closed: false, info_changed: true }; let mut n = Notices::default(); - assert_eq!(n.take(Some(ours)), Notice::Keep, "no notice"); + assert_eq!(n.take(Some(ours)), keep, "no notice"); n.note(Message::Closed { ctx: other }); - assert_eq!(n.take(Some(ours)), Notice::Keep, "another context closed"); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); n.note(Message::Closed { ctx: ours }); - assert_eq!(n.take(Some(ours)), Notice::Closed, "the driver closed it"); - assert_eq!(n.take(Some(ours)), Notice::Keep, "taken once"); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); n.note(Message::Closed { ctx: ours }); - assert_eq!(n.take(None), Notice::Keep, "nothing open"); + assert_eq!(n.take(None), keep, "nothing open"); assert_eq!(n, Notices::default(), "and the notice is gone"); n.note(Message::InfoChange); - assert_eq!(n.take(Some(ours)), Notice::Reopen); + assert_eq!(n.take(Some(ours)), reopen); n.note(Message::InfoChange); - assert_eq!(n.take(None), Notice::Reopen, "cursor ranges are read again even with nothing open"); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); // The reader closes its context, and the driver's notice of that arrives during the call; // a context opened next under the same handle value stays open. n.note(Message::Closed { ctx: ours }); n.closed_by_reader(ours); - assert_eq!(n.take(Some(ours)), Notice::Keep); + assert_eq!(n.take(Some(ours)), keep); for ctx in 0..20 { n.note(Message::Closed { ctx }); n.note(Message::Closed { ctx }); } assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); - assert_eq!(n.take(Some(19)), Notice::Closed, "the latest kept"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); n.note(Message::Packet { serial: 1, ctx: ours }); n.note(Message::Forget { ctx: ours }); n.note(Message::Other); assert_eq!(n, Notices::default(), "other messages are not notices"); } + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { closed: false, info_changed: true }, "another context's close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || None::), None, "an open that fails"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + #[test] fn wintab_messages_name_their_context() { assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); From 1157d8ab51e7b2be2d0c262f2dcd948b3ba902cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:36:33 -0800 Subject: [PATCH 18/84] Accessibility: the isolation bar's back arrow, crumbs and pattern buttons have screen-reader names The isolation bar drew its back arrow, the crumbs of the levels above and the pattern editing buttons as bare Tab stops with no name or role. Each is now a button. The back arrow is named for what it does: Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited. A crumb is named with the name it shows, and Save a Copy, Done and Cancel with their labels, all in the UI's language. The strings already have rows in every catalog. --- crates/ui-egui/src/chrome/tabs.rs | 28 +++++++++-- crates/ui-egui/src/chrome/tests.rs | 81 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 107 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..0410c2f71d 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -432,8 +432,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { // the levels above and the pattern buttons leaves isolation mode. let background = ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG); ui.painter().rect_filled(bar, 0.0, t.panel); + // The back arrow goes up one level: the isolated object's parent group, or `object.exitIsolation`, + // which goes from an isolated sublayer to its parent layer, from a group in a symbol's art to + // the symbol's layer, and otherwise leaves isolation mode. While a pattern is edited it is Done. + // Screen readers call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click()); + bresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), back_name)); icons::paint(ui, "chevron-left", back, if bresp.hovered() { t.text } else { t.icon }); let mut x = bar.left() + 30.0; @@ -449,6 +471,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if !is_leaf { let crumb_rect = egui::Rect::from_min_max(egui::pos2(x - 3.0, bar.top() + 3.0), egui::pos2(x + w + 3.0, bar.bottom() - 3.0)); let resp = ui.interact(crumb_rect, ui.scope_id().with(("iso-crumb", i)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &crumb.name)); if resp.hovered() { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } @@ -480,6 +503,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let w = 12.0 + 7.0 * label.len() as f32; let r = egui::Rect::from_min_max(egui::pos2(x - w, bar.top() + 3.0), egui::pos2(x, bar.bottom() - 3.0)); let resp = ui.interact(r, ui.scope_id().with(("pat-bar", cmd)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); ui.painter().rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.panel }); ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.button_border), egui::StrokeKind::Inside); ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), t.text); @@ -492,9 +516,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent group, or `object.exitIsolation`, which - // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. - nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + nav_cmd = Some(match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..00aabb241a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2264,6 +2264,87 @@ fn tab_skips_the_isolation_bars_background() { assert!(!stops.contains(&bar), "{stops:?}"); } +/// Screen readers call the isolation bar's back arrow by what it does, each crumb of the levels +/// above by the name it shows, and the pattern buttons by their labels, in the UI's language. The +/// current object's name is not a button. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let buttons = |app: &mut crate::VectorcraftApp| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::isolation_bar(app, ui, screen)); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let mut names: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + names.sort(); + names + }; + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + + // A path in a group: back goes to the group. + app.run("object.isolate", json!({"id": a})).unwrap(); + let mut want = vec!["Back One Level".to_string(), layer_name.clone(), group_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want, "the current object's name is not a button"); + + // The group itself: back leaves isolation mode. + app.run("object.isolate", json!({"id": group.0})).unwrap(); + let mut want = vec!["Exit Isolation Mode".to_string(), layer_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = app.run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + app.run("object.isolate", json!({"id": sub})).unwrap(); + let mut want = vec!["Back One Level".to_string(), layer_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want); + app.run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(buttons(&mut app), vec!["Exit Isolation Mode".to_string()]); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = buttons(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(german.contains(&"Isolationsmodus beenden".to_string()), "{german:?}"); + app.run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut app, 200.0); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + let names = buttons(&mut app); + for label in ["Save a Copy", "Cancel"] { + assert!(names.contains(&label.to_string()), "{label} in {names:?}"); + } + assert_eq!(names.iter().filter(|n| *n == "Done").count(), 2, "{names:?}"); + app.run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut app, 300.0); + app.run("select.set", json!({"ids": [d]})).unwrap(); + app.run("symbol.new", json!({"name": "Box"})).unwrap(); + app.run("symbol.edit", json!({"name": "Box"})).unwrap(); + let names = buttons(&mut app); + assert!(names.contains(&"Exit Symbol Editing Mode".to_string()), "{names:?}"); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..1ca8a95373 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1321,6 +1321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - Screen readers read the isolation bar's back arrow as a button named for what it does (Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited), each crumb of the levels above as a button with the name it shows, and Save a Copy, Done and Cancel by their labels, in the UI's language (`the_isolation_bars_controls_have_screen_reader_names`). - In isolation mode the Layers panel lists only the art of the isolated layer, sublayer or group, and lists the other layers and groups again when isolation mode ends ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=212)). As VectorCraft's own rules, the isolated layer, sublayer, group or object is the top row and opens on entering, the panel scrolls back to its row on leaving, search and filter look only inside it, nothing is dropped beside its row or into the empty space under the rows, Rename and Locate Object open no rows outside it, and rows highlighted outside it are no longer highlighted. With no row highlighted, Delete Selection and the trash do not delete a current layer outside it. New Layer, New Sublayer and Duplicate (in the panel menu and a row's context menu) are off, and OK in New Layer Options is an error, while the layer or copy they make would be outside it (`isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again`, `isolation_opens_the_isolated_row_and_keeps_drops_inside_it`, `isolation_drops_highlights_outside_the_isolated_art`, `isolation_keeps_rename_and_locate_to_the_rows_listed`, `isolation_keeps_delete_to_the_rows_listed`, `isolation_keeps_new_layers_to_the_rows_listed`, `new_layer_options_ok_checks_isolation_again`). - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). From 0c20ddaa02410484feb809633c5c80329d58b98c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:55:53 -0800 Subject: [PATCH 19/84] Windows: the Wintab wheel retries a failed open, sees the pen leave and closes while another app is active - An open that leaves no context (a failed `WTInfoW` or `WTOpenW`, or a window procedure that could not be put in front) is tried again for the same window by a pen message 2 s or more later (`RETRY_MS`), instead of only after the pen moves to another window. An open context is kept as before. - Windows sends `WM_POINTERLEAVE` to the window procedure, so winit's message hook does not see it. A `WH_CALLWNDPROC` hook on the UI thread now hands a sent `WM_POINTERENTER` or `WM_POINTERLEAVE` to the stylus code, and the wheel pen's leaving starts the readings afresh. A leave that comes while the readings are in use takes effect at the next Wintab or pen message. Until the hook is installed no context opens. - The context closes when another app becomes the active one (`WM_ACTIVATEAPP`, seen through the same hook), and no pen message opens one while the foreground window belongs to another thread, so the context does not stay in front of another app's context in the driver's overlap order. --- apps/vectorcraft/src/windows_stylus.rs | 36 +++ apps/vectorcraft/src/windows_wintab.rs | 309 +++++++++++++++++++++---- 2 files changed, 299 insertions(+), 46 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index a5d9b86271..bb05debce3 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -177,6 +177,25 @@ fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { } } +/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook +/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and +/// `WM_POINTERLEAVE` are sent +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen) +} + +/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on +/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as +/// [`msg_hook`] does for the messages it sees. +#[cfg(windows)] +pub fn sent_message(message: u32, wparam: usize) { + if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } +} + /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, /// not from a pen or a touch. fn is_mouse(extra_info: u32) -> bool { @@ -511,6 +530,23 @@ mod tests { assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); } + #[test] + fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let pen = Some(7); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window"); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel"); + assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window"); + // Posted messages, which the message hook already sees. + for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}"); + } + // WT_CTXCLOSE. + assert!(!sent_forgets_wheel(0x7FF2, 7, pen)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index ba4c784049..81a3f8efb2 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -41,7 +41,12 @@ //! to the window procedure, where a sent message does not pass winit's message hook, so the //! context's window gets a window procedure in front of its own that notes them ([`Notices`]). //! When that procedure cannot be put in front, no context is opened for the window -//! ([`hooked_open`]). A packet that `WTPacket` cannot read starts the readings afresh +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh //! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed //! (`TPS_QUEUE_ERR`, [`Readings::packet`]). #![cfg_attr(not(windows), allow(dead_code))] @@ -366,26 +371,43 @@ enum Current { Close, } -/// The context step for a pen message to a window owned by `owner`: what happens to the open -/// context, whose window is `current` with whether that window still exists, and whether a context -/// is opened for `owner`. The context follows the window the pen draws in. An open is tried once -/// for a window until another window is tried or the driver closes or changes the context -/// (`tried`). -fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usize) -> (Current, bool) { +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { let step = match current { Some((_, false)) => Current::Drop, Some((w, true)) if w == owner => return (Current::Keep, false), Some(_) => Current::Close, None => Current::Keep, }; - (step, tried != Some(owner) || step != Current::Keep) + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS } /// At most this many contexts' closing notices wait for [`Notices::take`]. const MAX_NOTICES: usize = 8; -/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`) since they were last -/// taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver /// call of its own, so they are noted here and acted on at the next Wintab or pen message. #[derive(Clone, Debug, Default, PartialEq)] struct Notices { @@ -393,6 +415,10 @@ struct Notices { closed: Vec, /// The driver's information changed. info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, } /// What the driver's notices do to the open context. Both can come in one batch. @@ -404,10 +430,15 @@ struct Notice { /// The driver's information changed: close it if it is still open, forget each cursor's wheel /// range, and open a context again at the next pen message. info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, } impl Notices { - /// Notes `message` if it is a closing or information-change notice. + /// Notes `message` if it is a closing, information-change or deactivation notice. fn note(&mut self, message: Message) { match message { Message::Closed { ctx } if !self.closed.contains(&ctx) => { @@ -417,6 +448,7 @@ impl Notices { self.closed.push(ctx); } Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, _ => {} } } @@ -427,16 +459,27 @@ impl Notices { self.closed.retain(|&c| c != ctx); } + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + /// Takes the notices: what they do to the open context `current`. fn take(&mut self, current: Option) -> Notice { let notices = std::mem::take(self); - Notice { closed: current.is_some_and(|c| notices.closed.contains(&c)), info_changed: notices.info_changed } + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } } } /// Opens a context with `open` only when `hook` put the window procedure that notes the driver's -/// notices in front of the window's own; otherwise opens none, and the window is not tried again -/// until another window is ([`next_context`]). +/// notices in front of the window's own; otherwise opens none, and the window is tried again as +/// [`next_context`] says. fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { if hook() { open() } else { None } } @@ -459,13 +502,21 @@ enum Message { }, /// The driver's information changed: the context closes and opens again. InfoChange, + /// Another app became the active one: the context closes. + Deactivated, Other, } +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + /// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` /// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. fn message(message: u32, wparam: usize, lparam: isize) -> Message { match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, WT_PROXIMITY => Message::Forget { ctx: wparam }, @@ -487,16 +538,18 @@ mod win { use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; use windows::Win32::UI::WindowsAndMessaging::{ - CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetPropW, GetWindowLongPtrW, IsWindow, MSG, RemovePropW, SetPropW, - SetWindowLongPtrW, WM_NCDESTROY, WNDPROC, + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, }; use windows::core::{PCWSTR, s, w}; use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, hooked_open, message, next_context, wheel_axis, + configure, decode, device_of, hooked_open, message, next_context, retry_due, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -526,8 +579,9 @@ mod win { #[derive(Default)] struct State { context: Option, - /// The window an open was last tried for ([`next_context`]). - tried: Option<*mut c_void>, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, /// Each cursor's wheel range, as the driver reported it. cursors: Vec<(u32, Option)>, readings: Readings, @@ -545,7 +599,7 @@ mod win { /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. fn note(what: Message) { - if !matches!(what, Message::Closed { .. } | Message::InfoChange) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { return; } NOTICES.with(|n| { @@ -578,6 +632,79 @@ mod win { unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } } + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns /// whether it is there. The window's property holds the procedure it replaced, and goes with the /// window. @@ -702,15 +829,24 @@ mod win { self.tried = None; self.cursors.clear(); } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } } - /// Moves the context to the window that owns `hwnd` ([`next_context`]). - fn open_for(&mut self, api: Api, hwnd: *mut c_void) { + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; let owner = if owner.is_null() { hwnd } else { owner }; let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); - let (step, open) = next_context(current, self.tried.map(|w| w as usize), owner as usize); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = next_context(current, tried, owner as usize, time, is_active()); match step { Current::Keep => {} Current::Drop => { @@ -722,7 +858,7 @@ mod win { if !open { return; } - self.tried = Some(owner); + self.tried = Some((owner, time)); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); let handle = hooked_open( @@ -785,22 +921,29 @@ mod win { s.readings.forget(); } } - Message::Closed { .. } | Message::InfoChange | Message::Other => {} + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} } }); + settle(); } /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when - /// none is open. + /// none is open. The first call installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { let api = api()?; - STATE.with(|s| { + if !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); - s.open_for(api, hwnd.0); + s.open_for(api, hwnd.0, time); s.readings.wheel_for(time, pen, eraser) - }) + }); + settle(); + wheel } /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer @@ -810,12 +953,16 @@ mod win { } /// Start the readings afresh: the pen left the window or detection range, or a press was - /// canceled. + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). pub fn forget() { - STATE.with(|s| { - if let Ok(mut s) = s.try_borrow_mut() { - s.readings.forget(); - } + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), }); } } @@ -996,17 +1143,73 @@ mod tests { assert_eq!(r.wheel_at(9000, false), Some(0.3)); } + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + #[test] fn the_context_follows_the_window_the_pen_draws_in() { let (main, doc) = (0x10, 0x20); - assert_eq!(next_context(None, None, main), (Current::Keep, true), "the first pen message opens it"); - assert_eq!(next_context(Some((main, true)), Some(main), main), (Current::Keep, false), "the same window keeps it"); - assert_eq!(next_context(Some((main, true)), Some(main), doc), (Current::Close, true), "another document window"); - assert_eq!(next_context(Some((doc, true)), Some(doc), main), (Current::Close, true), "and back"); - assert_eq!(next_context(Some((main, false)), Some(main), doc), (Current::Drop, true), "a window that is gone"); - assert_eq!(next_context(Some((main, false)), Some(main), main), (Current::Drop, true), "its handle reused"); - assert_eq!(next_context(None, Some(main), main), (Current::Keep, false), "an open that failed is not tried again"); - assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); } #[test] @@ -1024,8 +1227,8 @@ mod tests { fn the_drivers_notices_drop_or_reopen_the_context() { let (ours, other) = (0x5000, 0x6000); let keep = Notice::default(); - let closed = Notice { closed: true, info_changed: false }; - let reopen = Notice { closed: false, info_changed: true }; + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; let mut n = Notices::default(); assert_eq!(n.take(Some(ours)), keep, "no notice"); n.note(Message::Closed { ctx: other }); @@ -1060,7 +1263,7 @@ mod tests { #[test] fn a_close_and_an_information_change_in_one_batch_both_count() { let ours = 0x5000; - let both = Notice { closed: true, info_changed: true }; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; let mut n = Notices::default(); n.note(Message::Closed { ctx: ours }); n.note(Message::InfoChange); @@ -1070,7 +1273,21 @@ mod tests { assert_eq!(n.take(Some(ours)), both, "in either order"); n.note(Message::Closed { ctx: 0x6000 }); n.note(Message::InfoChange); - assert_eq!(n.take(Some(ours)), Notice { closed: false, info_changed: true }, "another context's close"); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); } #[test] From 38595ca3fd0ded35aa816b06677ae61990db4f9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:52:26 -0800 Subject: [PATCH 20/84] Font menu: the Document filter test holds other tests' font changes back the_document_filter_lists_the_families_the_documents_type_uses lists every family, turns the Document filter on and off, and expects the same list again. A composite font that a test running alongside registers in the process-wide font database in between shows up at the top of the second list, and the test fails. The test now holds test_fonts::steady_fonts on the global database from before its first listing, so those changes wait until it ends. --- crates/ui-egui/src/font_menu/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index e6dbdcca4e..930417a808 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1176,6 +1176,9 @@ fn the_document_filter_lists_the_families_the_documents_type_uses() { app.run("object.lock", serde_json::json!({})).unwrap(); app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap(); let db = vectorcraft_text::FontDb::global(); + // Tests running alongside register composite fonts and load fonts in the process-wide database; + // their changes wait until this test ends, so both listings of every family are the same. + let _steady = vectorcraft_text::test_fonts::steady_fonts(db); let used = super::document_families(db, &app.session.active().unwrap().doc); let mut names: Vec<_> = used.iter().cloned().collect(); names.sort(); From 86eed6b47dd963d2f83669c04f9db063d73e89e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:41:21 -0800 Subject: [PATCH 21/84] Selection: a selected linked image is crossed from corner to corner A selected linked image or placed document now shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. An image is outlined along its frame, so a turned or distorted image's outline follows its corners. The lines are selection marks: View > Hide Edges hides them, the hover highlight does not draw them, and output is unchanged. The overlay's point limit counts their ends where they are drawn. Fixes #9080 --- crates/ui-egui/src/canvas/outline.rs | 70 ++++++++++++++++--- crates/ui-egui/src/canvas/overlays.rs | 4 +- crates/ui-egui/src/canvas/panes.rs | 8 ++- crates/ui-egui/src/canvas/panes/tests.rs | 28 +++++++- crates/ui-egui/src/canvas/selection_marks.rs | 4 +- .../src/canvas/selection_marks/tests.rs | 68 ++++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 26 +++++++ docs/target-app-parity.md | 1 + 8 files changed, 194 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index c2ab7945be..33e9553c2c 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -39,8 +39,8 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip +/// Outline of a node for highlighting (paths, compound children, area type frames, other text +/// bounds, images' frames, symbol instances' bounds measured by their art from `symbols`; a clip /// group's clipping path only, as [`walk_drawn`] visits it). pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { let mut bp = BezPath::new(); @@ -62,7 +62,13 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { + // An image shows its frame, turned or distorted with it. + NodeKind::Image(_) => { + if let Some(frame) = c.image_frame() { + bp.extend(frame); + } + } + NodeKind::SymbolInstance { .. } => { if let Some(b) = c.geometric_bounds_with(symbols) { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } @@ -87,6 +93,41 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The corners (top left, top right, bottom right, bottom left) of a linked image's frame or of a +/// placed document's box. `None` for an embedded image and for anything else. +fn linked_corners(n: &Node) -> Option<[Point; 4]> { + match &n.kind { + NodeKind::Image(_) if is_linked(n) => n.image_corners(), + NodeKind::PlacedDocument(p) => Some(p.corners()), + _ => None, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080). The selection marks draw them; the hover +/// highlight does not. +pub(super) fn linked_crosses(n: &Node) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, &mut |c| { + if let Some([tl, tr, br, bl]) = linked_corners(c) { + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + }); + bp +} + /// The width of the key object's outline (Align to Key Object), thicker than the selection's. pub(super) const KEY_OUTLINE: f32 = 2.5; @@ -100,19 +141,32 @@ pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; /// counting stops there). pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { + over_limit(nodes, false) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator) -> bool { + over_limit(nodes, true) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`); counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..9d5808e249 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -6,7 +6,7 @@ use egui::epaint::{TessellationOptions, Tessellator}; use super::artboards::names_an_artboard; use super::input::marquee_through; -use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors}; +use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors, too_many_marks}; use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; @@ -161,7 +161,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: }; let st = app.session.active(); let show_marks = !crate::dialogs::halftone::previewing(app); - let big = show_marks && st.is_some_and(|st| too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); + let big = show_marks && st.is_some_and(|st| too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); let big_bounds = if big { app.selection_bounds() } else { None }; let app = &*app; let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 63d89f2be2..69c6940c25 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::sync::Arc; use super::grid::LineLook; -use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; +use super::outline::{c32, linked_crosses, node_outline, to_screen_path, too_many_marks}; use super::view::fit_zoom; use super::{ Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, @@ -639,7 +639,7 @@ fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec Vec Vec Vec [bool; 4] { + let picture = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)); + let drawn = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + picture.pixels[y * picture.size.0 + x][3] > 0.0 + }) + }) + }; + let [tl, tr, br, bl] = corners; + assert!([(tl, tr), (tr, br), (br, bl), (bl, tl)].into_iter().all(|(a, b)| drawn(a.midpoint(b))), "the outline runs along the frame"); + [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].map(drawn) + }; + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + app.run("select.all", json!({})).unwrap(); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a linked image"); + assert_eq!(crossed(&app, corners(&app, document)), [true; 4], "a placed document"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "an embedded image"); + assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "linked and embedded images"); + app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a turned linked image, along its frame"); + let doc = &app.session.active().unwrap().doc; + let [tl, tr, br, bl] = corners(&app, linked); + let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); + let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); + let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); + // Halfway between the middle of the left side and the centre: clear of both diagonals. + let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); + assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); + let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; + assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); +} + /// A frame of the whole canvas keeps entries for the selected objects only. #[test] fn the_canvas_drops_entries_it_does_not_draw() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..d5238029d7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -776,6 +776,32 @@ fn a_clip_group_over_a_huge_path_shows_its_clipping_path() { assert_eq!((anchors, hovered), (4, true), "the square's four anchors, and the hover highlight"); } +/// The selection marks count the ends of the lines that cross linked images toward the overlay's +/// limit; the hover highlight and the key object's outline, which draw no such lines, do not +/// (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(vectorcraft_doc::NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + assert!(!too_many_anchors(&linked) && too_many_marks(&linked), "linked images"); + assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); +} + /// #2422: the art inside a clip group still shows its whole outline when it is picked on its /// own: by Edit Contents, by a Direct Selection or Group Selection click, and in isolation mode; /// so does its Group Selection hover highlight. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..dd61b03ce9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,6 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a turned one, a placed document, an embedded image and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From d4ca49b7c6bac597597a6f3b3b26dd25e5e89ace Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:13:41 -0800 Subject: [PATCH 22/84] Tests: linked image crosses on distorted images, key, hover, Hide Edges The selection marks test now also checks a distorted linked image and a turned or distorted embedded image, the key object's outline alone and the hover highlight, each along the image's frame and without lines across it. A new test checks that the first canvas frame after View > Hide Edges draws nothing in the layer's color for a selected linked image. The render check comment uses American spelling. --- .../src/canvas/selection_marks/tests.rs | 70 +++++++++++++++---- crates/ui-egui/src/canvas/tests.rs | 41 +++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 97 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index a0ea0f7328..b0fcbc5658 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -586,8 +586,8 @@ fn an_edit_of_a_symbol_outlines_its_instance_again() { } /// A selected linked image and a selected placed document are crossed from corner to corner, on a -/// turned image along its frame; a selected embedded image shows its outline alone, and output of -/// the linked image shows no cross (#9080). +/// turned or distorted image along its frame; a selected embedded image shows its outline alone, +/// along its frame when turned or distorted. A render of the document is not crossed (#9080). #[test] fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; @@ -608,10 +608,9 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { let document = place(&mut app, &placed, true, [200.0, 230.0]); let ctx = egui::Context::default(); let view = xf(1.0, VIEW, 0.0); - // Whether the marks draw within a pixel of each of the points a quarter and three quarters of + // Whether `picture` draws within a pixel of each of the points a quarter and three quarters of // the way along each diagonal of `corners`, clear of the outline. - let crossed = |app: &VectorcraftApp, corners: [Point; 4]| -> [bool; 4] { - let picture = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)); + let crossed_in = |picture: &Picture, corners: [Point; 4]| -> [bool; 4] { let drawn = |q: Point| { let s = view.to_screen(q); (-1..=1).any(|dy| { @@ -625,6 +624,10 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { assert!([(tl, tr), (tr, br), (br, bl), (bl, tl)].into_iter().all(|(a, b)| drawn(a.midpoint(b))), "the outline runs along the frame"); [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].map(drawn) }; + // The same for the selection marks. + let crossed = |app: &VectorcraftApp, corners: [Point; 4]| { + crossed_in(&picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)), corners) + }; let corners = |app: &VectorcraftApp, id: NodeId| { let n = app.session.active().unwrap().doc.node(id).unwrap(); match &n.kind { @@ -637,19 +640,56 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { assert_eq!(crossed(&app, corners(&app, document)), [true; 4], "a placed document"); assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "an embedded image"); assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "linked and embedded images"); - app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); app.run("object.rotate", json!({"angle": 30})).unwrap(); assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a turned linked image, along its frame"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "a turned embedded image, outlined along its frame"); + { + let doc = &app.session.active().unwrap().doc; + let [tl, tr, br, bl] = corners(&app, linked); + let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); + let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); + let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); + // Halfway between the middle of the left side and the center: clear of both diagonals. + let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); + assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); + let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; + assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); + } + // Move each image's bottom right corner up its right side, so its corners no longer make a + // parallelogram and one diagonal turns away from where it ran. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); let doc = &app.session.active().unwrap().doc; - let [tl, tr, br, bl] = corners(&app, linked); - let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); - let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); - let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); - // Halfway between the middle of the left side and the centre: clear of both diagonals. - let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); - assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); - let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; - assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a distorted linked image, corner to corner"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "a distorted embedded image, outlined along its frame"); + // The key object's outline alone, with no other selection marks. + for id in [linked, embedded] { + let st = app.session.active_mut().unwrap(); + st.selection.objects.clear(); + st.selection.key = Some(id); + let key = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), &app, p, &view, false)); + assert_eq!(crossed_in(&key, corners(&app, id)), [false; 4], "the key object's outline of a distorted image, {id:?}"); + } + // The hover highlight outlines a linked image along its frame and does not cross it. + app.run("select.set", json!({"ids": []})).unwrap(); + for id in [linked, embedded] { + let [tl, tr, br, bl] = corners(&app, id); + app.hover_doc = Some(tl.midpoint(tr).midpoint(bl.midpoint(br))); + let hovered = picture(&ctx, 1.0, |p| super::super::overlays::hover_highlight(&app, p, &view)); + assert_eq!(crossed_in(&hovered, [tl, tr, br, bl]), [false; 4], "the hover highlight of a distorted image, {id:?}"); + } } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5238029d7..e80d331bdb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -802,6 +802,47 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); } +/// View › Hide Edges hides the lines across a selected linked image along with its outline +/// (#9080). +#[test] +fn hide_edges_hides_the_lines_across_a_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let dir = vectorcraft_testkit::temp_dir("hide-edges-linked"); + let png = dir.join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut place = + |link: bool, at: [f64; 2]| app.run("file.place", json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap(); + let (linked, embedded) = (place(true, [100.0, 120.0]), place(false, [250.0, 120.0])); + let ctx = egui::Context::default(); + let select = |app: &mut VectorcraftApp, id: u64| { + app.run("select.set", json!({"ids": [id]})).unwrap(); + frame(app, &ctx, vec![]); + }; + // The vertices the next canvas frame draws in the layer color of `id`. + let marks = |app: &mut VectorcraftApp, id: u64| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + let mesh = |p: &egui::ClippedPrimitive| match &p.primitive { + egui::epaint::Primitive::Mesh(m) => m.vertices.iter().filter(|v| v.color == color).count(), + egui::epaint::Primitive::Callback(_) => 0, + }; + ctx.tessellate(out.shapes, out.pixels_per_point).iter().map(mesh).sum::() + }; + select(&mut app, embedded); + let shown_embedded = marks(&mut app, embedded); + select(&mut app, linked); + let shown_linked = marks(&mut app, linked); + assert!(shown_linked > shown_embedded, "the lines across the linked image draw: {shown_linked} > {shown_embedded}"); + // The linked image stays selected, and the first frame after edges are hidden is checked. + app.ui.view.edges = false; + assert_eq!(marks(&mut app, linked), 0, "with edges hidden, a selected linked image draws nothing in its layer's color"); +} + /// #2422: the art inside a clip group still shows its whole outline when it is picked on its /// own: by Edit Contents, by a Direct Selection or Group Selection click, and in isolation mode; /// so does its Group Selection hover highlight. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dd61b03ce9..d15f17cd5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a turned one, a placed document, an embedded image and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From e79aa9836a7d86657ed6d66a05b5ad449fde71ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:45:22 -0800 Subject: [PATCH 23/84] Docs: linked image crosses above the outline point limit The progress-doc entry now says that above the 100,000-point overlay limit, counting 4 points for each linked image's or placed document's lines, both the current pane and other panes draw one rectangle around the selection instead of outlines and crossing lines. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d15f17cd5c..d6006c9e7e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 4f6e1515b46f52a71b7e2b79fe1b709bf2e0ebef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:16:18 -0800 Subject: [PATCH 24/84] Selection: a selected group leaves its hidden members unmarked The selection marks walked every member of a selected group or layer, so a hidden member, and the art inside a hidden group or a hidden sublayer, showed its outline, its anchors and the lines across a linked image, although the canvas does not draw hidden objects. The walk now skips hidden members, so the selection marks, the hover highlight and the outlines in other panes leave them out, and the overlay point limit no longer counts their points. The same holds for the members of a blend, a repeat and an intertwine. A compound path keeps every path, since it draws all of them, and an Image Trace object keeps its hidden source image in the views that show it. A hidden object that is itself selected keeps its marks. --- crates/doc/src/node/ops.rs | 3 +- crates/ui-egui/src/canvas/outline.rs | 24 +++++- .../src/canvas/selection_marks/tests.rs | 64 ++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 84 ++++++++++++++++++- docs/target-app-parity.md | 1 + 5 files changed, 170 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..42bece8844 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -361,7 +361,8 @@ impl Node { } /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. The canvas's selection + /// highlights also leave out hidden members, except a compound path's paths. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); let trace_source = self.extras().trace.is_some() diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 33e9553c2c..fbb2241f3d 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use super::{BezPath, Color32, Node, NodeKind, PathEl, Point, Pos2, Shape, Stroke, SymbolBoxes, VectorcraftApp, Xf, pos2}; pub(super) fn to_screen_path(bp: &BezPath, xf: &Xf) -> Vec> { @@ -163,7 +165,7 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b if n.clips() { return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && drawn_children(n).any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; nodes.into_iter().any(|n| over(n, &mut left, crosses)) @@ -193,9 +195,23 @@ fn overlay_points(n: &Node) -> usize { } } +/// The children of `n` that [`walk_drawn`] visits: [`Node::editing_children`], without the hidden +/// members, which the canvas does not draw. An Image Trace object's hidden source image stays when +/// the object's view shows it. Every path of a compound path stays, since the compound path draws +/// all of them. +fn drawn_children(n: &Node) -> impl Iterator> { + let members = !matches!(n.kind, NodeKind::Compound { .. }); + let source = (n.extras().trace.is_some() && n.trace_view().shows_source()) + .then(|| n.children().and_then(|children| children.first())) + .flatten() + .filter(|c| matches!(c.kind, NodeKind::Image(_))); + n.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) +} + /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members are left out +/// ([`drawn_children`]). pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { @@ -207,7 +223,7 @@ pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } return; } - for c in n.editing_children().iter() { + for c in drawn_children(n) { walk_drawn(c, f); } } diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index b0fcbc5658..32459a5825 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -692,6 +692,70 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { } } +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member +/// and the members of a hidden group inside it leave no outline, anchors or crossing lines. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let dir = vectorcraft_testkit::temp_dir("selection-marks-hidden"); + let png = dir.join("red.png"); + let pixels = [200u8, 40, 40, 255].repeat(40 * 40); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, pixels).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = NodeId(app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap()); + app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + app.session + .edit("Hide", |doc, _| { + for id in [hidden, inner] { + if let Some(n) = doc.node_mut(id) { + n.visible = false; + } + } + Ok(()) + }) + .unwrap(); + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let ctx = egui::Context::default(); + let view = xf(1.0, VIEW, 0.0); + let marks = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), &app, p, &view, false)); + // Whether the marks draw within a pixel of document point `q`. + let drawn = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + marks.pixels[y * marks.size.0 + x][3] > 0.0 + }) + }) + }; + let doc = &app.session.active().unwrap().doc; + let sides = |id: NodeId| { + let b = doc.node(id).unwrap().geometric_bounds().unwrap(); + [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] + }; + for id in [left, right] { + let [tl, tr, br, bl] = sides(id); + assert!([tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn), "a visible member is outlined and marked"); + } + let [tl, tr, br, bl] = doc.node(linked).unwrap().image_corners().unwrap(); + assert!( + ![tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn), + "the lines across a linked image in a hidden group" + ); + assert!(![tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn), "the outline of a linked image in a hidden group"); + let [tl, tr, br, bl] = sides(hidden); + assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); + assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); +} + /// A frame of the whole canvas keeps entries for the selected objects only. #[test] fn the_canvas_drops_entries_it_does_not_draw() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e80d331bdb..af4281cbbb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -802,6 +802,41 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); } +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of +/// a group, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{PathData, SubPath}; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let group = Node::group(NodeId(1), vec![Arc::new(member), few.clone()]); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&layer, "a layer")] { + assert_eq!(too_many_anchors([n]), visible, "{what}, member visible: {visible}"); + assert_eq!(too_many_marks([n]), visible, "{what}, member visible: {visible}"); + } + } +} + /// View › Hide Edges hides the lines across a selected linked image along with its outline /// (#9080). #[test] @@ -13466,8 +13501,55 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { }; assert_eq!(node_outline(&group, &symbols).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), "{view:?}"); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, an intertwine and a layer leave out a hidden member, and a layer the art +/// of a hidden sublayer. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::FillRule; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// Hovering over point type shows only its baseline (not the transform bounding box), while diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d6006c9e7e..446f395823 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,6 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group, layer, blend or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From b232fd8e96e4b1f7423510f55a7f76102377649d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 18:48:21 -0800 Subject: [PATCH 25/84] Tests: hidden members in a repeat, a clip group, hover and other panes The tests now cover the repeat, whose hidden source members are not outlined, a clip group, whose clipping path stays outlined whether or not it is hidden, a hidden object that is itself selected, the hover highlight of a group with hidden members and another pane's outlines of one. The overlay limit test reports the group and the layer case separately. The comment on editing_children is back to main's text, and the progress line lists the repeat and the new tests. --- crates/doc/src/node/ops.rs | 3 +- crates/ui-egui/src/canvas/panes/tests.rs | 30 +++++++++++++++++++ .../src/canvas/selection_marks/tests.rs | 25 ++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 28 ++++++++++++++--- docs/target-app-parity.md | 2 +- 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 42bece8844..20dae6ec4b 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -361,8 +361,7 @@ impl Node { } /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. The canvas's selection - /// highlights also leave out hidden members, except a compound path's paths. + /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); let trace_source = self.extras().trace.is_some() diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index b0f68367cc..5d664096b0 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -968,6 +968,36 @@ fn other_panes_cross_a_selected_linked_image() { assert_eq!(linked, embedded + 2, "the outline of a linked image and its two crossing lines; an embedded image's outline alone"); } +/// Another pane outlines a selected group's visible members only: hiding a member draws the same +/// outlines as deleting it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + let shown = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); + let hidden = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); + in_first(&mut app, "select.set", json!({"ids": [shown, hidden]})); + let group = in_first(&mut app, "object.group", json!({}))["id"].clone(); + let outlines = |app: &mut VectorcraftApp| { + in_first(app, "select.set", json!({"ids": [group]})); + frame(app, &ctx, vec![]); + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn).to_vec() + }; + let both = outlines(&mut app); + in_first(&mut app, "select.set", json!({"ids": [hidden]})); + in_first(&mut app, "edit.clear", json!({})); + let without = outlines(&mut app); + in_first(&mut app, "edit.undo", json!({})); + in_first(&mut app, "select.set", json!({"ids": [hidden]})); + in_first(&mut app, "object.hide", json!({})); + let with_hidden = outlines(&mut app); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 32459a5825..408b7c8ec0 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -754,6 +754,31 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let [tl, tr, br, bl] = sides(hidden); assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); + // The hover highlight of the group outlines its visible members only. + let (left_sides, right_sides, hidden_sides, image) = + (sides(left), sides(right), sides(hidden), doc.node(linked).unwrap().image_corners().unwrap()); + app.run("select.set", json!({"ids": []})).unwrap(); + app.hover_doc = Some(left_sides[0].midpoint(left_sides[2])); + let hovered = picture(&ctx, 1.0, |p| super::super::overlays::hover_highlight(&app, p, &view)); + let lit = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + hovered.pixels[y * hovered.size.0 + x][3] > 0.0 + }) + }) + }; + for [tl, tr, br, bl] in [left_sides, right_sides] { + assert!([tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit), "the hover highlight outlines a visible member"); + } + let [tl, tr, br, bl] = hidden_sides; + assert!(![tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit), "the hover highlight of a hidden member"); + let [tl, tr, br, bl] = image; + assert!( + ![tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit), + "the hover highlight of a linked image in a hidden group" + ); } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index af4281cbbb..3e7d629b75 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -817,6 +817,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default(), )); + let mut wrong = vec![]; for visible in [true, false] { let mut member = (*many).clone(); member.visible = visible; @@ -831,10 +832,12 @@ fn the_overlay_limit_leaves_out_hidden_members() { children.extend([Arc::new(sublayer), few.clone()]); } for (n, what) in [(&group, "a group"), (&layer, "a layer")] { - assert_eq!(too_many_anchors([n]), visible, "{what}, member visible: {visible}"); - assert_eq!(too_many_marks([n]), visible, "{what}, member visible: {visible}"); + if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } } } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); } /// View › Hide Edges hides the lines across a selected linked image along with its outline @@ -13517,8 +13520,9 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { } /// A compound path draws every path it holds, hidden ones included, so its highlight outlines them -/// all; a group, a blend, an intertwine and a layer leave out a hidden member, and a layer the art -/// of a hidden sublayer. +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. #[test] fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { use std::sync::Arc; @@ -13539,6 +13543,22 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + let repeat = |source: Vec>| contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(source, 0.0, 0.0)))); + let visible = children().into_iter().take(1).collect(); + assert_eq!(repeat(children()), repeat(visible), "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); sublayer.visible = false; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 446f395823..af0e9a73d6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,7 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. -- **Selection: hidden members are not marked:** a selected group, layer, blend or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group, layer, blend, repeat or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 1612f363c5b565debd606dd392cffa9de97f85b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 19:21:52 -0800 Subject: [PATCH 26/84] Selection: the hidden-member rule sits next to editing_children The rule for which children a selection highlight outlines moves from the canvas into Node::drawn_children in vectorcraft-doc, next to Node::editing_children. Both now read the Image Trace source image through one private helper, and editing_children's doc comment says it gives the editing bounds and that highlights outline drawn_children. The highlight's behavior is unchanged. - the_overlay_limit_leaves_out_hidden_members also covers a blend, a repeat and an intertwine. - The repeat case of the compound-path test asserts its contour count. - a_selected_group_leaves_its_hidden_members_unmarked reports every failed check together, so the hover highlight checks run even when an earlier check fails. - The docs line now states which marks are tested for blends, repeats and intertwines, and that the rectangle drawn above the point limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. --- crates/doc/src/node/ops.rs | 25 ++++++++++--- crates/ui-egui/src/canvas/outline.rs | 21 ++--------- .../src/canvas/selection_marks/tests.rs | 37 ++++++++++++------- crates/ui-egui/src/canvas/tests.rs | 15 +++++--- docs/target-app-parity.md | 2 +- 5 files changed, 57 insertions(+), 43 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..aaa45c0c6f 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -360,17 +360,32 @@ impl Node { self.geometric(Some(symbols)) } - /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for + /// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline + /// [`Node::drawn_children`]. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); - let trace_source = self.extras().trace.is_some() - && !self.trace_view().shows_source() - && children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_))); + let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible); let skip = usize::from(self.extras().shaper.is_some() || trace_source); children.get(skip..).unwrap_or_default() } + /// The children a selection highlight outlines: [`Node::editing_children`] without the hidden + /// members, which the canvas does not draw. An Image Trace object's hidden source image stays + /// when the object's view shows it, and every path of a compound path stays, since the compound + /// path draws all of them. + pub fn drawn_children(&self) -> impl Iterator> { + let members = !matches!(self.kind, NodeKind::Compound { .. }); + let source = self.trace_source().filter(|_| self.trace_view().shows_source()); + self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) + } + + /// The first child of an Image Trace object when it is an image: the bitmap the trace keeps. + fn trace_source(&self) -> Option<&Arc> { + self.extras().trace.as_ref()?; + self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_))) + } + /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` /// is given. pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index fbb2241f3d..e96cf2abcc 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use super::{BezPath, Color32, Node, NodeKind, PathEl, Point, Pos2, Shape, Stroke, SymbolBoxes, VectorcraftApp, Xf, pos2}; pub(super) fn to_screen_path(bp: &BezPath, xf: &Xf) -> Vec> { @@ -165,7 +163,7 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b if n.clips() { return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && drawn_children(n).any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; nodes.into_iter().any(|n| over(n, &mut left, crosses)) @@ -195,23 +193,10 @@ fn overlay_points(n: &Node) -> usize { } } -/// The children of `n` that [`walk_drawn`] visits: [`Node::editing_children`], without the hidden -/// members, which the canvas does not draw. An Image Trace object's hidden source image stays when -/// the object's view shows it. Every path of a compound path stays, since the compound path draws -/// all of them. -fn drawn_children(n: &Node) -> impl Iterator> { - let members = !matches!(n.kind, NodeKind::Compound { .. }); - let source = (n.extras().trace.is_some() && n.trace_view().shows_source()) - .then(|| n.children().and_then(|children| children.first())) - .flatten() - .filter(|c| matches!(c.kind, NodeKind::Image(_))); - n.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) -} - /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the /// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, /// its first child, not the art the path clips (#2422), and hidden members are left out -/// ([`drawn_children`]). +/// ([`Node::drawn_children`]). pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { @@ -223,7 +208,7 @@ pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } return; } - for c in drawn_children(n) { + for c in n.drawn_children() { walk_drawn(c, f); } } diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 408b7c8ec0..171a0a2df7 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -741,18 +741,25 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let b = doc.node(id).unwrap().geometric_bounds().unwrap(); [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] }; + // Every check runs, and the failures are reported together. + let mut wrong = vec![]; for id in [left, right] { let [tl, tr, br, bl] = sides(id); - assert!([tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn), "a visible member is outlined and marked"); + if ![tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn) { + wrong.push("a visible member is not outlined and marked"); + } } let [tl, tr, br, bl] = doc.node(linked).unwrap().image_corners().unwrap(); - assert!( - ![tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn), - "the lines across a linked image in a hidden group" - ); - assert!(![tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn), "the outline of a linked image in a hidden group"); + if [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn) { + wrong.push("the lines across a linked image in a hidden group"); + } + if [tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn) { + wrong.push("the outline of a linked image in a hidden group"); + } let [tl, tr, br, bl] = sides(hidden); - assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); + if [tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn) { + wrong.push("a hidden member"); + } assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); // The hover highlight of the group outlines its visible members only. let (left_sides, right_sides, hidden_sides, image) = @@ -770,15 +777,19 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { }) }; for [tl, tr, br, bl] in [left_sides, right_sides] { - assert!([tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit), "the hover highlight outlines a visible member"); + if ![tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit) { + wrong.push("the hover highlight does not outline a visible member"); + } } let [tl, tr, br, bl] = hidden_sides; - assert!(![tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit), "the hover highlight of a hidden member"); + if [tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit) { + wrong.push("the hover highlight of a hidden member"); + } let [tl, tr, br, bl] = image; - assert!( - ![tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit), - "the hover highlight of a linked image in a hidden group" - ); + if [tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit) { + wrong.push("the hover highlight of a linked image in a hidden group"); + } + assert!(wrong.is_empty(), "drawn where it should not be, or missing: {wrong:?}"); } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3e7d629b75..e4dd0af97c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -803,7 +803,8 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { } /// The overlay's limit counts the points of the members the highlight outlines: a hidden member of -/// a group, and the art of a hidden sublayer, do not count toward it. +/// a group, a blend, a repeat or an intertwine, and the art of a hidden sublayer, do not count +/// toward it. #[test] fn the_overlay_limit_leaves_out_hidden_members() { use super::outline::{too_many_anchors, too_many_marks}; @@ -821,7 +822,11 @@ fn the_overlay_limit_leaves_out_hidden_members() { for visible in [true, false] { let mut member = (*many).clone(); member.visible = visible; - let group = Node::group(NodeId(1), vec![Arc::new(member), few.clone()]); + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); sublayer.visible = visible; if let Some(children) = sublayer.children_mut() { @@ -831,7 +836,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { if let Some(children) = layer.children_mut() { children.extend([Arc::new(sublayer), few.clone()]); } - for (n, what) in [(&group, "a group"), (&layer, "a layer")] { + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { wrong.push(format!("{what}, member visible: {visible}")); } @@ -13543,9 +13548,7 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); - let repeat = |source: Vec>| contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(source, 0.0, 0.0)))); - let visible = children().into_iter().take(1).collect(); - assert_eq!(repeat(children()), repeat(visible), "a repeat"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); // A clip group shows its clipping path, hidden or not, and none of the art it clips. let clip = |visible: bool| { let mut members = children(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af0e9a73d6..43c7fc1cb9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,7 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. -- **Selection: hidden members are not marked:** a selected group, layer, blend, repeat or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 270f7cb654e8d6d9905506e5897f3f43f4654fd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 20:50:22 -0800 Subject: [PATCH 27/84] Docs: the key object's rectangle above the outline point limit The current pane draws a thicker rectangle around the key object instead of its outline when the key object alone has more than 100,000 outline points. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 43c7fc1cb9..685ab5dc4b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline, or a thicker rectangle around the key object when it alone has more than 100,000 outline points. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. - **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. From 2dece75952cde7debc82c85b86556369483d018e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 05:24:02 -0800 Subject: [PATCH 28/84] Windows: a pen reads only the airbrush whose wheel it read first Once a pen has read an airbrush cursor's wheel, a recent packet of another tablet's airbrush no longer gives that pen its wheel. The pen reads the other cursor only after the readings start afresh. --- apps/vectorcraft/src/windows_wintab.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 81a3f8efb2..c49bcbea7f 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -270,6 +270,9 @@ struct Readings { /// The pointer id of the pen whose message first read the wheel since the readings started /// afresh; another pen's messages read none. pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, } impl Readings { @@ -317,6 +320,7 @@ impl Readings { self.list.clear(); self.eraser = None; self.pen = None; + self.cursor = None; } /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took @@ -331,7 +335,8 @@ impl Readings { /// readings, the one cursor read since they started afresh, however long ago its last packet /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then. A turn to the other end starts them afresh first. + /// read a wheel first since then, or the pen read another cursor's wheel since then. A turn to + /// the other end starts them afresh first. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; @@ -351,11 +356,12 @@ impl Readings { r } }; - if !r.moved { + if !r.moved || self.cursor.is_some_and(|c| c != r.cursor) { return None; } let wheel = r.axis?.wheel(r.raw)?; self.pen = Some(pen); + self.cursor = Some(r.cursor); Some(wheel) } } @@ -1106,6 +1112,21 @@ mod tests { assert_eq!(r.wheel_at(500, false), None, "a value past the range"); } + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), None, "the other cursor's wheel"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + #[test] fn zero_is_no_wheel_until_the_pen_reports_another_value() { let mut r = Readings::default(); @@ -1136,6 +1157,7 @@ mod tests { r.forget(); r.packet(packet(1, 300), AXIS, 150); assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); for c in 0..10 { r.packet(packet(c, 300), AXIS, 1000 * c); } From fdca4a75f53a564c56ef8bc72cc47fb7995d4614 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:39:25 -0800 Subject: [PATCH 29/84] Live Corners: scrubbing the Properties panel's Corner Radius updates the corners as it moves The field applies each value of the gesture through an undo scope, as the Corners pop-up's Radius field does, so a scrub is one undo step. --- .../src/panels/properties/transform_section.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/transform_section.rs b/crates/ui-egui/src/panels/properties/transform_section.rs index 97d0e14942..86189395b7 100644 --- a/crates/ui-egui/src/panels/properties/transform_section.rs +++ b/crates/ui-egui/src/panels/properties/transform_section.rs @@ -18,6 +18,7 @@ use serde_json::json; use vectorcraft_doc::{LiveCorners, LiveShape, NodeKind}; use crate::VectorcraftApp; +use crate::edits::{EditPath, apply_edits}; use crate::panels::{self, first_selected, transform}; /// The Transform section for the selection: its position and size about the reference point, the @@ -112,17 +113,21 @@ pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { panels::set_picked_corners(app, &picked, json!({"kind": kind})); } let lengths = crate::canvas::general_lengths(app); - let mut typed = None; + let mut edit = None; Field::new(tl!("Corner Radius")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - typed = - NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit.events.committed().copied().flatten(); + edit = Some(NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit); panels::corners_link(app, ui); }); }); - // A negative radius typed in rounds nothing: the command takes 0 or more. - if let Some(r) = typed { - panels::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + if let Some(edit) = edit { + // Every value of a scrub sets the corners; the gesture is one undo step. + apply_edits(app, &edit, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + panels::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); } } From b081fd0e0d1e1c0447d8a68f883e7aad9968623f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:23:34 -0800 Subject: [PATCH 30/84] Live Corners: the Corner Radius fields show a relative radius as a length A live rectangle or polygon with Relative rounding showed the fraction it stores in its Corner Radius fields, while the Corners pop-up showed the length. The fields now show the length, which object.setLiveShape takes. --- crates/ui-egui/src/panels.rs | 22 ++++++++++++++----- crates/ui-egui/src/panels/properties/tests.rs | 16 ++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 890dc7443b..260e460bef 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -103,10 +103,22 @@ pub(crate) fn corner_radius(app: &VectorcraftApp, n: &Node) -> Option { corner_style(app, n).0 } -/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. +/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. The +/// radius is a document length ([`corner_length`]). pub(crate) fn corner_style(app: &VectorcraftApp, n: &Node) -> (Option, Option) { let partial = app.session.active().and_then(|d| d.selection.partial(n.id)); - LiveCorners::of(n).map_or((None, None), |c| c.style(&c.picked(partial))) + let Some(c) = LiveCorners::of(n) else { return (None, None) }; + let corners = c.picked(partial); + let mut radii = corners.iter().map(|k| corner_length(&c, *k)); + let radius = radii.next().filter(|first| radii.all(|r| (r - first).abs() < 1e-9)); + (radius, c.style(&corners).1) +} + +/// The radius asked for at corner `k`, as a document length, even where it draws smaller. A +/// relative radius is stored as a fraction of the corner's largest; the fields and +/// `object.setLiveShape` take lengths. +pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 { + if c.radii_relative() { c.radius(k) * c.corner(k).map_or(0.0, |c| c.max_radius()) } else { c.radius(k) } } /// One entry per corner kind, labelled as the Corners dialog labels them. @@ -214,7 +226,7 @@ fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { for (k, label, corner) in rectangle_corners() { Field::new(label).show(ui, |ui, _| { Row::new().wrap(true).show(ui, |ui, _| { - radii.push((k, NumberField::length(label, Bind::given(Some(lc.radius(k))), lengths).show(ui).edit)); + radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit)); if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) { kinds.push((k, kind)); } @@ -304,9 +316,7 @@ pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option { continue; } for &k in &corners { - // The radius asked for, even where it draws smaller. A relative radius is stored as a - // fraction of the corner's largest; the field and `object.setLiveShape` take lengths. - radii.push(if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }); + radii.push(corner_length(&lc, k)); kinds.push(lc.kind(k)); } relative.push(lc.radii_relative()); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 6eb2df684d..ea8e28b8bc 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1078,6 +1078,22 @@ fn a_whole_live_shape_with_direct_selection_shows_the_corners_link() { assert!(!panel.shows("Corner") && !panel.shows("Corners")); } +/// A live rectangle with Relative rounding shows its radius as a document length in its Corner +/// Radius field, as the Corners pop-up does, not as the fraction it stores. +#[test] +fn a_relative_live_rectangle_shows_its_radius_as_a_length() { + let mut app = new_app(); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "radius": 10})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "relativeRadii": true})).unwrap(); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); + let shown = crate::panels::corner_radius(&app, &n).unwrap(); + assert!((shown - 10.0).abs() < 1e-6, "the field shows {shown}"); + assert_eq!(crate::panels::picked_corners(&app).unwrap().radius.map(|r| (r - 10.0).abs() < 1e-6), Some(true), "as the pop-up does"); +} + /// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { let id = rect(app, x, 50.0, 100.0, 100.0); From 1c4df7b3432e83c6781655cc384d57c317a8a5cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:42:21 -0800 Subject: [PATCH 31/84] Rerun CI From 9860ca3d6ee7cfb899e14af342eb655821c69926 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:46:36 -0800 Subject: [PATCH 32/84] Docs: Curvature Circle overview names the configured snap reach The tool overview in docs/mcp.md said the pointer snaps within 5 screen points. It now names the tool's Snap Tolerance (5 by default) and the limit that Snap with Smart Guides Off sets while Smart Guides are off, as the options section below describes. --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index e7476d4332..6420f4d9e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7509,8 +7509,10 @@ marked smooth), when the circle would reach past the canvas (4,000,000 pt from t origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The -pointer snaps to the nearest path that is not a guide within 5 screen points, or within Smart Guides › Snapping -Tolerance when that is larger, and the tool shows the circle that matches the path there as a dashed outline (solid +pointer snaps to the nearest path that is not a guide within the tool's Snap Tolerance (`snapTolerance` below, 5 +screen points by default), or within Smart Guides › Snapping Tolerance when that is larger; with Snap with Smart +Guides Off turned off, the reach while Smart Guides are off is no more than Selection & Anchor Display › Tolerance. +The tool shows the circle that matches the path there as a dashed outline (solid once it is more than 50,000 screen points around), a small cross at its center, a line from the center to the point it touches and, with Measurement Labels on, its radius by the pointer, followed by an asterisk for an arc's own radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; From 7418753350ebbaa156412d6520fecfc3942d0d3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:53:19 -0800 Subject: [PATCH 33/84] Windows: the Wintab context opens only while the tool uses the wheel The Paintbrush with a brush whose Size or Width is on Stylus Wheel with a range the wheel can change, or the Eraser with a value on Stylus Wheel and a variation above 0, uses the wheel. The app asks the active tool (Tool::reads_wheel) once a frame and tells the host when the answer changes (Services::stylus_wheel). Until a tool uses the wheel, a pen message loads no Wintab32.dll, installs no hook, subclasses no window and opens no context; when it stops, the context closes. --- apps/vectorcraft/src/host_services.rs | 4 + apps/vectorcraft/src/windows_wintab.rs | 116 +++++++++++++++++++--- crates/engine/src/tooling.rs | 6 ++ crates/tools/src/draw2/gesture.rs | 5 + crates/tools/src/draw2/gesture/tests.rs | 19 ++++ crates/tools/src/lib.rs | 6 ++ crates/tools/src/symbolism.rs | 62 ++++++++++++ crates/ui-egui/src/app.rs | 5 + crates/ui-egui/src/canvas/tool_adapter.rs | 9 +- crates/ui-egui/src/services.rs | 3 + crates/ui-egui/src/stylus.rs | 62 ++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 13 files changed, 286 insertions(+), 17 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services { open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), + // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens + // only while the active tool uses the wheel. + #[cfg(all(windows, not(target_vendor = "win7")))] + stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)), ..Default::default() } } diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index c49bcbea7f..be43f918f2 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -8,9 +8,13 @@ //! Windows Ink comparison says the wheel comes only through Wintab //! (). //! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). //! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen -//! comes over a window. Without it, without one of its exports, or when a call fails, the pens -//! read no wheel and draw as before; the user sees no error. +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. //! - The context is opened from the driver's default context for the window that owns the pen's //! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor //! and makes no press. When the pen comes over another top-level window, such as a separate @@ -403,6 +407,35 @@ fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, own (step, active && (due || step != Current::Keep)) } +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + /// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or /// more later, on the message clock, which wraps. fn retry_due(at: u32, time: u32) -> bool { @@ -533,12 +566,12 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel, wheel_pen}; +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] mod win { - use std::cell::RefCell; + use std::cell::{Cell, RefCell}; use std::ffi::c_void; use std::sync::OnceLock; @@ -554,8 +587,8 @@ mod win { use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, hooked_open, message, next_context, retry_due, wheel_axis, + MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, Wheel, + calls_driver, configure, decode, device_of, hooked_open, message, next_context, retry_due, unused_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -598,6 +631,9 @@ mod win { /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends /// while [`STATE`] is borrowed for a driver call. static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; } /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. @@ -802,6 +838,11 @@ mod win { wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) } + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + fn is_window(hwnd: *mut c_void) -> bool { // SAFETY: `IsWindow` takes any handle value and reads no caller memory. unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() @@ -845,14 +886,18 @@ mod win { } /// Moves the context to the window that owns `hwnd`, for a pen message at the message time - /// `time` ([`next_context`]). - fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32) { + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; let owner = if owner.is_null() { hwnd } else { owner }; let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); let tried = self.tried.map(|(w, at)| (w as usize, at)); - let (step, open) = next_context(current, tried, owner as usize, time, is_active()); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; match step { Current::Keep => {} Current::Drop => { @@ -907,6 +952,9 @@ mod win { if what == Message::Other { return; } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } let Some(api) = api() else { return }; note(what); STATE.with(|s| { @@ -935,21 +983,51 @@ mod win { /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when - /// none is open. The first call installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is /// installed, no context opens and the pens read no wheel. pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } let api = api()?; - if !hook_thread(time) { + if used == Wheel::Used && !hook_thread(time) { return None; } let wheel = STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); - s.open_for(api, hwnd.0, time); + s.open_for(api, hwnd.0, time, used); s.readings.wheel_for(time, pen, eraser) }); settle(); - wheel + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); } /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer @@ -1220,6 +1298,18 @@ mod tests { assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); } + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + #[test] fn another_app_becoming_active_closes_the_context() { assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 446d441fc4..be665de83a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1060,6 +1060,12 @@ impl Session { self.tool.wants_samples() } + /// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel + /// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open. + pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.reads_wheel(cx)) + } + /// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input /// held until an edit it computes is applied, or are requests for the UI left from making it? pub fn tool_waiting(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 4f2fb7b463..67bb337774 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1861,6 +1861,11 @@ impl Tool for GestureTool { fn wants_samples(&self) -> bool { matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser") } + /// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel + /// with a Variation above 0. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + self.tip_modes().contains(&Variation::StylusWheel) + } /// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again /// after a zoom change, reach the whole drag over several frames. fn overlays_pending(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 24a0e1e5e6..b6d2dc1073 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4008,3 +4008,22 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); assert_eq!(last[1], Action::Commit); } + +#[test] +fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + for id in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults"); + } + for value in ["angle", "roundness", "size"] { + let mut t = GestureTool::new("eraser"); + t.set_option(&format!("{value}Mode"), &json!("stylusWheel")); + assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation"); + t.set_option(&format!("{value}Variation"), &json!(4)); + assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel"); + t.set_option(&format!("{value}Mode"), &json!("pressure")); + assert!(!t.reads_wheel(&cx), "{value} on Pressure"); + } +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 486de86876..0942322124 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -319,6 +319,12 @@ pub trait Tool: Send { fn wants_samples(&self) -> bool { false } + /// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip + /// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read + /// the wheel opens it only while this is so. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + false + } /// Is the tool waiting for work it runs on another thread (the planar map of a large selection /// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It /// highlights nothing under the pointer until a map is done. While this holds, the desktop app diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -438,6 +438,20 @@ impl Tool for BrushPaintTool { fn wants_samples(&self) -> bool { self.inner.wants_samples() } + /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus + /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values + /// differ, or an Art brush whose width is on it with two different widths. + fn reads_wheel(&self, cx: &ToolContext) -> bool { + use vectorcraft_brush::{BrushKind, Variation}; + let wheel = |mode: Variation| mode == Variation::StylusWheel; + let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false }; + match brush.kind { + BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), + BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), + BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, + BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + } + } fn busy(&self) -> bool { self.inner.busy() } @@ -758,4 +772,52 @@ mod tests { let a = drag(&d, &mut BrushPaintTool::default()); assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); } + + #[test] + fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + let wheel = Variation::StylusWheel; + let calligraphic = + |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); + let scatter = |size| { + BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) + }; + let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let library = [ + Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, + Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, + Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) }, + Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) }, + Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) }, + Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, + Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, + Brush { name: "Flat".into(), kind: art(None, 200.0) }, + ]; + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); + let (s, p) = (Selection::default(), paint()); + let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p)); + let mut t = BrushPaintTool::default(); + assert!(!reads(&d, &t), "no brush"); + let brushes = [ + ("Plain", false), + ("Nib", true), + ("Still nib", false), + ("Dots", true), + ("Even dots", false), + ("Taper", true), + ("Even taper", false), + ("Flat", false), + ("Deleted", false), + ]; + for (name, varies) in brushes { + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name)); + assert_eq!(reads(&d, &t), varies, "the current brush {name}"); + } + t.set_option("brush", &json!("Plain")); + assert!(!reads(&d, &t), "the tool's own brush comes first"); + t.set_option("brush", &json!("Nib")); + d.unknown.remove(vectorcraft_brush::CURRENT_KEY); + assert!(reads(&d, &t), "and reads the wheel"); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 299f4c22d5..3c08e487e2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -441,6 +441,11 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // With no document open too, so closing the last one stops the host reading the wheel. A + // held press, whose previews change the document each frame, keeps what it was told. + if self.canvas.grab.is_none() { + crate::stylus::sync_wheel_use(self); + } self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..5bda6d918e 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -577,8 +577,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 40d7ff903f..8e653d8dce 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -62,6 +62,9 @@ pub struct Services { /// The pen the host reads itself (tablet APIs the window system doesn't route): the same /// handle the host installs for the framework's pointer feed. pub pen: Option, + /// Told whether the active tool reads an airbrush pen's finger wheel (Windows: the host opens + /// the tablet driver's Wintab context only while it does). Without it nothing is told. + pub stylus_wheel: Option>, pub read: Option, /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one /// byte past the limit, so a larger file is refused without reading all of it. Without it, the diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index f92fc2f347..0491874822 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -22,6 +22,10 @@ use crate::VectorcraftApp; /// The tool the pen's eraser end selects. const ERASER: &str = "eraser"; +/// What decides whether the active tool reads an airbrush pen's finger wheel ([`sync_wheel_use`]): +/// the active document's uid and revision, its current brush, and the tool with its options. +type WheelKey = (Option<(u64, u64)>, Option, &'static str, serde_json::Value); + /// The end of the pen the canvas saw last, and the tool the eraser end stands in for /// ([`sync_eraser_tool`]). #[derive(Clone, Debug, Default)] @@ -30,6 +34,8 @@ pub(crate) struct PenEnd { end: Option, /// The tool that was active when the eraser end selected the Eraser. before: Option<&'static str>, + /// What the host was last told about the finger wheel, and for which state ([`sync_wheel_use`]). + wheel: Option<(WheelKey, bool)>, } impl PenEnd { @@ -79,6 +85,33 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { } } +/// Tells the host whether the active tool reads an airbrush pen's finger wheel +/// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or +/// the Eraser with a value on it. The host is told at the first call and then each time the answer +/// changes; the tool is asked again only when the document, its current brush, the tool or its +/// options change. +/// +/// [`VectorcraftApp::tick`] calls this once a frame, with no document open too, and the canvas +/// calls it again when the pen's end changes the tool ([`sync_eraser_tool`]). +pub(crate) fn sync_wheel_use(app: &mut VectorcraftApp) { + if app.services.stylus_wheel.is_none() { + return; + } + let st = app.session.active(); + let key = + (st.map(|s| (s.uid, s.revision)), st.and_then(|s| vectorcraft_brush::current(&s.doc)), app.session.tool_id(), app.session.tool_options()); + if app.pen_end.wheel.as_ref().is_some_and(|(k, _)| *k == key) { + return; + } + let used = app.session.tool_reads_wheel(app.view_info()); + let told = app.pen_end.wheel.replace((key, used)).map(|(_, u)| u); + if told != Some(used) + && let Some(tell) = app.services.stylus_wheel.as_mut() + { + tell(used); + } +} + #[cfg(test)] mod tests { use super::*; @@ -126,4 +159,33 @@ mod tests { assert!(!sync_eraser_tool(&mut app)); assert_eq!(app.session.tool_id(), "rectangle"); } + + #[test] + fn the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel() { + use serde_json::json; + let told = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tell = told.clone(); + app.services.stylus_wheel = Some(Box::new(move |used| tell.borrow_mut().push(used))); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("paintbrush"); + let frame = |app: &mut VectorcraftApp| { + sync_wheel_use(app); + told.borrow().clone() + }; + assert_eq!(frame(&mut app), [false], "told at the first frame"); + assert_eq!(frame(&mut app), [false], "and not again while nothing changes"); + app.session.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + assert_eq!(frame(&mut app), [false], "a brush without Stylus Wheel"); + let params = json!({"variation": [0, 0, 2], "modes": ["fixed", "fixed", "stylusWheel"]}); + app.session.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + assert_eq!(frame(&mut app), [false, true], "its size on Stylus Wheel"); + app.select_tool("rectangle"); + assert_eq!(frame(&mut app), [false, true, false], "another tool"); + app.select_tool(ERASER); + assert_eq!(frame(&mut app), [false, true, false], "the Eraser at its defaults"); + app.session.set_tool_option("sizeMode", &json!("stylusWheel")); + app.session.set_tool_option("sizeVariation", &json!(4)); + assert_eq!(frame(&mut app), [false, true, false, true], "its size on Stylus Wheel"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 754f36cec6..68bf1806b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4304,7 +4304,9 @@ already walks Image Trace. Short agent entry points: way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` - is installed; without it a Windows pen reads no wheel. The web build does not read it. `.ai` brush definitions read + is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Eraser with a + value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2d75b2e000..f256cdbec1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2109,7 +2109,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample` and `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From bd8e9002518fa35b9aa07936e5de33f32f44e56d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:15:43 -0800 Subject: [PATCH 34/84] Windows: the Blob Brush's Stylus Wheel size also opens the Wintab context The Blob Brush takes Stylus Wheel for its Size, and its tip already counts through Tool::reads_wheel. The test and the docs name it. --- crates/tools/src/draw2/gesture/tests.rs | 6 +++++- crates/ui-egui/src/stylus.rs | 2 +- docs/mcp.md | 6 +++--- docs/target-app-parity.md | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 5f4adbf4e2..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4131,7 +4131,7 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { } #[test] -fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { +fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() { let (d, _) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let cx = cx(&d, &s, &p); @@ -4147,4 +4147,8 @@ fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { t.set_option(&format!("{value}Mode"), &json!("pressure")); assert!(!t.reads_wheel(&cx), "{value} on Pressure"); } + let mut t = GestureTool::new("blobBrush"); + t.set_option("sizeMode", &json!("stylusWheel")); + t.set_option("sizeVariation", &json!(4)); + assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel"); } diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0491874822..dc3a9f5195 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -87,7 +87,7 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { /// Tells the host whether the active tool reads an airbrush pen's finger wheel /// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or -/// the Eraser with a value on it. The host is told at the first call and then each time the answer +/// the Blob Brush or the Eraser with a value on it. The host is told at the first call and then each time the answer /// changes; the tool is asked again only when the document, its current brush, the tool or its /// options change. /// diff --git a/docs/mcp.md b/docs/mcp.md index b8b06d9d8b..938dedf84d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4477,9 +4477,9 @@ already walks Image Trace. Short agent entry points: desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool - uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Eraser with a - value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps no wheel. The web build does not read it. `.ai` brush definitions read - and write the wheel as variation code 3. + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Blob Brush or + the Eraser with a value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps + no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5c06d423e8..d05c441153 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From 281cee4379b40aa86f37b451d259353754d37792 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:21:19 -0800 Subject: [PATCH 35/84] Live Corners: the Corners pop-up applies its radius after the Stack The pop-up's Radius edits are now collected inside the Stack and applied after it, as the kind and rounding radios already are. relativeRadii no longer turns a plain path into a Live Corners path here; that change goes to its own pull request. relativeRadii on a plain path, an ellipse or a line leaves it as it is and adds no undo step. --- crates/doc/src/corners.rs | 7 +++--- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 27 +++++------------------- crates/engine/src/tests/livecorners.rs | 25 +++++----------------- crates/ui-egui/src/panels.rs | 19 ++++++++++------- docs/mcp.md | 10 ++++----- docs/target-app-parity.md | 2 +- 7 files changed, 31 insertions(+), 61 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 3810bbb1f5..24228604a6 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -205,8 +205,8 @@ impl<'a> LiveCorners<'a> { /// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of /// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again. /// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a -/// plain path again once no corner is cut, unless its rounding is Relative. Ellipses and lines -/// have no corners: they stay as they are. +/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they +/// are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { fn edit( base: &PathData, @@ -268,8 +268,7 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, } match live.as_deref_mut() { - // A path with Relative rounding keeps its record, and with it the rounding. - Some(LiveShape::Path { base, radii, kinds, radii_relative: false }) if radii.is_empty() && kinds.is_empty() => { + Some(LiveShape::Path { base, radii, kinds, .. }) if radii.is_empty() && kinds.is_empty() => { *path = std::mem::take(base); *live = None; } diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 7a03abfb48..b675061f6b 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole path: a live rectangle, a live polygon or any path with a corner, which keeps its outline as the base of its Live Corners; a path without Live Corners is Absolute, and a path whose anchors are edited loses its Live Corners and is Absolute again; ellipses and lines are left as they are), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut, unless its rounding is Relative; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index 24274782d8..12a92b9193 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,15 +99,10 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } -/// Whether `relativeRadii` applies to a path drawn as `path` with live shape `live`: a live -/// rectangle, a live polygon, a path with Live Corners, or a plain path with a corner. A plain -/// path's rounding is Absolute. -fn takes_rounding(path: &PathData, live: Option<&LiveShape>) -> bool { - match live { - Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }) => true, - Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => false, - None => LiveCorners::new(path, None).is_some_and(|c| !c.all().is_empty()), - } +/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live +/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. +fn takes_rounding(live: Option<&LiveShape>) -> bool { + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) } /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about @@ -288,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| takes_rounding(path, live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { + if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -366,23 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *l = new.clone(); *path = l.to_path(); } - // A path with corners and no Live Corners yet keeps its outline as their base, so that - // Relative rounding has a record to go in. - if relative_radii == Some(true) && live.is_none() && takes_rounding(path, None) { - *live = Some(Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![], radii_relative: false })); - } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { convert_radii_relative(l, on); *path = l.to_path(); - // Absolute with no corner cut: a plain path again, as `set_corners` leaves one. - if let LiveShape::Path { radii, kinds, radii_relative: false, .. } = l - && radii.is_empty() - && kinds.is_empty() - { - *live = None; - } } if radius.is_none() && kind.is_none() { continue; diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 479c599124..4641467aa4 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,12 +910,10 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } -/// Relative rounding on a path with corners and no Live Corners yet takes effect in one undo step, -/// a radius set afterwards is stored as a fraction, and the rounding stays when no corner is cut -/// any more. Absolute, which such a path already has, and Relative on an ellipse, which has no -/// corners, add no undo step. +/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them +/// as they are and adds no undo step. #[test] -fn relative_rounding_takes_on_a_plain_path() { +fn relative_rounding_without_live_corners_adds_no_undo_step() { let (mut s, id) = session(); s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); s.execute("object.expandShape", &json!({})).unwrap(); @@ -923,22 +921,9 @@ fn relative_rounding_takes_on_a_plain_path() { let steps = |s: &Session| s.doc().unwrap().history.undo.len(); let n = steps(&s); run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); - assert_eq!(steps(&s), n, "Absolute: no change"); run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); - assert_eq!(steps(&s), n + 1, "Relative: one undo step"); - let node = s.doc().unwrap().doc.node(id).unwrap(); - assert!(LiveCorners::of(node).unwrap().radii_relative()); - let max = LiveCorners::of(node).unwrap().corner(0).unwrap().max_radius(); - run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": max / 2.0})); - let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); - assert!(c.radii_relative() && (c.radius(0) - 0.5).abs() < 1e-9, "stored fraction: {}", c.radius(0)); - // With no corner cut again, the path keeps its Relative rounding. - run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": 0})); - let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); - assert!(c.radii_relative() && c.radius(0) == 0.0, "still Relative"); - // Absolute again with no corner cut: a plain path again. - run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); - assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path again"); + assert_eq!(steps(&s), n, "a plain path: no change"); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path"); let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); let n = steps(&s); run(&mut s, json!({"ids": [e], "relativeRadii": true})); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 132925e362..fb19b8195a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -356,7 +356,7 @@ pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui) { fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(picked) = picked_corners(app) else { return }; let lengths = general_lengths(app); - let mut set = None; + let (mut set, mut radius) = (None, None); Stack::new().show(ui, |ui, _| { Field::new(tl!("Corner")).show(ui, |ui, _| { let group = RadioGroup::new(tl!("Corner"), Bind::given(picked.kind)).show(ui, |ui, _| { @@ -371,13 +371,7 @@ fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { } }); Field::new(tl!("Radius")).show(ui, |ui, _| { - let radius = NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit; - apply_edits(app, &radius, EditPath::Scope, |app, v: &Option, _| { - // A negative radius typed in rounds nothing: the command takes 0 or more. - if let Some(r) = v { - set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); - } - }); + radius = Some(NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit); }); let rounding = RadioGroup::new(tl!("Rounding"), Bind::given(picked.relative)).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { @@ -389,6 +383,15 @@ fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { set = Some(json!({"relativeRadii": on})); } }); + // Applied after the Stack, whose body runs twice (measure, then real), as the radios' `set`. + if let Some(radius) = radius { + apply_edits(app, &radius, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); + } if let Some(p) = set { set_picked_corners(app, &picked, p); } diff --git a/docs/mcp.md b/docs/mcp.md index 8b9fb31dd7..57044f4ccf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7989,8 +7989,8 @@ polygon's from its first vertex clockwise; a star's from its first tip; an index Each corner keeps its own radius and kind (the shape's `live` in queries has `radii` and, when a corner isn't round, `kinds`); a corner with no radius is one anchor, a cut one two, and Direct-Selected corners stay selected as that changes. A path that isn't a live shape keeps its uncut outline (`live` `{"shape": "path", "base", "radii"}`) so its -corners stay editable, and is a plain path again once no corner is cut, unless its rounding is Relative; a polygon -stays a live polygon, its corners keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius +corners stay editable, and is a plain path again once no corner is cut; a polygon stays a live polygon, its corners +keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform @@ -8018,9 +8018,9 @@ Direct Selection, while a corner is selected or one live rectangle or polygon is the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the -paths differ). A path without Live Corners is Absolute, and Relative on a path with a corner keeps its outline as the -base of its Live Corners, as a radius does; ellipses and lines are left as they are. Editing a path's anchors (for -example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. With Relative rounding, a radius is +paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no +undo step. Editing a path's anchors (for example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. +With Relative rounding, a radius is compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one `object.setLiveShape` with `items`, one undo step, and the corners that were not picked keep their radius and kind. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b99205fcb..733f42cb74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1525,7 +1525,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules. Relative rounding also works on a plain path with corners (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_takes_on_a_plain_path`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). + - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). From 16710bf8db44632ffa039dfc0ca11e5f205f30cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:59:48 -0800 Subject: [PATCH 36/84] Tests: the grid preview test draws through the shared frame helper drawn_preview now runs each frame with testing::part_frame_uploads instead of its own ctx.run_ui loop. part_frame_uploads is part_frame with the frame's texture uploads kept in the returned FullOutput; part_frame calls it and clears them as before, so its callers see no change. --- crates/ui-egui/src/dialogs/document_setup.rs | 22 ++++++++++++-------- crates/ui-egui/src/testing.rs | 16 ++++++++++++-- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 6d8b492104..4c9a6ae4c7 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -1117,20 +1117,24 @@ mod tests { assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")])); } - /// The grid preview the open dialog draws in `ctx`: its rect, the span of its texture + /// The grid preview the open dialog draws in `ctx`, in frames run as the hosts run them + /// ([`crate::testing::part_frame_uploads`]): its rect, the span of its texture /// coordinates (two cells per unit) and the four pixels of the texture it draws. `tiles` holds /// the pixels of each 2 × 2 texture uploaded so far in `ctx`, so every frame drawn in `ctx` /// goes through this function. The preview is the largest rect drawn with such a texture. fn drawn_preview( - app: &VectorcraftApp, + app: &mut VectorcraftApp, ctx: &egui::Context, tiles: &mut std::collections::HashMap>, ) -> (Rect, egui::Vec2, Vec) { let mut preview = None; for _ in 0..4 { let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; - let dialogs = app.dialogs().unwrap(); - let mut out = ctx.run_ui(raw, |ui| dialogs.with(|h| h.run(ui))); + let mut out = crate::testing::part_frame_uploads(app, ctx, raw, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| h.run(ui)); + } + }); for (id, deltas) in &out.textures_delta.set { if let Some(d) = deltas.last() { let egui::ImageData::Color(img) = &d.image; @@ -1166,19 +1170,19 @@ mod tests { /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. #[test] fn the_grid_preview_follows_edits_in_the_open_dialog() { - let (app, ctx) = setup_open(); + let (mut app, ctx) = setup_open(); let mut tiles = std::collections::HashMap::new(); set(&app, &ctx, "tab", json!("Transparency")); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); set(&app, &ctx, "gridColors", json!(["#ff0000", "#0000ff"])); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); set(&app, &ctx, "gridSize", json!("large")); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); set(&app, &ctx, "gridColors", json!("Dark")); - let (_, _, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (_, _, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); let st = app.session.active().unwrap(); assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index ac732ae644..a065c31ef8 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -48,6 +48,19 @@ pub(crate) fn app_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, ra /// [`app_frame`] with `draw` showing part of the window in place of the whole app. pub(crate) fn part_frame( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + raw: egui::RawInput, + draw: impl FnMut(&mut crate::VectorcraftApp, &mut egui::Ui), +) -> egui::FullOutput { + let mut out = part_frame_uploads(app, ctx, raw, draw); + out.textures_delta.clear(); + out +} + +/// [`part_frame`] with the frame's texture uploads kept in the output, for a test that reads them. The test clears +/// `textures_delta` once it has read it. +pub(crate) fn part_frame_uploads( app: &mut crate::VectorcraftApp, ctx: &egui::Context, mut raw: egui::RawInput, @@ -56,9 +69,8 @@ pub(crate) fn part_frame( app.adopt_context(ctx); app.raw_input(ctx, &mut raw); embed::before_input(ctx, |out| app.frame_input(out)); - let mut out = ctx.run_ui(raw, |ui| draw(app, ui)); + let out = ctx.run_ui(raw, |ui| draw(app, ui)); run_fired(app, ctx); - out.textures_delta.clear(); out } From 5ff353a23b32b89371e623018da8bd1cb2b61273 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:47:35 -0800 Subject: [PATCH 37/84] Windows: the Wintab reader keeps each pen's end and asks a failed cursor query again - Each pen's end is kept by its pointer id, so only the same pen turning over starts the readings afresh; another pen's message with the other end does not. - A cursor whose WTInfoW query failed is asked again 2 s of the message clock later, and only a cursor the driver describes without a wheel is cached as having none. - Whether the app is active is asked again right before WTOpenW, after the close and WTInfoW calls before it. - docs/target-app-parity.md: a pen first reads the wheel from a packet within 200 ms of its message, then holds the readings until they start afresh. --- apps/vectorcraft/src/windows_wintab.rs | 192 ++++++++++++++++++++----- docs/target-app-parity.md | 2 +- 2 files changed, 154 insertions(+), 40 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index be43f918f2..13fe249a06 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -153,6 +153,8 @@ const MAX_DEVICES: u32 = 16; const MAX_SKEW_MS: u32 = 200; /// At most this many cursors' readings are kept. const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; /// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, /// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on @@ -247,6 +249,52 @@ fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { found.next().is_none().then_some(d) } +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + /// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. fn near(a: u32, b: u32) -> bool { (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS @@ -269,8 +317,10 @@ struct Reading { #[derive(Clone, Debug, Default)] struct Readings { list: Vec, - /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. - eraser: Option, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, /// The pointer id of the pen whose message first read the wheel since the readings started /// afresh; another pen's messages read none. pen: Option, @@ -322,7 +372,7 @@ impl Readings { /// could not be read, the context's queue overflowed, or the context closed. fn forget(&mut self) { self.list.clear(); - self.eraser = None; + self.ends.clear(); self.pen = None; self.cursor = None; } @@ -339,16 +389,25 @@ impl Readings { /// readings, the one cursor read since they started afresh, however long ago its last packet /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then, or the pen read another cursor's wheel since then. A turn to - /// the other end starts them afresh first. + /// read a wheel first since then, or the pen read another cursor's wheel since then. The same + /// pen's turn to its other end starts them afresh first; another pen's message with another end + /// does not. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; } - if self.eraser.is_some_and(|e| e != eraser) { + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { self.forget(); } - self.eraser = Some(eraser); + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } let r = match self.list.as_slice() { [one] if self.pen == Some(pen) => one, list => { @@ -517,10 +576,11 @@ impl Notices { } /// Opens a context with `open` only when `hook` put the window procedure that notes the driver's -/// notices in front of the window's own; otherwise opens none, and the window is tried again as +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as /// [`next_context`] says. -fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { - if hook() { open() } else { None } +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } } /// What a message does to the readings and the context. @@ -586,9 +646,10 @@ mod win { use windows::core::{PCWSTR, s, w}; use super::{ - Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, Wheel, - calls_driver, configure, decode, device_of, hooked_open, message, next_context, retry_due, unused_context, wheel_axis, + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -621,8 +682,7 @@ mod win { /// The window an open was last tried for, and the message time it was tried at /// ([`next_context`]). tried: Option<(*mut c_void, u32)>, - /// Each cursor's wheel range, as the driver reported it. - cursors: Vec<(u32, Option)>, + cursors: Cursors, readings: Readings, } @@ -821,21 +881,27 @@ mod win { (wrote == N * 4).then_some(out) } - /// The wheel range of `cursor`, `None` for a cursor without one or one the driver does not - /// describe. - fn cursor_axis(api: Api, cursor: u32) -> Option { + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { if cursor >= MAX_INDEX { - return None; + return Ok(None); } - let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE)?; - let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA)?; - let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES)?; + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; let mut devices = vec![]; for d in 0..count.min(MAX_DEVICES) { - devices.push((info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR)?[0], info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES)?[0])); + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); } - let device = u32::try_from(device_of(cursor, &devices)?).ok()?; - wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) } /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. @@ -912,8 +978,10 @@ mod win { self.tried = Some((owner, time)); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. let handle = hooked_open( || subclass(owner), + is_active, || { // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for // the call. @@ -930,16 +998,8 @@ mod win { self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) } - fn axis(&mut self, api: Api, cursor: u32) -> Option { - if let Some(&(_, axis)) = self.cursors.iter().find(|(c, _)| *c == cursor) { - return axis; - } - let axis = cursor_axis(api, cursor); - if self.cursors.len() >= MAX_READINGS * 4 { - self.cursors.remove(0); - } - self.cursors.push((cursor, axis)); - axis + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) } } @@ -967,7 +1027,7 @@ mod win { // SAFETY: the handle is the open context's, and `buf` holds more bytes than a // packet of every field. let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; - let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor))); + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); s.readings.read(read, msg.time); } Message::Forget { ctx } => { @@ -1409,15 +1469,69 @@ mod tests { opens.set(opens.get() + 1); Some(7) }; - assert_eq!(hooked_open(|| true, open), Some(7)); + assert_eq!(hooked_open(|| true, || true, open), Some(7)); assert_eq!(opens.get(), 1); let open = || { opens.set(opens.get() + 1); Some(7) }; - assert_eq!(hooked_open(|| false, open), None, "no context without the procedure"); + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); assert_eq!(opens.get(), 1, "and the driver is not asked for one"); - assert_eq!(hooked_open(|| true, || None::), None, "an open that fails"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d05c441153..e8a7fa1579 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still and no packet has come for longer, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From 5668a3428eeff72936715e25c388fd82f4f981a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:05:33 -0800 Subject: [PATCH 38/84] Windows: a pen keeps its airbrush's wheel while another tablet's cursor is read The pen that took the Wintab readings now reads the latest packet of its own cursor whenever that cursor is still near the context, instead of only when it is the one cursor read. Another tablet's airbrush moving while the pen is held still no longer drops the pen's wheel. --- apps/vectorcraft/src/windows_wintab.rs | 40 ++++++++++++++------------ docs/target-app-parity.md | 2 +- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 13fe249a06..31da32a1ff 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -386,12 +386,11 @@ impl Readings { /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the - /// readings, the one cursor read since they started afresh, however long ago its last packet - /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, - /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then, or the pen read another cursor's wheel since then. The same - /// pen's turn to its other end starts them afresh first; another pen's message with another end - /// does not. + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; @@ -408,18 +407,18 @@ impl Readings { self.ends.push((pen, eraser)); } } - let r = match self.list.as_slice() { - [one] if self.pen == Some(pen) => one, - list => { - let mut near_time = list.iter().filter(|r| near(time, r.time)); - let r = near_time.next()?; - if near_time.next().is_some() { - return None; - } - r + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; } + r }; - if !r.moved || self.cursor.is_some_and(|c| c != r.cursor) { + if !r.moved { return None; } let wheel = r.axis?.wheel(r.raw)?; @@ -1237,12 +1236,13 @@ mod tests { assert_eq!(r.wheel_at(1010, false), Some(0.25)); assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); r.packet(packet(1, 1000), AXIS, u32::MAX - 5); r.packet(packet(2, 500), None, u32::MAX); assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); r.packet(packet(1, 1000), AXIS, 5000); assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); - assert_eq!(r.wheel_at(9000, false), None, "neither recent"); r.forget(); r.packet(packet(2, 500), None, 100); assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); @@ -1257,9 +1257,13 @@ mod tests { assert_eq!(r.wheel_at(1000, false), Some(0.25)); // Another tablet's airbrush moves while the pen is held still. r.packet(packet(2, 750), AXIS, 5000); - assert_eq!(r.wheel_at(5010, false), None, "the other cursor's wheel"); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); r.packet(packet(1, 500), AXIS, 6000); assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); r.forget(); r.packet(packet(2, 750), AXIS, 7000); assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e8a7fa1579..ac268ed3cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still and no packet has come for longer, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From eca0b0c0e1f56ad06200361be7a19878c2acad26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:38:29 -0800 Subject: [PATCH 39/84] Canvas: selection marks follow the pointer in the frame it moves The canvas drew the selection's outlines, anchors, handles and dots before the tool host took the frame's pointer event, so during a drag they showed where the art was one frame earlier. They are now drawn after the tool host and placed back at their old spot in the paint order through a PaintSlot, under the widgets and bars as before. Tests: a Selection tool drag draws its marks at the object's new corner and none at the old one; a Pen drag draws the handle end at the pointer of the same frame. --- crates/ui-egui/src/canvas.rs | 11 +++- crates/ui-egui/src/canvas/tests.rs | 93 ++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e0bc44b304..d2c137b3ce 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -8,6 +8,7 @@ use craft::ui::canvas::{ Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -261,7 +262,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// 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 { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; @@ -276,7 +278,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -313,6 +317,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..e2752d11d0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -166,6 +166,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] From 272c24a119759a7acc35c27201a9b0475f51c75d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:40:11 -0800 Subject: [PATCH 40/84] Selection: a selected group leaves out guides and templates the view hides A selected group or layer outlined and marked a member made into a guide while the guides were hidden, and the art of a template sublayer while View > Hide Template was on, although the canvas does not draw them. - Node::hidden_by_view (crates/doc/src/node/ops.rs) holds the rule; the renderer's left_out now uses it too. - walk_drawn and the overlay's point limit in canvas/outline.rs leave out the members the view hides, so the selection's outlines, key outline, anchors, hover outline and point count skip them. - The selection's bounds are unchanged. --- crates/doc/src/node/ops.rs | 7 ++ crates/render/src/node_checks.rs | 4 +- crates/ui-egui/src/canvas/outline.rs | 74 +++++++++------ crates/ui-egui/src/canvas/selection.rs | 41 ++++---- crates/ui-egui/src/canvas/selection/tests.rs | 98 ++++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 26 ++++-- 6 files changed, 188 insertions(+), 62 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index aaa45c0c6f..cadfb6b7a6 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -131,6 +131,13 @@ impl Node { matches!(self.kind, NodeKind::Layer { template: true, .. }) } + /// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this + /// object out: a template layer while templates are hidden, or a path made into a guide while + /// guides are hidden. The canvas draws ruler guides apart from the art. + pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool { + (templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. })) + } + /// The art objects of this container: its children, looking through sublayers, which are not /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, /// unlocked, non-template sublayers. diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool { /// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its /// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = a.is_ruler_guide() - || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 4e83b1197b..6ebda8e24a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,33 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// Whether the view leaves `n` out. + fn hides(self, n: &Node) -> bool { + n.hidden_by_view(self.templates, self.guides) + } +} + /// Outline of a node for highlighting (paths, compound children, area type frames, other text /// bounds, images' frames, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// group's clipping path only, as [`walk_drawn`] visits it, without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -72,11 +93,11 @@ fn is_linked(n: &Node) -> bool { } /// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, -/// from corner to corner of its frame or box (#9080). The selection marks draw them; the hover -/// highlight does not. -pub(super) fn linked_crosses(n: &Node) -> BezPath { +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Image(_) if is_linked(c) => { if let Some(cross) = c.image_cross() { bp.extend(cross); @@ -101,22 +122,23 @@ pub(super) fn linked_crosses(n: &Node) -> BezPath { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - over_limit(nodes, false) +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) } /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they -/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them. -pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator) -> bool { - over_limit(nodes, true) +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) } /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the -/// ends of the crossing lines when `crosses`); counting stops there. -fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> bool { - fn over(n: &Node, left: &mut usize, crosses: bool) -> bool { +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { let ends = if crosses && is_linked(n) { 4 } else { 0 }; match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, @@ -124,12 +146,12 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().filter(|c| !hides.hides(c)).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left, crosses)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -158,21 +180,21 @@ fn overlay_points(n: &Node) -> usize { /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the /// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, -/// its first child, not the art the path clips (#2422), and hidden members are left out -/// ([`Node::drawn_children`]). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.drawn_children() { - walk_drawn(c, f); + for c in n.drawn_children().filter(|c| !hides.hides(c)) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 55da766408..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline and cross: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -174,9 +174,9 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -189,7 +189,7 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; // Linked images and placed documents are also crossed from corner to corner. - for path in [node_outline(node, &symbols), linked_crosses(node)] { + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { if !path.elements().is_empty() { group(&mut out, color_of(*id)).paths.push(path); } @@ -200,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -268,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -279,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -371,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -407,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -497,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 0e8dd77e45..bef89f1f41 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -331,7 +331,11 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { let st = app.session.active().unwrap(); let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); - assert_eq!(outline_of(st, id).unwrap().path.elements(), frame_of(corners(&app, id)).as_slice(), "the hover outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); } } @@ -356,8 +360,9 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { let count = OVERLAY_MAX_ANCHORS / 6; let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; let embedded = vec![image(None); count]; - assert!(!too_many_anchors(&linked) && too_many_marks(&linked), "linked images"); - assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); } /// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image @@ -385,7 +390,7 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let st = app.session.active().unwrap(); let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); - let hovered = outline_of(st, group).map(|h| h.path.elements().to_vec()); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); (outlined, anchored, hovered) }; let both = shown(&mut app, &[]); @@ -396,6 +401,87 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { assert_eq!(with_hidden, without, "hidden members are not marked"); } +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); +} + /// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a /// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. #[test] @@ -430,7 +516,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { children.extend([Arc::new(sublayer), few.clone()]); } for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { - if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { wrong.push(format!("{what}, member visible: {visible}")); } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 00c503addb..801a5c401e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,7 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); } /// One headless canvas frame on an 800 × 600 window. @@ -4537,18 +4541,18 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); // A hidden path sent to the back of a trace is not its source image, in any view. let mut path = Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); @@ -4557,7 +4561,11 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), "{view:?}"); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); } } @@ -4580,7 +4588,7 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { }; let doc = vectorcraft_doc::Document::new(300.0, 300.0); let symbols = doc.symbol_boxes(); - let contours = |n: &Node| node_outline(n, &symbols).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); From 6d908ec05197c0aac0c32e9a524c147fc97fabe2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:41:37 -0800 Subject: [PATCH 41/84] Pathfinder: the Repeat row names the operation that ran last The Pathfinder panel menu's Repeat row read "Repeat Pathfinder" after every operation. The label for pathfinder.repeat now reads "Repeat Unite", "Repeat Minus Front" and so on from the last Shape Mode or Pathfinder operation, through the existing "Repeat {name}" template, and keeps "Repeat Pathfinder" before any has run. Every row of the command uses the same label. --- crates/ui-egui/src/menus/labels.rs | 14 ++++++++++++++ crates/ui-egui/src/panels/pathfinder.rs | 22 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index bce650899b..93e13ae22f 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -99,6 +99,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), None => label.into(), }, + // Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last. + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => format!("Repeat {name}"), + None => label.into(), + }, // Apply Last Filter and Last Filter… are named after the filter that ran last. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => format!("Apply {name}"), @@ -129,6 +134,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some(text) } +/// The Pathfinder panel's name for the Shape Mode or Pathfinder operation that ran last. +fn last_pathfinder_label(app: &VectorcraftApp) -> Option<&'static str> { + app.last_pathfinder.as_deref().and_then(crate::panels::pathfinder::operation_label) +} + /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a /// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never @@ -201,6 +211,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } None => crate::i18n::tr_id(lang, id, label).to_string(), }, + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => fmt(tl!("Repeat {name}"), &[("name", tl!(name))]), + None => crate::i18n::tr_id(lang, id, label).to_string(), + }, // The filter's name is the plug-in's own text, never translated. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => fmt(tl!("Apply {filter}"), &[("filter", &name)]), diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 8280c4c3d1..d1ee58262d 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -520,6 +520,28 @@ mod tests { assert!(p.app().run("pathfinder.repeat", json!({})).is_err()); } + /// The state the window's menus give the Repeat row, which the panel menu's row reads. + fn repeat_row(p: &Panel) -> Option { + crate::menus::model::refresh(&mut p.app(), p.ctx()); + p.app().menus.states.get(&CommandRef::new("pathfinder.repeat")).cloned() + } + + /// Before an operation has run, the Repeat row reads Repeat Pathfinder and is dimmed; after Unite + /// or Minus Front from the panel it names that operation. + #[test] + fn the_repeat_row_names_the_last_operation() { + let mut p = Panel::new(two_squares(), show); + let command = CommandRef::new("pathfinder.repeat"); + let off = crate::menus::model::off_reason(&p.app(), &command, "Repeat Pathfinder"); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(false).hint(off)), "the plain label, dimmed"); + p.click("Unite"); + select_two_squares(&mut p.app(), 110.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Unite"))); + p.click("Minus Front"); + select_two_squares(&mut p.app(), 210.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Minus Front"))); + } + /// One selected path cannot supply the operands for Unite; the command reports the failure. #[test] fn repeat_with_one_path_keeps_art_and_history() { From 7ece56ec6989a3be48c31df9252cd15367c6436f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:23:15 -0800 Subject: [PATCH 42/84] Packaging tests: use the shared panel harness --- crates/ui-egui/src/addons/packaging/tests.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index d71a98d334..8222b179d5 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_engine::Session; use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show}; use crate::i18n::LangExt as _; +use crate::tests::panel_harness::Panel; use crate::{VectorcraftApp, menus}; /// An app with two rectangles, nothing selected → (app, their ids). @@ -19,16 +20,6 @@ fn app() -> (VectorcraftApp, u64, u64) { (app, a, b) } -/// The values the panel's editable fields show, read from the access tree of its second frame. -fn field_values(app: &mut VectorcraftApp) -> Vec { - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)).textures_delta.clear(); - let out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); - let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - nodes.iter().filter(|(_, n)| n.supports_action(egui::accesskit::Action::SetValue)).filter_map(|(_, n)| n.value().map(str::to_string)).collect() -} - /// The count of each role the panel's rows show. fn counts(app: &mut VectorcraftApp) -> Vec<(String, u64)> { rows(app).into_iter().map(|row| (row.0, row.3)).collect() @@ -190,7 +181,9 @@ fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); let text = crate::tests_labels::painted_text(&mut app, show); assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}"); - let values = field_values(&mut app); + let panel = Panel::new(app, show); + let values = panel.values(); + let mut app = panel.app(); assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}"); let kept = read_rows(&mut app); assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1)); From 59ddb9c3e21c6f054af4928f3142d2089a64210d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:28:05 -0800 Subject: [PATCH 43/84] JavaScript: consume iterators in Promise combinators --- crates/js/src/builtins/promise.rs | 97 +++++++++++-------------------- crates/js/src/iteration.rs | 2 +- crates/js/src/promise_tests.rs | 73 +++++++++++++++++++++-- docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 111 insertions(+), 71 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..1fbbf9c334 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -18,9 +18,9 @@ //! 25.6.1.9); one that still has none when the run ends successfully is reported by //! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. //! -//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object -//! whose `length` is a whole number by index, and a string by code point; other values reject the -//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator +//! when processing a yielded value throws. Noniterable values reject the promise they return +//! with a `TypeError`. The statics need a constructor as `this`, and the //! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` //! are not read. @@ -32,7 +32,6 @@ use crate::LimitKind; use crate::bytecode::Code; use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::string_builtins::flat_charged; use crate::value::Value; /// Where a promise was rejected: the code and the instruction. @@ -1010,67 +1009,41 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe }) } -/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to -/// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. -enum Inputs { - Indexed { object: ObjId, length: f64 }, - CodePoints(Rc<[u16]>), -} - -impl Inputs { - fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { - match input { - Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { - Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { - Ok(Inputs::Indexed { object: *o, length }) - } - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - }, - Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - } - } - - /// The input at `index`, which counts code units for a string; `None` past the end. - fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { - match self { - Inputs::Indexed { object, length } => { - let end = match interp.heap.object(*object).map(|o| &o.class) { - Some(Class::Array { length, .. }) => f64::from(*length), - _ => *length, - }; - if *index >= end { - return Ok(None); - } - let v = super::get_at(interp, *object, *index)?; - *index += 1.0; - Ok(Some(v)) - } - Inputs::CodePoints(units) => { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let i = *index as usize; - let Some(&first) = units.get(i) else { return Ok(None) }; - let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); - let n = if pair { 2 } else { 1 }; - let piece = units.get(i..i + n).unwrap_or_default().to_vec(); - *index += n as f64; - let bytes = crate::heap::string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - Ok(Some(Value::String(crate::value::Str::from_units(piece)))) - } - } - } -} - fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { let resolve_fn = interp.get_value(this, &key("resolve"))?; if !interp.is_callable(&resolve_fn) { return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); } root(interp, &resolve_fn); - let inputs = Inputs::new(interp, input, how)?; + let iterator = interp.get_iterator(input)?; + root(interp, &Value::Object(iterator)); + let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject)); + if let Err(Abrupt::Throw(reason)) = &result { + root(interp, reason); + let site = interp.throw_site.clone(); + let mark = interp.thrown_mark; + match interp.iter_close(iterator) { + Ok(()) | Err(Abrupt::Throw(_)) => { + interp.throw_site = site; + interp.thrown_mark = mark; + interp.passing = reason.clone(); + } + Err(other) => return Err(other), + } + } + result +} + +fn combine_iterator( + interp: &mut Interp, + this: &Value, + iterator: ObjId, + how: Combine, + rec: ObjId, + resolve_fn: &Value, + handlers: (&Value, &Value), +) -> JsResult<()> { + let (resolve, reject) = handlers; let combinator = if how == Combine::Race { None } else { @@ -1080,14 +1053,12 @@ fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine root(interp, &Value::Object(c)); Some((c, values)) }; - let mut position = 0.0; let mut index: u32 = 0; loop { - interp.use_fuel()?; let mark = interp.temp_roots.len(); - let Some(next) = inputs.get(interp, &mut position)? else { break }; + let Some(next) = interp.iter_next(iterator)? else { break }; root(interp, &next); - let next_promise = interp.call(&resolve_fn, this, &[next])?; + let next_promise = interp.call(resolve_fn, this, &[next])?; root(interp, &next_promise); match combinator { None => { diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index 49a503f506..eac1d4abe6 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -162,7 +162,7 @@ impl Interp { /// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return` /// method, unless it is done, and checks that it gives an object. - fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { + pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { let r = self.record(rec)?; if r.done { return Ok(()); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..3d1d92769d 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -144,7 +144,73 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { } #[test] -fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { +fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() { + let src = "var input = {}; input[Symbol.iterator] = function () {\n\ + var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\ + };\n\ + Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\ + Promise.race(input).then(function (v) { log.push('race ' + v); });\n\ + var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\ + Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\ + Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });"; + let out = log(src); + for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] { + assert!(out.contains(expected), "{expected} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_close_after_resolve_or_then_throws() { + let src = "function check(name, failure) {\n\ + var closed = 0, input = {};\n\ + input[Symbol.iterator] = function () { return {\n\ + next: function () { return { value: 1, done: false }; },\n\ + return: function () { closed++; throw 'close'; }\n\ + }; };\n\ + Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\ + function () { return { get then() { throw 'then'; } }; };\n\ + Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\ + }\n\ + var original = Promise.resolve;\n\ + for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\ + Promise.resolve = original;"; + let out = log(src); + for name in ["all", "allSettled", "race"] { + for failure in ["resolve", "then"] { + let expected = format!("{name}:{failure}:{failure}:1"); + assert!(out.contains(&expected), "{expected} in {out}"); + } + } +} + +#[test] +fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() { + let src = "var closed = 0;\n\ + function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\ + next: function () { if (failure === 'next') throw failure;\n\ + return { get done() { if (failure === 'done') throw failure; return false; },\n\ + get value() { throw failure; } }; },\n\ + return: function () { closed++; return {}; }\n\ + }; }; return o; }\n\ + for (var i = 0; i < 3; i++) {\n\ + Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\ + }\n\ + var empty = {}; empty[Symbol.iterator] = function () { return {\n\ + next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\ + }; };\n\ + Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\ + Promise.race(empty).then(function () { log.push('race settled'); });\n\ + log.push('closed ' + closed);"; + let out = log(src); + for expected in ["next", "done", "value", "empty 0", "closed 0"] { + assert!(out.contains(expected), "{expected} in {out}"); + } + assert!(!out.contains("race settled"), "{out}"); +} + +#[test] +fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() { // `Promise.resolve` runs once for each input and appends to the input while it is read. let src = "var resolve = Promise.resolve; var input;\n\ Promise.resolve = function (x) {\n\ @@ -152,11 +218,10 @@ fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_t return resolve.call(this, x);\n\ };\n\ input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ - input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });"; + input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });"; let out = log(src); assert!(out.contains("array 1,2,3"), "{out}"); - assert!(out.contains("object 1"), "{out}"); - assert!(!out.contains("object 1,"), "{out}"); + assert!(out.contains("object true"), "{out}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..b2be537836 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2887,8 +2887,12 @@ own rules: stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. -- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one - item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the +- `all`, `allSettled` and `race` read their input through `Symbol.iterator`, including user-defined iterables and + overridden array iterators. In a kept engine with no `Symbol.iterator`, they walk arrays, `arguments` objects and + strings. String iterators keep surrogate pairs together. A noniterable object, including one + with only a `length`, rejects the promise they return with a `TypeError`. When processing a yielded value throws, + the combinator calls the iterator's `return` method if present; the original exception remains the rejection reason + even when `return` throws. An iterator whose step threw or finished is not closed. The promises `then` and the statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. - A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043ae5c403..80bac7dabe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1107,7 +1107,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. From dcc688915d3b2bad694a347297f07e9218d96ae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:29:03 -0800 Subject: [PATCH 44/84] Graphic Styles: restore the New and Delete Alt-click hints --- crates/ui-egui/src/panels/graphic_styles.rs | 25 +++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..a1f3dabb97 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -485,9 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .popup(PopupKind::Menu) .pressed(library_panel::any_open::(&app.ui)), FooterAction::new(svg("link-2-off"), tl!("Break Link to Graphic Style")).enabled(linked), - FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style")).enabled(!sel.is_empty()).takes_drops_disabled(true).accepts_drops(ours), + FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style (Alt-click: without asking)")) + .enabled(!sel.is_empty()) + .takes_drops_disabled(true) + .accepts_drops(ours), // A style dropped here is duplicated with or without art selected. - FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style")) + FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style (Alt-click to name it)")) .enabled(selection_len(app) > 0) .takes_drops_disabled(true) .accepts_drops(ours), @@ -1430,4 +1433,22 @@ mod tests { 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:?}"); } + + /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete + /// deletes without asking. + #[test] + fn the_new_and_delete_buttons_name_their_alt_click() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let mut panel = Panel::new(app(), show); + panel.click_with("New Graphic Style (Alt-click to name it)", Modifiers::ALT); + assert!(open_dialog(&panel.app(), graphic_style_options::KIND).is_some(), "Alt-click on New asks for a name"); + let mut app = app(); + app.session.execute("graphicStyle.new", &json!({"name": "Mine"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click("Mine"); + panel.click_with("Delete Graphic Style (Alt-click: without asking)", Modifiers::ALT); + let app = panel.app(); + assert!(!names(&app).iter().any(|s| s == "Mine") && confirm::open_question(&app).is_none(), "Alt-click on Delete deletes at once"); + } } From e26efcb1659b661d5e3648dc7951608bf3fb3f3c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:36:14 -0800 Subject: [PATCH 45/84] Kinsoku Shori Sets: show None when the set list is empty --- crates/ui-egui/src/dialogs/kinsoku_sets.rs | 5 +++-- crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 1aac4c28b8..6eb690989d 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -361,10 +361,11 @@ impl KinsokuDialog { let rows: Vec> = list.iter().map(|s| PresetRow::item(name_of(s).to_owned(), name_of(s), 0)).collect(); let mut value = list.get(self.index(list.len())).map(|s| name_of(s).to_owned()); let suggestion = new_name(&list, &self.opened); - // PLAN: PresetPicker has no placeholder: an empty list shows an empty name field, not "None". let source = PresetSource::listed(&rows); let refuses = |typed: &str| name_problem(&list, typed); - let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)).field(PickerField::Name); + let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)) + .field(PickerField::Name) + .placeholder(tl!("None")); let out = NamedPresetRow::new(tl!("Kinsoku Set"), picker).suggest_name(suggestion).check_name(NameCheck::of_host(&refuses)).show(ui); self.apply(out.events); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index f39cf6d596..887dbbc202 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,21 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn empty_kinsoku_list_shows_none_in_the_preset_picker() { + let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fixture.room(egui::vec2(800.0, 600.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut app).unwrap(); + fixture.settle(); + + let picker = fixture.by_label("Kinsoku Set").expect("Kinsoku Set picker"); + assert_eq!(fixture.tree().value_of(picker.node), Some("None")); + assert!(picked(&app).is_empty(), "the caption does not select a set"); +} + /// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its /// categories edited in their fields and Add putting in a character by its code point; nothing /// changes until OK, which sets them as one undo step; Cancel leaves them. From 75fd52fca639e3d85918be6adcc4b560f199ac82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:40:33 -0800 Subject: [PATCH 46/84] Scripts: keep nested apply operands alive during collection --- crates/js/src/interp.rs | 5 ++++- crates/js/src/interp_tests.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c2b707e3c6..6a57041cfe 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2830,9 +2830,12 @@ impl Interp { return Err(self.type_error("apply was called on a value that is not a function")); } let list = args.get(1).cloned().unwrap_or(Value::Undefined); + let mut roots = vec![f.clone(), this.clone()]; + roots.extend(args.iter().cloned()); + let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?; f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = expanded; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..a300d22451 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { assert_eq!(realm.run(src), Ok(JsValue::Number(42.0))); } +#[test] +fn successive_apply_expansions_keep_getter_receivers_alive() { + for queued in [false, true] { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() }); + let src = "var result; function callback(a) { result = this.kept + a; } \ + var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \ + var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};"; + realm.run(src).unwrap(); + let collections = realm.interp().heap.collections; + let call = if queued { + "Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));" + } else { + "Function.prototype.apply.apply(callback, outer);" + }; + realm.run(call).unwrap(); + assert!(realm.interp().heap.collections > collections); + assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}"); + } +} + #[test] fn to_number_skips_the_white_space_the_lexer_skips() { let mut realm = small(Limits::default()); From 1b6bcd370ac11fa318da69ca1930a15a72f7a66f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:42:40 -0800 Subject: [PATCH 47/84] JavaScript: cache shared rejection reason attribution --- crates/js/src/builtins/promise.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..6a2b5005a6 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -731,6 +731,7 @@ impl Interp { pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { let rejected = std::mem::take(&mut self.promises.rejected); let mut out = Vec::new(); + let mut attribution = Vec::new(); let mut count = 0; for p in rejected { let (reason, site) = match self.heap.object(p).map(|o| &o.class) { @@ -748,7 +749,17 @@ impl Interp { message.truncate(cut); message.push('…'); } - let authored = self.thrown_by_script(&reason); + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); out.push(crate::Rejection { message, line, column, tag, authored }); } From ff9bd64003f21a1cb9f83a1b7c49ca632c850b78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:53:49 -0800 Subject: [PATCH 48/84] JavaScript: preserve Promise rejection relay locations --- crates/js/src/builtins/promise.rs | 15 +++++++++------ crates/js/src/promise_tests.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 +++ docs/target-app-parity.md | 2 +- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..a464dd348d 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -140,7 +140,7 @@ enum Job { /// What happens when the running job's call ends. enum Then { /// The result resolves this promise, and an exception rejects it. - Settle(ObjId), + Settle(ObjId, Option), /// An exception rejects through this resolving record. Reject(ObjId), /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or @@ -214,7 +214,7 @@ impl Promises { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); roots.values.extend(self.completion.iter()); match &self.running { - Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Settle(o, _) | Then::Reject(o)) => roots.objects.push(*o), Some(Then::Finally { derived, value, .. }) => { roots.objects.push(*derived); roots.values.push(value); @@ -662,7 +662,7 @@ impl Interp { interp.temp_roots.extend([handler, argument.clone()]); (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) } - None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)), + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), } } Job::Thenable { promise, thenable, then } => { @@ -689,8 +689,8 @@ impl Interp { let site = if r.is_err() { caught(self) } else { None }; let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; match (then, r) { - (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), - (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), (Then::Reject(_), Ok(_)) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); @@ -796,7 +796,10 @@ fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// A promise's reject function (section 25.6.1.3.1). fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; - let site = here(interp); + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); reject_through(interp, rec, arg(args, 1), site)?; Ok(Value::Undefined) } diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..ef0ed1d0d1 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -226,6 +226,30 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { assert_eq!(got, want); } +#[test] +fn combinator_rejection_relays_keep_the_input_location() { + for method in ["all", "race"] { + let mut r = realm(); + r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 1, "{method}: {reported:?}"); + assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); + assert!(reported[0].column > 0); + assert_eq!(reported[0].tag, r.script_tag()); + } + let mut r = realm(); + r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});") + .unwrap(); + assert_eq!(r.unhandled_rejections().len(), 1); + assert_eq!(r.unhandled_rejections()[0].line, 3); + assert!(r.unhandled_rejections()[0].column > 0); + let mut r = realm(); + r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 2); + assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}"); +} + #[test] fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { let mut r = realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..18f0c52537 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2895,6 +2895,9 @@ own rules: rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. + `all` and `race` preserve an input rejection's known location. Calling a saved reject function from script uses + that call's location. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits + `file` and sets `line` and `column` to 0. The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and `arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b564a77730..da7d19a638 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1107,7 +1107,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. From fc07f8a326996d106537458b10d8794606e90fb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:56:03 -0800 Subject: [PATCH 49/84] JavaScript: root the running rejection site code --- crates/js/src/builtins/promise.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index a464dd348d..92e5c25796 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -214,7 +214,11 @@ impl Promises { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); roots.values.extend(self.completion.iter()); match &self.running { - Some(Then::Settle(o, _) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), Some(Then::Finally { derived, value, .. }) => { roots.objects.push(*derived); roots.values.push(value); From f182ad845be7fc42189402682734c9cb0599391f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:56:36 +0700 Subject: [PATCH 50/84] Text: an over-budget COLR glyph returns no image, raster fallback included A sweep gradient sets unsupported without too_large, so a glyph that later passed the budget still took the raster branch, and Pixels replayed the whole graph with no budget. Check too_large first, as tree.finish() does. Under-budget glyphs are unchanged. Answers CodeRabbit. --- crates/text/src/colr.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 822e1b0972..37c4cefbae 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -73,6 +73,10 @@ pub(crate) fn colour_glyph( return (None, false); } let used = tree.foreground_used; + // Over the budget nothing is drawn, not even the raster fallback: it would replay the graph. + if tree.too_large { + return (None, used); + } if tree.unsupported.is_some() { // What it paints, y up, for a glyph without a clip box. let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b)); From 0983b6dfd50d6b6438b8d196c756975e23cf42f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:57:29 -0800 Subject: [PATCH 51/84] End paused JavaScript runs before compiling replacement source --- crates/js/src/host_tests.rs | 90 +++++++++++++++++++++++++++++++++++++ crates/js/src/realm.rs | 3 ++ docs/mcp.md | 2 + docs/target-app-parity.md | 2 + 4 files changed, 97 insertions(+) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 25265086e5..63032d7aa2 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -75,6 +75,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() { r.end(); } +fn paused_for_replacement(promise: bool) -> Realm { + let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default()); + let pause = r.pause_flag(); + r.define_function("pauseNow", move |_| { + pause.set(true); + Ok(JsValue::Undefined) + }); + let source = if promise { + "var kept = 'yes', after = false, queued = false;\n\ + Promise.resolve().then(function () { pauseNow(); after = true; });\n\ + Promise.resolve().then(function () { queued = true; }); 'old'" + } else { + "var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'" + }; + r.start(source).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.is_running()); + if promise { + assert!(r.interp().promises.draining); + } + r +} + +fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result { + if sliced { + r.start(source)?; + finish(r, 1_000).0 + } else { + r.run(source) + } +} + +#[test] +fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() { + for sliced in [false, true] { + let mut r = paused_for_replacement(true); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_paused_script_discards_its_remaining_code() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_waiting_run_discards_its_host_call() { + for sliced in [false, true] { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var after = false; ask('old'); after = true").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.waits()); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + assert_eq!(calls.get(), 1); + assert!(r.answer(Data::Null).is_err()); + } +} + +#[test] +fn replacing_a_paused_run_with_invalid_source_still_ends_it() { + for promise in [false, true] { + for sliced in [false, true] { + let mut r = paused_for_replacement(promise); + assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } + } +} + +#[test] +fn replacing_a_paused_run_applies_its_pending_language_setting() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + r.set_es2015(true); + assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0)); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + } +} + /// Setting `Folder.current` back for the next run drops what only the last run's uncaught /// exception held, so a full heap from that exception does not stop the next run. #[test] diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index b1273cb760..a3a7c0cc1f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -277,6 +277,7 @@ impl Realm { /// Runs `source` as a script in the global environment, then the promise jobs it queued, and /// returns its completion value (the value of the last expression statement that ran). A realm /// whose built-ins could not be installed runs nothing and gives an internal error. + /// A paused or waiting run ends first; its globals remain available. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); @@ -285,6 +286,7 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.end(); self.script_tag = UNKNOWN_SOURCE; self.rejections = (Vec::new(), 0); let interp = &mut self.interp; @@ -391,6 +393,7 @@ impl Realm { } /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + /// A paused or waiting run ends first; its globals remain available. pub fn start(&mut self, source: &str) -> Result<(), RunError> { let code = self.compile(source)?; match self.interp.enter_global(code, false) { diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..1705b42b38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2883,6 +2883,8 @@ own rules: - The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. A promise still pending when no job is left stays pending, and the run ends. +- In the host API, `Realm::run` and `Realm::start` end a paused or waiting run before compiling the new source. + The earlier run's globals remain available; its remaining code and queued jobs do not run. - The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b564a77730..49104b8aa5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From acda8bed2747980e1f1271c597c34b736d174bdd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:07:41 -0800 Subject: [PATCH 52/84] Effects: restore the blend-mode menu for shadows and glows Use the grouped picker in the effect dialogs and Appearance editor. Validate new automation requests while preserving earlier spellings, recorded steps, and untouched stored modes. --- crates/effects/src/catalog.rs | 6 +- crates/effects/src/lib.rs | 5 +- crates/effects/src/params.rs | 22 ++++++ crates/engine/src/cmd/effectcmd.rs | 11 ++- crates/engine/src/cmd/params.rs | 23 +++++- crates/engine/tests/it/param_keys.rs | 50 +++++++++++++ crates/ui-egui/src/control.rs | 5 ++ crates/ui-egui/src/dialogs/effect.rs | 20 ++++++ crates/ui-egui/src/dialogs/effect_params.rs | 5 ++ crates/ui-egui/src/dialogs/form.rs | 7 ++ crates/ui-egui/src/dialogs/tests.rs | 79 +++++++++++++++++++++ crates/ui-egui/src/fields.rs | 9 +++ docs/mcp.md | 14 ++++ 13 files changed, 245 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..071d3c3b64 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "stylize.dropShadow", "Drop Shadow…", STYLIZE, - "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", + "{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), ), r( "stylize.innerGlow", "Inner Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), ), r( "stylize.outerGlow", "Outer Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..555610f206 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -82,11 +82,12 @@ pub use group::{ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; +pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use placement::pinned_gradient_item; pub use raster::{ - RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, - without_geometry, + RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, + staged_effects, without_geometry, }; pub use reshape::{ SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index fed9df7811..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -1,6 +1,28 @@ +use vectorcraft_doc::color::BlendMode; + use super::catalog::{catalog_index, plugin_info}; use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util}; +/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in. +pub fn takes_blend_mode(effect: &str, key: &str) -> bool { + key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow") +} + +/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode. +pub fn parse_blend_mode(s: &str) -> Option { + let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect(); + BlendMode::parse(&name) +} + +/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`. +pub fn blend_mode_id(mode: BlendMode) -> String { + let mut name = format!("{mode:?}"); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_lowercase(); + } + name +} + /// Dialog defaults for `id` (`None` for unknown effects). pub fn default_params(id: &str) -> Option { match catalog_index().get(id) { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..25d7d38321 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption } } +/// The effect an apply request names, including the older `id` parameter. +pub(crate) fn requested_effect(p: &Value) -> Option<&str> { + str_param(p, "effect").or_else(|| str_param(p, "id")) +} + /// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the -/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; -/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. +/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one. +/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.apply"; - let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?; + let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?; // An effect given as `id` names no objects: the targets are read with that `id` as null. let effect_as_id; let p = if str_param(p, "effect").is_none() { diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..e88f348085 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -34,7 +34,8 @@ //! plays. A key a schema doesn't name passes there too, and the values of the parameters it names //! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` -//! themselves ([`check_effect_color`], [`check_effect_channel`]). +//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown +//! shadow or glow blend mode, which the effect draws as Normal. use std::collections::HashMap; use std::sync::OnceLock; @@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> { /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the /// effect takes (those of its dialog defaults and of its params description), each of the type /// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) -/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or +/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range /// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its /// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { @@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(unknown(id, key, &keys)); } + check_effect_blend(id, effect, params)?; check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER @@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was +/// given it: a parameter error naming the blend modes unless the effect reads it as one +/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal. +fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + let key = "mode"; + let Some(v) = params.get(key) else { return Ok(()) }; + if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() { + return Ok(()); + } + let modes: Vec = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect(); + Err(bad(id, format!("`{key}` must be one of {}", modes.join(", ")))) +} + /// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` /// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's /// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they @@ -1067,7 +1084,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = - (id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params")) + (id, super::effectcmd::requested_effect(params), params.get("params")) { check_effect_params(id, effect, given)?; } diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() { assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha")); } +/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused +/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it +/// takes, and the document and its undo history stay as they were. Blend-mode names in any +/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays. +#[test] +fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap(); + let state = |s: &Session| { + let st = s.active().unwrap(); + (st.doc.clone(), st.history.undo.len()) + }; + let before = state(&s); + let why = "`mode` must be one of normal, darken, multiply, colorBurn"; + for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] { + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"mode": bad}})), + ("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})), + ("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})), + ("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).unwrap_err().to_string(); + assert!(checked.contains(why), "{cmd} {params}: {checked}"); + assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history"); + } + } + let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone(); + let shadow = effect(&s); + let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params); + assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default"); + for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] { + let params = json!({"index": 0, "params": {"mode": good}}); + s.check_params("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + assert_eq!(effect(&s).params["mode"], json!(good)); + } + s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap(); + assert_eq!(effect(&s).params["mode"], json!("multipy")); + assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal); + for mode in vectorcraft_color::BlendMode::ALL { + let id = vectorcraft_render::effects::blend_mode_id(mode); + assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode)); + assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode); + } +} + /// What a command adds to its own journal entry passes the check, so a recorded journal can be /// sent back through the control channel or MCP. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 813ed31d97..9d729c31d4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1465,6 +1465,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index bcfecb47e1..a765bebbc8 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -69,6 +69,26 @@ pub(crate) struct Open { asking: bool, } +/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. +pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { + let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; + if id != open.id || open.asking || !vectorcraft_effects::takes_blend_mode(&open.cx.id, "mode") { + return; + } + let normalize = |field: &mut Value| { + if field["field"] == "mode" + && let Some(mode) = field["value"].as_str().and_then(vectorcraft_effects::parse_blend_mode) + { + field["value"] = json!(vectorcraft_effects::blend_mode_id(mode)); + } + }; + if let Some(fields) = params.get_mut("fields").and_then(Value::as_array_mut) { + fields.iter_mut().for_each(normalize); + } else { + normalize(params); + } +} + /// `effect.dialog {effect, index?, item?}`: edit applied effect `index` of `item` (null: the /// object's effects; omitted: the active item's, else the object's) prefilled with its values, /// or add `effect`, first asking when that list already has it. diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 06bf617898..ef5b2a5ea4 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -150,6 +150,11 @@ fn generic_row(cx: &EffectCx, key: &str, default: &Value, relative: bool) -> Opt Param::number(key, label, n, 1.0, 2) } } + // The blend mode the effect draws in: the mode it draws a name in, Normal for one it doesn't know. + Value::String(text) if vectorcraft_effects::takes_blend_mode(id, key) => { + let mode = vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(text)); + Param::new(key, label, ParamKind::blend(crate::fields::effect_blend_modes(), Some(mode))) + } Value::String(text) => match options() { Some(list) => Param::new(key, label, ParamKind::choice(list, Some(text.clone()))), None if text.starts_with('#') => Param::new(key, label, ParamKind::color(None)), diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 6d81d18214..a8d20b7416 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -171,6 +171,13 @@ fn field_value(row: Option<&Param>, value: &Value) -> Option { }, // A pair of radio buttons over a flag (Relative / Absolute): the ids are "true" and "false". Some(ParamKind::Radio { .. }) if value.is_boolean() => value.as_bool().map(|b| FieldValue::Text(b.to_string())), + // Use the renderer's mode for each spelling, including Normal for unknown names and the effect's default for + // a legacy value that is not text. + Some(ParamKind::Blend { default, .. }) => value + .as_str() + .map(|s| vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(s))) + .or_else(|| default.clone()) + .map(FieldValue::Text), // A custom row's list, and one a key no row has carries through (an export's `artboards: [0, 1]`), stay JSON: a // list of whole numbers would read back as a grid, and one of two or three as a point or colour. Some(ParamKind::Custom(_)) | None if value.is_array() => Some(FieldValue::Json(value.clone())), diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1eeec2d52d..c45284ba5a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -213,6 +213,85 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// Drop Shadow's, Inner Glow's and Outer Glow's Mode is a blend-mode menu of every mode the effect draws, opening on the +/// effect's default, in the dialog and in the Appearance panel's editor (the same rows over the stored values, where a +/// mode in another spelling shows as its menu entry). Picking Multiply in a glow's dialog stores `multiply`, and a mode +/// the menu lacks is refused as it is set. +#[test] +fn shadow_and_glow_dialogs_pick_mode_from_a_blend_mode_menu() { + use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, ParamKind}; + let modes: Vec = vectorcraft_doc::color::BlendMode::ALL.into_iter().map(vectorcraft_effects::blend_mode_id).collect(); + for (effect, default) in [("stylize.dropShadow", "multiply"), ("stylize.innerGlow", "screen"), ("stylize.outerGlow", "screen")] { + let mut app = app(); + for editing in [false, true] { + let cx = super::effect_params::EffectCx::new(&app, effect, editing); + let rows = super::effect_params::effect_params(&cx, &DialogFields::new()); + let row = rows.iter().find(|p| p.key == "mode").unwrap_or_else(|| panic!("{effect}: a Mode row")); + let ParamKind::Blend { modes: listed, default: shown, .. } = &row.kind else { panic!("{effect}: Mode is {:?}", row.kind) }; + let listed: Vec = listed.iter().map(|(entry, _)| entry.key.clone()).collect(); + assert_eq!(listed, modes, "{effect}"); + assert_eq!(shown.as_deref(), Some(default), "{effect}"); + let stored = serde_json::Map::from_iter([("mode".to_string(), json!("Color Burn"))]); + let fields = super::form::fields_of(&rows, &stored); + assert_eq!(fields.get("mode"), Some(&FieldValue::from("colorBurn")), "{effect}"); + } + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(default), "{effect}"); + let (dialog, ctx) = (top(&app).0, app.ui_ctx.clone().expect("a window app")); + let refused = app.dialogs().expect("a window app").with(|h| h.set_json_field(&ctx, dialog, "mode", json!("multipy"))); + assert!(refused.is_err(), "{effect}: a mode the menu lacks"); + let want = if default == "multiply" { "colorBurn" } else { "multiply" }; + let mode = if default == "multiply" { "Color Burn" } else { "Multiply" }; + let params = match effect { + "stylize.dropShadow" => json!({"field": "mode", "value": mode}), + "stylize.innerGlow" => json!({"dialog": dialog.value(), "fields": [{"field": "mode", "value": mode}]}), + _ => json!({"dialog": dialog.value().to_string(), "fields": [{"field": "mode", "value": mode}]}), + }; + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", params); + assert_eq!(fields(&app)["mode"], json!(want)); + frame(&mut app, vec![]); + assert!(confirm(&mut app), "{effect}"); + let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert_eq!(n.appearance.effects[0].params["mode"], json!(want), "{effect}"); + } +} + +/// Confirming an untouched legacy mode keeps the file's value and does not add an undo step. +/// Choosing a different mode updates the stored value. +#[test] +fn unchanged_effect_dialog_preserves_legacy_blend_modes() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let effect = "stylize.dropShadow"; + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null})).unwrap(); + for (old_mode, shown_mode) in [(Value::Null, "multiply"), (json!("multipy"), "normal")] { + app.session.replay("effect.setParams", &json!({"ids": [id], "index": 0, "item": null, "params": {"mode": old_mode}})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(shown_mode)); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params.get("mode"), Some(&old_mode)); + assert_eq!(state.history.undo.len(), before); + + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + let ctx = app.ui_ctx.clone().expect("a window app"); + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "mode", "value": "Screen"})); + frame(&mut app, vec![]); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params["mode"], json!("screen")); + assert_eq!(state.history.undo.len(), before + 1); + } +} + /// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's dialog open on the /// converted color, and OK without editing it keeps the color. #[test] diff --git a/crates/ui-egui/src/fields.rs b/crates/ui-egui/src/fields.rs index f5eb2e33f2..a2f0e728d9 100644 --- a/crates/ui-egui/src/fields.rs +++ b/crates/ui-egui/src/fields.rs @@ -44,6 +44,15 @@ pub fn blend_entries() -> Vec> { framework_blend_entries(&entries, |entry| mode_label(entry.key)) } +/// The modes of an effect's blend-mode row. The entries use the stored IDs and translated names. +/// The framework uses each mode's key metadata to separate the existing groups. +pub fn effect_blend_modes() -> Vec<(BlendKeyEntry, Label)> { + blend_table() + .into_iter() + .map(|(mode, shortcut)| (BlendKeyEntry::new(vectorcraft_effects::blend_mode_id(mode), shortcut), mode_label(mode))) + .collect() +} + /// `mode`'s name in the interface language. fn mode_label(mode: BlendMode) -> Label { Label::from(crate::i18n::t(mode.label())) diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..570293be09 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2152,6 +2152,20 @@ one opens as before and draws it as `rgb`: → invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue ``` +The `mode` of Drop Shadow, Inner Glow and Outer Glow must name one of the 16 blend modes: `normal`, `darken`, +`multiply`, `colorBurn`, `lighten`, `screen`, `colorDodge`, `overlay`, `softLight`, `hardLight`, `difference`, +`exclusion`, `hue`, `saturation`, `color` or `luminosity`. The name is read in any letter case and with any spaces, +hyphens or underscores (`Color Burn` and `color-burn` are `colorBurn`). An omitted `mode` keeps the effect's default +(`multiply` for Drop Shadow, `screen` for the glows). New `effect.apply` and `effect.setParams` calls refuse any other +value. An older document, action or journal with an unknown name still draws it as `normal`. A non-string value uses +the effect's default. The effect dialogs and the Appearance panel show `mode` as a blend-mode menu. +`ui.dialog.set` accepts the same blend-mode spellings. + +```json +{"id": "effect.setParams", "params": {"index": 0, "params": {"mode": "multipy"}}} +→ invalid parameters for `effect.setParams`: `mode` must be one of normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color, luminosity +``` + Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other From e3b21ad2bdaa38a202d4347f224a4c85d3b483de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:09:16 -0800 Subject: [PATCH 53/84] Name the undo step when keeping an add-on preview --- crates/ui-egui/src/addons/dialogs.rs | 4 ++-- crates/ui-egui/src/addons/dialogs/tests.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 55ad5dd64d..d29066a126 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -99,8 +99,8 @@ fn pump_commit(app: &mut VectorcraftApp) { let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); - // PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label) - let answer = preview.run(app, *previewing, spec.command, spec.command, params); + let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); + let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 9a24a362eb..eb24e09c37 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -247,6 +247,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() { } } +#[test] +fn keeping_an_add_on_preview_records_the_command_name() { + let mut app = two_rects(); + let undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + + assert!(confirm(&app, id)); + frame(&mut app); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid"); +} + #[test] fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() { let mut app = two_rects(); From cb89cd5ef39da2ddd3c547d22e6da1673cdd4cbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:09:16 -0800 Subject: [PATCH 54/84] Clear pending Type edit when the missing font prompt closes --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/canvas/tests.rs | 13 ++++++++++ crates/ui-egui/src/dialogs/confirm.rs | 36 +++++++++++++++------------ crates/ui-egui/src/lib.rs | 2 ++ 4 files changed, 36 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 89d64872e8..c083bf99a6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -232,6 +232,7 @@ impl VectorcraftApp { shortcuts_dialog: None, shortcut_overrides: Default::default(), told: Default::default(), + missing_font_edit_token: None, held: Default::default(), edit_scopes: Default::default(), command_dialog: Default::default(), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..baee23876b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3599,7 +3599,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3609,6 +3612,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 12e13a36b3..72fb9a40a6 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -100,8 +100,7 @@ wrapped_dialog!(Question, StandardPrompt, KIND); pub(crate) struct Message(HostedAlert); wrapped_dialog!(Message, HostedAlert, MESSAGE); -/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the -/// tool's edit token. +/// The Type tool's question whether to edit type set in fonts that aren't available. pub(crate) struct MissingFontQuestion(StandardPrompt); wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); @@ -215,13 +214,15 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(token) = p.get("token").and_then(Value::as_u64) else { + return; + }; let Some(dialogs) = app.dialogs() else { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; }; if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -234,14 +235,18 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) .paragraph(detail) .button(PromptChoice::Proceed, tl!("OK")) - .button(PromptChoice::Cancel, tl!("Cancel")) - .tag(token); - dialogs.with(|host| host.open(MissingFontQuestion(prompt))); + .button(PromptChoice::Cancel, tl!("Cancel")); + dialogs.with(|host| { + host.open(MissingFontQuestion(prompt)); + // Replacing a prompt leaves its Cancel in the host. The tool is already waiting on the new token. + let _ = host.take::(); + }); + app.missing_font_edit_token = Some(token); } /// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` /// names: with `ok` the edit starts at once; without, the tool forgets it. -pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { +fn answer_missing_font_edit(app: &mut VectorcraftApp, token: u64, ok: bool) { app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); @@ -277,13 +282,12 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { let Some(dialogs) = app.dialogs() else { return; }; - let (ok, token) = match dialogs.with(|host| host.take::()) { - None => return, - Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), - // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. - Some(_) => (false, None), - }; - answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); + if let Some(result) = dialogs.with(|host| host.take::()) + && let Some(token) = app.missing_font_edit_token.take() + { + let ok = matches!(result, DialogResult::Ok(answer) if answer.choice == PromptChoice::Proceed); + answer_missing_font_edit(app, token, ok); + } } /// The confirmation open now, if one is: its message and detail as shown, and the command OK runs. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 99d88741c1..6078ca0c07 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -266,6 +266,8 @@ pub struct VectorcraftApp { pub(crate) shortcut_overrides: Arc, /// Messages waiting for the dialog that shows them. pub(crate) told: dialogs::host::Told, + /// The Type tool's pending edit, kept even when the dialog closes without a prompt answer. + pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one From bc2162f91c32e82097cae20c53c2eb2d28be236f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:49:28 -0800 Subject: [PATCH 55/84] Use muted body text for Learn step numbers --- crates/ui-egui/src/panels/learn.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs index 985871889c..5753cc3bb5 100644 --- a/crates/ui-egui/src/panels/learn.rs +++ b/crates/ui-egui/src/panels/learn.rs @@ -27,7 +27,7 @@ use craft::ui::contract::{ Bind, CollectionEvent, Gap, LabelKind, MemoProps, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, Sizing, clicked, }; -use craft::ui::display::Text; +use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; @@ -221,8 +221,7 @@ fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::Tuto if let Some(next) = next { marked = Some((i, next)); } - // PLAN: the number should read in the muted ink; the caption role stands in until `Text` names it. - Text::new(format!("{}.", i + 1)).role(TypeRole::Caption).show(ui); + Text::new(format!("{}.", i + 1)).shade(Shade::Muted).show(ui); if step_text(ui, step) { locate = step.tool; } From 4d35a569cbf4c0c12bba6546c5b51742fcc1e83e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:05:38 -0800 Subject: [PATCH 56/84] Make the Production Preflight findings list name translatable --- crates/ui-egui/src/panels/preflight.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index f8ed1f6967..4b4353d8ac 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -302,7 +302,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { let rows = PreflightRows::new(report); let pending = Pending::default(); - let out = FindingsList::new("Findings").show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { + let out = FindingsList::new(tl!("Findings")).show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { Some(Entry_::Heading(c)) => heading_row(&rows.checks[*c], &pending), Some(Entry_::Finding(f)) => finding_row(*key, &rows.findings[*f], &icx.words::(), &pending), None => ListRow::new(String::new()), From a257568cd3e2d028018991e68533d0d7b2fa018b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:07:25 -0800 Subject: [PATCH 57/84] Fix the PDF page options OK footer --- crates/ui-egui/src/dialogs/import_pdf.rs | 11 ++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 44 +++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..99ce30805d 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,14 +372,11 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } - match (out.accepted, out.closed) { - (Some(_), _) => { - self.ok(); - None - } - (None, Some(_)) => Some(DialogResult::Cancel), - (None, None) => None, + if out.picked == Some(0) && !waiting { + self.ok(); + return None; } + out.closed.map(|_| DialogResult::Cancel) } } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..4e9008a734 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -1,6 +1,7 @@ //! The Import PDF dialog: opening and placing multi-page and password-protected PDFs. use craft::ui::dialog::{HeldOk, StackDialog}; +use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; @@ -72,6 +73,37 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } +fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::import_pdf::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(!is_open(h.state())); + h +} + +#[test] +fn pdf_page_footer_ok_opens_the_chosen_range() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); + + let h = click_page_footer_ok(app); + assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); +} + #[test] fn opening_a_multi_page_pdf_asks_for_the_pages() { let mut app = app(); @@ -228,6 +260,18 @@ fn place(app: &mut VectorcraftApp, bytes: &[u8], extra: serde_json::Value) -> Re crate::place::run(app, &p) } +#[test] +fn pdf_page_footer_ok_places_the_chosen_page() { + let mut app = app(); + place(&mut app, &three_pages(), json!({"at": [100, 120], "link": false})).unwrap(); + set(&mut app, "page", json!(2)); + set(&mut app, "cropTo", json!("art")); + + let h = click_page_footer_ok(app); + let (_, bounds) = placed(h.state()); + assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); +} + #[test] fn placing_a_pdf_page_asks_for_the_page_and_crop_box() { let mut app = app(); From 6e190e189aeccde32834bc774878fe1feaacaa0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:07:25 -0800 Subject: [PATCH 58/84] Fix the Graph Column and Marker OK footer --- crates/ui-egui/src/dialogs/graph_design.rs | 34 ++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 2bfdf7b913..f361b5f8c6 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,8 +519,7 @@ impl GraphDesignDialog { } true }); - if let Some(options) = shown.accepted { - self.column = options; + if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); return None; @@ -836,6 +835,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { + use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; use super::GraphDesignDialog; @@ -879,6 +879,36 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_design_footer_ok_applies_column_and_marker_designs() { + for (graph_type, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_type); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(4); + + let app = h.state_mut(); + assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], "New Design"); + } + } + #[test] fn marker_lists_the_designs_and_applies_the_one_picked() { let (mut app, ctx) = app_with_design(); From 70e0dd20de334b0ce04a2790e9ed757129bd45b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:11:37 -0800 Subject: [PATCH 59/84] Reject foreign-document artwork in Asset Export --- crates/ui-egui/src/panels/asset_export.rs | 3 +- .../ui-egui/src/panels/tests_asset_export.rs | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index bfd9867950..36df059b59 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -553,7 +553,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { footer = Some(bar); }); let zone = footed.show(ui, |ui, _| { - DropAction::::new(|p| matches!(p, PanelDrag::Art { .. })).sizing(Sizing::Fill).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |p| matches!(p, PanelDrag::Art { document, .. } if *document == uid)); + drop_art.sizing(Sizing::Fill).show(ui, |ui, _| { if st.doc.assets.is_empty() { Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) .title(tl!("No assets")) diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index bde196ffd2..e14e6c0ea3 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -56,6 +56,56 @@ fn assets(app: &mut VectorcraftApp) -> Vec { app.run("assets.list", json!({})).unwrap()["assets"].as_array().unwrap().clone() } +/// Draws a row carrying the selected artwork's payload above the Asset Export panel. +fn art_and_assets(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + + let st = app.session.active().unwrap(); + let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + super::asset_export::show(app, ui); +} + +#[test] +fn asset_export_accepts_artwork_only_from_its_document() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let mut rectangle = |x| { + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let first = rectangle(10); + let second = rectangle(70); + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + let source = app.session.active().unwrap().uid; + + let mut p = Panel::new(app, art_and_assets); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("No assets").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_some(), "Asset Export accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_none(), "Asset Export withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert!(assets(&mut p.app()).is_empty(), "the foreign drag must never collect the active document's same-ID artwork"); + + p.drag("Dragged artwork", "No assets", egui::Modifiers::NONE); + let list = assets(&mut p.app()); + assert_eq!(list.len(), 1, "dropping artwork from the active document still collects it"); + assert_eq!(list[0]["nodes"], json!([second])); +} + /// The document's export settings, which the panel and Export for Screens share. fn settings(p: &Panel) -> Value { run(p, "document.exportSettings", json!({}))["settings"].clone() From 40f7f2e0a08a75d01acda014c304b2dfafba3f0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:12:50 -0800 Subject: [PATCH 60/84] Keep Graph Data imports with the sheet that asked --- crates/ui-egui/src/dialogs/graph_data.rs | 55 ++++++++++++++++++++---- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 2ac4764bf5..572f92f664 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -18,6 +18,7 @@ //! empties it). use std::collections::BTreeMap; +use std::sync::Arc; use craft::behavior::{EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; @@ -395,8 +396,12 @@ fn can_import(app: &VectorcraftApp) -> bool { file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() } -/// Import Data's answer: a tab-separated text file's rows into the sheet. -fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { +/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. +fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result { + let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) }; + if !dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) { + return Ok(Value::Null); + } let bytes = match picked { Picked::Paths(paths) => { let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) }; @@ -420,15 +425,14 @@ fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { return Err("the file is larger than 1 MB".into()); } let grid = grid_from_text(&decode(&bytes)); - if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); - } + dialogs.with(|host| host.get_mut::().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid))); Ok(Value::Null) } /// What the window asked of the app since the last [`pump`]. struct Asks { graph: Option, + import_owner: Arc<()>, apply: Option, actions: Vec, } @@ -444,7 +448,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { d.take_asks() }) }); - let Some(Asks { graph, apply: filed, actions }) = asked else { return }; + let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; if let Some(sheet) = filed { if let Err(e) = apply(app, &sheet, graph) { app.status(e); @@ -455,7 +459,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); - file_asks::ask(app, request, Owner::Document, import); + let owner = import_owner.clone(); + file_asks::ask(app, request, Owner::Document, move |app, picked| import(app, &owner, picked)); } Action::Revert => match graph_grid(app, graph) { Ok(grid) => { @@ -636,6 +641,8 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { /// sheet for [`pump`], which sends it to the graph and keeps the window open. pub(crate) struct GraphDataDialog { id: DialogId, + /// Identifies this opening even when another Graph Data dialog reuses `id`. + import_owner: Arc<()>, sheet: Sheet, state: GridState, entry: Entry, @@ -658,6 +665,7 @@ impl GraphDataDialog { load(&sheet, &state, &mut entry); GraphDataDialog { id: dialog_id(KIND), + import_owner: Arc::new(()), sheet, state, entry, @@ -672,7 +680,7 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. @@ -959,6 +967,37 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let files = Arc::new(ScriptedFiles::held()); + app.services.read = Some(Box::new(|_| Err("this picker answers with bytes".into()))); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1); + + let app = h.state_mut(); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + open(app).unwrap(); + let series = |h: &Harness| read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)); + assert!(files.answer(Picked::Contents(vec![("first.txt".into(), b"\tstale\nQ1\t7".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "second"); + + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert!(files.answer(Picked::Contents(vec![("second.txt".into(), b"\timported\nQ2\t8".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "imported"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); From 78aa254ddb7e7c8f2149f1bd9b6325afc1bdbaac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:05:38 -0800 Subject: [PATCH 61/84] Translate the canvas Type editor's accessible name --- crates/ui-egui/src/canvas/tests.rs | 17 +++++++++++++++++ crates/ui-egui/src/type_editing.rs | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..6f90aeba3f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3919,6 +3919,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.active().unwrap().selection.objects[0].0 } +#[test] +fn the_canvas_type_editor_uses_the_interface_language() { + use crate::i18n::LangExt as _; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let former = crate::i18n::current(); + start_typing(&mut app, &ctx); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]); + crate::i18n::set_current(former); + + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte"))); +} + /// Returns a key press and its release. fn tap(key: egui::Key) -> [egui::Event; 2] { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) diff --git a/crates/ui-egui/src/type_editing.rs b/crates/ui-egui/src/type_editing.rs index 346a5854bf..8ee26749a2 100644 --- a/crates/ui-egui/src/type_editing.rs +++ b/crates/ui-egui/src/type_editing.rs @@ -289,7 +289,7 @@ pub(crate) struct TypeEditor<'a> { impl<'a> TypeEditor<'a> { /// A part for the tool's caret at `caret`, the instance of [`TypeEditorCommand`]'s scope while it has the keys. fn new(app: &'a mut VectorcraftApp, caret: Rect, ctx: egui::Context) -> Self { - TypeEditor { common: Common::new(), app, caret, ctx }.label("Type").command_scope(TYPE_EDITOR_SCOPE) + TypeEditor { common: Common::new(), app, caret, ctx }.label(tl!("Type")).command_scope(TYPE_EDITOR_SCOPE) } /// Applies one input of the editor part to the engine tool; a Paste types `pasted`, the text the paste delivered, From 3098ef72d24dfec40e0e52af7854408133017b4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:17:03 -0800 Subject: [PATCH 62/84] Reject foreign-document artwork in Graphic Styles --- crates/ui-egui/src/panels/graphic_styles.rs | 65 ++++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..52b6b2bdf1 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -477,6 +477,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The browser's own state (an open rename field, the scroll position) is kept per document. let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); let list = PresetBrowser::::list_id(browser_id); + let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid).is_some(); // A style dragged from this panel's list. let ours = move |drag: &ListDrag| drag.list == list; let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); @@ -516,8 +517,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) - .takes_drop(PresetDrop::new::(DropPlace::Between, |drag, _| dropped_object(drag).is_some())) - .takes_drop(PresetDrop::new::(DropPlace::Onto, |drag, _| dropped_object(drag).is_some())) + .takes_drop(PresetDrop::new::(DropPlace::Between, takes_object)) + .takes_drop(PresetDrop::new::(DropPlace::Onto, takes_object)) .takes_drop(PresetDrop::new::>( DropPlace::Onto, |drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)), @@ -596,11 +597,11 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent>) { } } -/// The object whose look a dropped payload carries: the first of the art dragged off the canvas, or the Appearance -/// panel's object. -fn dropped_object(drag: &PanelDrag) -> Option { +/// The object whose look a dropped payload carries: the first of the art dragged from this document, or the +/// Appearance panel's object. +fn dropped_object(drag: &PanelDrag, uid: u64) -> Option { match drag { - PanelDrag::Art { ids, .. } => ids.first().copied(), + PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(), PanelDrag::Appearance(id) => Some(*id), _ => None, } @@ -612,7 +613,7 @@ fn dropped(app: &mut VectorcraftApp, at: &DropAt, payload: &DropPayloa DropAt::Onto(name) => Some(name.as_str()), _ => None, }; - let object = payload.get::().and_then(dropped_object); + let object = app.session.active().and_then(|st| dropped_object(payload.get::()?, st.uid)); let style = payload.get::>().map(|drag| drag.grabbed.as_str()); drop_on(app, onto, object, style, alt); } @@ -1319,7 +1320,7 @@ mod tests { let n = names(&app); let document = app.session.active().unwrap().uid; for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] { - drop_on(&mut app, Some("Red"), dropped_object(&payload), None, true); + drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true); let d = doc(&app); assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green); assert_eq!(d.node(oval).unwrap().extras().graphic_style, d.graphic_style("Red").map(|g| g.id)); @@ -1336,6 +1337,54 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), steps); } + #[test] + fn graphic_styles_accepts_artwork_only_from_its_document() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 25, "y": 25, "width": 55, "height": 55})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let second = app.session.active().unwrap().selection.objects[0]; + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + let before = names(&app); + assert!(app.session.set_active(0)); + + let mut p = PanelHarness::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Drop Target").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphic Styles accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphic Styles withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(names(&p.app()), before, "the foreign drop creates no style from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Drop Target", egui::Modifiers::NONE); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a same-document drop still makes a style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { From 9093809d5dd7eff02798ea25fe644168c912d230 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:18:44 -0800 Subject: [PATCH 63/84] Keep Batch folder picks with the dialog that asked --- crates/ui-egui/src/dialogs/action_batch.rs | 59 ++++++++++++++++++---- crates/ui-egui/src/dialogs/actions.rs | 10 ++-- 2 files changed, 55 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 705913d428..4b2b79a02d 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,6 +8,7 @@ //! empty, or Data Sets without a document, is an error and the dialog stays open. use std::hash::Hash; +use std::sync::Arc; use craft::automation::actions::Action; use craft::host::PickRequest; @@ -131,6 +132,8 @@ pub(crate) enum Folder { /// The Batch dialog on the dialog host. pub struct BatchDialog { id: DialogId, + /// Identifies this opening even when another Batch dialog reuses `id`. + folder_owner: Arc<()>, /// The index of the action's set. pub set: usize, /// The index of the action in its set. @@ -150,13 +153,13 @@ impl BatchDialog { &self.form.values } - /// The Browse presses since the last call. - pub(crate) fn take_asked(&mut self) -> Vec { - std::mem::take(&mut self.asked) + /// The Browse presses since the last call and the opening that made them. + pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec) { + (self.folder_owner.clone(), std::mem::take(&mut self.asked)) } /// Writes the folder the picker answered into its row. - pub(crate) fn set_folder(&mut self, which: Folder, path: String) { + fn set_folder(&mut self, which: Folder, path: String) { match which { Folder::Source => self.form.values.folder = path, Folder::Destination => self.form.values.destination_folder = path, @@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result, which: Folder) { let title = match which { Folder::Source => crate::i18n::t("Source Folder"), Folder::Destination => crate::i18n::t("Destination Folder"), @@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) { if let Some(path) = picked.paths().first() && let Some(dialogs) = app.dialogs() { - let path = path.to_string_lossy().into_owned(); dialogs.with(|host| { - if let Some(dialog) = host.get_mut::() { - dialog.set_folder(which, path); + if let Some(dialog) = host.get_mut::().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) { + dialog.set_folder(which, path.to_string_lossy().into_owned()); } }); } @@ -437,6 +440,44 @@ mod tests { }); } + #[test] + fn batch_folder_answers_belong_to_the_dialog_that_asked() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let mut app = app_with(vec![step]); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let request_folders = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.get_mut::().unwrap().asked.extend([Folder::Source, Folder::Destination])); + pump(app, &ctx); + }; + let folders = || { + dialogs.with(|host| { + let fields = host.get::().unwrap().fields(); + (fields.folder.clone(), fields.destination_folder.clone()) + }) + }; + let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| { + picker.answer(&[destination]); + picker.answer(&[source]); + file_asks::poll(app); + }; + + open(&mut app, 0, 0).unwrap(); + request_folders(&mut app); + assert_eq!(picker.requests().len(), 2); + dialogs.with(|host| host.cancel::(&ctx)); + open(&mut app, 0, 0).unwrap(); + set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]); + answer(&mut app, "old-source", "old-destination"); + assert_eq!(folders(), ("new-source".into(), "new-destination".into())); + + request_folders(&mut app); + assert_eq!(picker.requests().len(), 4); + answer(&mut app, "picked-source", "picked-destination"); + assert_eq!(folders(), ("picked-source".into(), "picked-destination".into())); + } + /// Batch plays an action recorded with a key its command no longer reads, as Play does. #[test] fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() { diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 7d52338be2..8a6de85fe4 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -363,13 +363,13 @@ fn push_app_data(app: &VectorcraftApp) { } } -/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose -/// answer is written into the dialog. +/// Files the folder picks the Batch dialog asked for with the identity of that opening. fn ask_batch_folders(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked).unwrap_or_default()); - for which in asked { - super::action_batch::ask_folder(app, which); + let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked)); + let Some((owner, folders)) = asked else { return }; + for which in folders { + super::action_batch::ask_folder(app, owner.clone(), which); } } From 4020b59c5a2eaf6247a695b916a73cfd545a1420 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:17:05 -0800 Subject: [PATCH 64/84] Reject Swatches pattern drops from another document --- crates/ui-egui/src/panels/swatches.rs | 13 ++++------- crates/ui-egui/src/panels/swatches/dnd.rs | 12 ++++++++++ crates/ui-egui/src/panels/swatches/tests.rs | 25 ++++++++++++++++++++- 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9995752ec1..58f24ed3f5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use craft::color_ui::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchKind use craft::color_ui::ui::{SwatchKey, SwatchesPanel, SwatchesState}; use craft::theme::Srgba; use craft::ui::choice::SwatchFace; -use craft::ui::contract::{Bind, DropAt, DropPlace, ListDrag, MemoProps, SelectMode}; +use craft::ui::contract::{Bind, DropPlace, ListDrag, MemoProps, SelectMode}; use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; @@ -407,6 +407,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { doc: Arc::clone(&st.doc), }; let dragged_doc = Arc::clone(&thumbs.doc); + let document = st.uid; let shown_app: &VectorcraftApp = app; let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) @@ -416,8 +417,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { _ => vec![], }) .row_items(|key| row_items(shown_app, key)) - .takes_drop::(DropPlace::Between, takes) - .takes_drop::(DropPlace::Onto, takes) + .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document)) + .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document)) .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) @@ -467,12 +468,6 @@ fn on_event(app: &mut VectorcraftApp, shown: &[SwatchKey], event: PresetEvent) -> bool { - matches!(d, PanelDrag::Paint { .. } | PanelDrag::Art { .. }) -} - /// A double click or Enter: Swatch Options for a swatch, Edit or Apply Color Group for a group. fn activate(app: &mut VectorcraftApp, key: &SwatchKey) { match key { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index dd3aff50f9..2151357979 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,6 +4,15 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; +/// Swatches take paint payloads and artwork from the current document's canvas. +pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { + match drag { + PanelDrag::Paint { .. } => true, + PanelDrag::Art { document: source, .. } => *source == document, + _ => false, + } +} + /// A drag released on the panel. pub(super) enum Drop { /// Swatches (or colour groups) dropped before or `after` row `target`, into folder `target`, or @@ -75,6 +84,9 @@ fn place(shown: &[SwatchKey], at: &DropAt) -> (Option, bool) /// `drag` dropped onto a swatch or between rows of the `shown` list (ap.AP2 `Dropped`); a gap with no /// row under the pointer is the end of the list. pub(super) fn on_dropped(app: &mut VectorcraftApp, shown: &[SwatchKey], at: &DropAt, drag: &PanelDrag, mods: Mods) { + if !app.session.active().is_some_and(|st| accepts(drag, st.uid)) { + return; + } let (target, after) = place(shown, at); if let Some(drop) = Drop::of(drag, target, after, mods) { apply_drop(app, drop); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index b638b289f5..c770f5094a 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::dialogs::swatch_options::KIND; use crate::tests::picks::{answer_dialog, cancel_dialog, draw_dialogs, open_dialogs}; use craft::keymap::Mods; -use craft::ui::contract::ReorderMove; +use craft::ui::contract::{DropAt, ReorderMove}; use craft::ui::dialog::DialogId; use egui::Pos2; use vectorcraft_color::Color; @@ -602,6 +602,29 @@ fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { assert_eq!(doc(&app).node(vectorcraft_doc::NodeId(id)), before.node(vectorcraft_doc::NodeId(id)), "the art stays as it was"); } +#[test] +fn swatches_ignore_artwork_from_another_document_with_the_same_object_id() { + let mut app = app(); + let shape = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + let source = app.run("shape.rectangle", shape.clone()).unwrap()["id"].as_u64().unwrap(); + let drag = art_drag(&app, vec![vectorcraft_doc::NodeId(source)]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let local = app.run("shape.rectangle", shape).unwrap()["id"].as_u64().unwrap(); + assert_eq!(source, local); + + dropped_below(&mut app, drag.clone(), none()); + assert!(doc(&app).patterns.is_empty(), "foreign artwork cannot create a pattern"); + + let star = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap(); + let local_drag = art_drag(&app, vec![vectorcraft_doc::NodeId(star)]); + dropped_below(&mut app, local_drag, none()); + assert_eq!(doc(&app).patterns.len(), 1, "the same document's artwork can create a pattern"); + let before = doc(&app).patterns[0].clone(); + let name = before.name.clone(); + dropped(&mut app, drag, &name, alt()); + assert_eq!(doc(&app).patterns[0].art, before.art, "foreign artwork cannot replace an existing pattern"); +} + /// Art released with Alt held over a pattern swatch becomes that pattern's tile art in one undo /// step: no pattern or swatch is added and the art stays. With Alt over a color swatch, or without /// Alt over the pattern swatch, the art becomes a new pattern swatch. From 74d23677a60f7f2325731a7813c1c8f2d57775b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:14:25 -0800 Subject: [PATCH 65/84] Translate canvas widget accessibility text --- crates/ui-egui/src/canvas/selection_widgets.rs | 2 +- crates/ui-egui/src/canvas/widgets.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 00abc89bc9..921a9e73e4 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets { impl SelectionWidgets { fn new(layout: Layout) -> Self { - SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets")) } } diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 204853bd98..2545d16761 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -275,7 +275,7 @@ impl ShapeWidgets { } fn new(marks: Vec) -> Self { - ShapeWidgets { common: Common::new(), marks }.label("Shape widgets") + ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets")) } } @@ -334,7 +334,7 @@ impl Component for ShapeWidgets { } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { - access.description("Shape widgets"); + access.description(tl!("Shape widgets")); } fn finish(self, cx: Cx<'_, Self>) -> Response { From 7535fada7b388e3e06114826c6fc2bd98aa710e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:21:38 -0800 Subject: [PATCH 66/84] Keep gradient stop models when dropping onto art --- crates/ui-egui/src/canvas/drops.rs | 6 ++++ crates/ui-egui/src/canvas/drops/tests.rs | 35 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..f2ae87a7a8 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -362,6 +362,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); + if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) { + if cmd == "paint.setStroke" { + gradient.remove("dither"); + } + params["keepModel"] = json!(true); + } run(app, cmd, params) } Payload::Panel(PanelDrag::Appearance(source)) => { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..6fdaf1b7af 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -45,6 +45,41 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + app.session.fill_active = fill; + let mut gradient = GradientPaint::new(Default::default()); + gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0); + gradient.gradient.dither = true; + let start = undo_len(app); + let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient))); + drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(app), start + 1); + id +} + +#[test] +fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, true); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") }; + assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(fill.gradient.dither); +} + +#[test] +fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, false); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") }; + assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(!stroke.gradient.dither); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol From 682cac41bd8a9ea851875c8a139459429c321a60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:22:11 -0800 Subject: [PATCH 67/84] Reject artwork drops from a different document in Libraries --- crates/ui-egui/src/panels/libraries.rs | 68 ++++++++++++-------- crates/ui-egui/src/panels/libraries/tests.rs | 28 ++++++++ 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 655be80fb3..5d1955810a 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -162,21 +162,6 @@ enum Grab { New(ItemKind, Value), } -/// The item of library `library` that `drag` holds, or what it would add, if anything. -fn grabbed(drag: &PanelDrag, library: &str) -> Option { - match drag { - PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), - PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), - PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), - PanelDrag::Art { ids, .. } => { - let ids: Vec = ids.iter().map(|id| id.0).collect(); - Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) - } - PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), - _ => None, - } -} - /// The kind and `library.add` params of what `drag` holds, to add to library `library`: a color /// (not one of that library's own; a spot colour with its swatch's name), or a gradient or pattern /// swatch, by its name. @@ -205,6 +190,7 @@ fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { /// which keep their test, can read it: what a drop into a group, or out of every group, does. struct Membership { library: String, + active_document: Option, /// The group of each grouped item, by its index in the library's groups. index: HashMap<(ItemKind, String), usize>, /// The groups' names, in the library's order. @@ -212,9 +198,25 @@ struct Membership { } impl Membership { - fn of(library: &str, lib: &Library) -> Self { + fn of(library: &str, lib: &Library, active_document: Option) -> Self { let index = lib.group_index().into_iter().map(|((kind, item), group)| ((kind, item.to_string()), group)).collect(); - Membership { library: library.to_string(), index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + Membership { library: library.to_string(), active_document, index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + } + + /// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document. + fn grabbed(&self, drag: &PanelDrag) -> Option { + let library = &self.library; + match drag { + PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), + PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), + PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), + PanelDrag::Art { document, ids } if Some(*document) == self.active_document => { + let ids: Vec = ids.iter().map(|id| id.0).collect(); + Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) + } + PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), + _ => None, + } } fn group_of(&self, kind: ItemKind, key: &str) -> Option { @@ -232,7 +234,7 @@ impl Membership { /// another group moves in, art or a swatch is added there. `None` when nothing would change, /// as for an item dropped on its own group, so that the target does not take it. fn landing(&self, drag: &PanelDrag, group: Option) -> Option { - let (cmd, mut params) = match grabbed(drag, &self.library)? { + let (cmd, mut params) = match self.grabbed(drag)? { Grab::Item(kind, item) if self.group_of(kind, &item) != group => ("library.moveItem", json!({ "kind": kind_param(kind), "item": item })), Grab::New(_, add) => ("library.add", add), Grab::Item(..) => return None, @@ -303,8 +305,8 @@ struct View<'a> { } impl<'a> View<'a> { - fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, has_doc: bool, can_apply: bool) -> Self { - let membership = Membership::of(library, lib); + fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, active_document: Option, can_apply: bool) -> Self { + let membership = Membership::of(library, lib, active_document); let query = query.trim().to_lowercase(); let searching = !query.is_empty(); let items: Vec> = lib @@ -319,7 +321,20 @@ impl<'a> View<'a> { } } let empty = lib.items().next().is_none() && lib.groups.is_empty(); - View { library, lib, membership: Arc::new(membership), items, counts, query, searching, empty, list, fill_active, has_doc, can_apply } + View { + library, + lib, + membership: Arc::new(membership), + items, + counts, + query, + searching, + empty, + list, + fill_active, + has_doc: active_document.is_some(), + can_apply, + } } /// The list: the ungrouped items, then the groups as sections. A drop anywhere on it away from @@ -387,7 +402,7 @@ impl<'a> View<'a> { /// Whether the drag in progress holds an item of one of this library's groups. fn dragging_grouped(&self, ui: &Ui) -> bool { craft::ui::runtime::drag::active::(ui.ctx()).is_some_and( - |drag| matches!(grabbed(&drag, self.library), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), + |drag| matches!(self.membership.grabbed(&drag), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), ) } @@ -476,7 +491,7 @@ impl<'a> View<'a> { let source = keyed(shown, |item: &&Shown<'a>| item.key.to_string()); let takes = DropKind::new::( DropPlace::Between, - move |drag: &PanelDrag, _: &DropAt| matches!(grabbed(drag, self.library), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), + move |drag: &PanelDrag, _: &DropAt| matches!(self.membership.grabbed(drag), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), ); // A graphic is placed by a double click; every other item is used by a click. let activate = if kind == ItemKind::Graphic { ActivateOn::DoubleClick } else { ActivateOn::Click }; @@ -565,7 +580,7 @@ impl<'a> View<'a> { /// `kind` moves there, art or a swatch of that kind is added there. Nothing for an item dropped /// beside itself. fn dropped(&self, drag: &PanelDrag, kind: ItemKind, at: Option<(&'static str, &str)>, group: Option) -> Option { - match grabbed(drag, self.library)? { + match self.membership.grabbed(drag)? { Grab::Item(k, item) if k == kind => (at.is_none_or(|(_, key)| key != item)).then(|| self.moved(kind, &item, at, group)), Grab::New(k, mut params) if k == kind => { if let Some((side, key)) = at { @@ -761,7 +776,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let acts = RefCell::new(Vec::new()); - let has_doc = app.session.active().is_some(); + let active_document = app.session.active().map(|st| st.uid); + let has_doc = active_document.is_some(); { // PLAN: assumed `UiState::{libraries_list_view: bool, library_search: String, library_groups_closed: HashSet<(String, String)>}` (ap.AS17, hub-w1). let (session, state) = (&app.session, &mut app.ui); @@ -769,7 +785,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Whether a character style's Apply Character Style is enabled (looked up only when the library has one). let can_apply = has_doc && !lib.char_styles.is_empty() && vectorcraft_engine::cmd::textstyles::target_style_attrs(session, &json!({}), false).is_some(); - let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, has_doc, can_apply); + let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, active_document, can_apply); Panel::new(tl!("Libraries")).footer(|ui, _| footer(ui, has_doc, &acts)).show(ui, |ui, _| { let search = (!view.empty).then_some(&mut state.library_search); header(ui, &session.libraries, &lib_id, &mut state.libraries_list_view, search, &acts); diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 4d14dcb8a4..305e8eadbf 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -248,6 +248,34 @@ fn an_empty_library_takes_art_anywhere() { assert_eq!(graphics(&mut panel.app()).len(), 1); } +#[test] +fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() { + let mut app = app(); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + let first = art_drag(&mut app, 10.0); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let second = art_drag(&mut app, 50.0); + assert!(matches!((&first, &second), (PanelDrag::Art { ids: a, .. }, PanelDrag::Art { ids: b, .. }) if a == b)); + assert!(app.session.set_active(0)); + + let mut panel = Harness::new(app, with_source); + let from = panel.rect(SOURCE).center(); + let to = panel.rect("This library is empty").center(); + CARRIED.with(|carried| *carried.borrow_mut() = Some(first.clone())); + panel.drag_hold_role(SOURCE, craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_some()); + assert!(panel.app().session.set_active(1)); + panel.frame(); + let drag = craft::ui::runtime::drag::active::(panel.ctx()); + assert_eq!(drag.as_deref(), Some(&first)); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_none()); + panel.release(); + assert!(graphics(&mut panel.app()).is_empty(), "the library never collects the target document's same-ID artwork"); + + drop_at(&mut panel, second, to); + assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added"); +} + fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { let mut app = app(); app.run("library.create", json!({"name": "Brand"})).unwrap(); From 9314ddc4e7a4f21e964b59b2f990861d1259904c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:56:54 -0800 Subject: [PATCH 68/84] Tests: quote script file paths as JavaScript strings --- crates/engine/src/tests/script_dom.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..e3fada4b17 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1347,24 +1347,24 @@ fn editable_measures_a_group_on_a_locked_artboard_once() { #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); - let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + let fixture = vectorcraft_testkit::TempDir::new("script-file-open-quoting"); + let path = fixture.join("quote's open.svg"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = serde_json::to_string(&path.to_string_lossy()).unwrap(); + let other = serde_json::to_string(&format!("{}.other", path.to_string_lossy())).unwrap(); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. - let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + let elsewhere = fixture.join("elsewhere"); std::fs::create_dir_all(&elsewhere).unwrap(); let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); assert_eq!(out, vec![json!(false), json!(false)]); - let _ = std::fs::remove_dir_all(&elsewhere); for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); } assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); - let _ = std::fs::remove_file(path); } #[test] From e6e7d389a47e898c62a309388d7568c7e1c32958 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:25:36 -0800 Subject: [PATCH 69/84] Reject foreign-document artwork in 3D and Materials --- crates/ui-egui/src/dialogs/three_d.rs | 3 ++ .../ui-egui/src/dialogs/three_d_materials.rs | 5 +- crates/ui-egui/src/panels/tests_three_d.rs | 48 +++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 8345aad401..1bf8a87680 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -55,6 +55,8 @@ pub(crate) struct Data { pub bevels_file: bool, /// The active document, for the symbol pictures. pub doc: Option>, + /// The document that owns the object IDs accepted by the Graphics drop target. + pub document_uid: Option, /// The active document's version. pub revision: u64, /// Whether the active document has a selection. @@ -77,6 +79,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map Option { Text::new(tl!("Graphics")).show(ui); let mut action = None; - let (Some(doc), true) = (data.doc.clone(), true) else { return action }; + let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let keys = crate::panels::symbols::document_symbols(&doc, data.revision); let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str())); - let mut dropped = DropAction::::new(|drag| matches!(drag, PanelDrag::Art { .. })).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid)); + let mut dropped = drop_art.show(ui, |ui, _| { TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| { let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) }; let (doc, keys, name) = (doc.clone(), keys.clone(), name.clone()); diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index e13cf649a6..cc1c1593da 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -686,6 +686,54 @@ fn art_can_be_added_as_a_graphic_before_any_3d_effect() { assert!(painted_text(&mut app, show).contains("Add as Single Graphic")); } +#[test] +fn three_d_graphics_accepts_artwork_only_from_its_document() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + let add_existing = |app: &mut VectorcraftApp| app.run("threeD.addGraphic", json!({"name": "Existing Graphic"})).unwrap(); + add_existing(&mut app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + add_existing(&mut app); + assert_eq!(first.0, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + + let mut p = Panel::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Existing Graphic").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphics accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphics withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 1, "the foreign drop adds no symbol from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Existing Graphic", egui::Modifiers::NONE); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 2, "a same-document drop still makes a graphic"); +} + #[test] fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { let (mut app, _) = materials_app(); From 909895a6fe35003e0616eebf4fb17862a627d09a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:26:26 -0800 Subject: [PATCH 70/84] Scope Other Library replies to the Recolor opening --- crates/ui-egui/src/dialogs/recolor.rs | 15 ++++++++---- crates/ui-egui/src/tests/recolor.rs | 33 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e9c0760844..3768c182d2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1505,6 +1505,7 @@ impl Feed { /// What the pump works on with the app, out of the host: the values, their steps and what `show` /// asked for. struct Work { + opening: Arc<()>, fields: Fields, steps: Steps, filed: Filed, @@ -1544,7 +1545,7 @@ impl Work { randomize(app, &mut self.fields, sb); } if filed.library { - pick_library(app); + pick_library(app, Arc::clone(&self.opening)); } let d = &mut self.fields; if let Some(before) = filed.edited { @@ -1591,16 +1592,16 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. -fn pick_library(app: &mut VectorcraftApp) { +fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); - // PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| { + // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. + crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("swatch.library.load", json!({ "path": path }))?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { - if let Some(d) = host.get_mut::() { + if let Some(d) = host.get_mut_by_id::(dialog_id(KIND)).filter(|d| Arc::ptr_eq(&opening, &d.opening)) { d.fields.fields.insert("limitTo".into(), library); } }); @@ -1765,6 +1766,8 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { /// commits the recolour. pub(crate) struct RecolorDialog { id: DialogId, + /// The identity of this opening, since Recolor Artwork reuses its dialog ID. + opening: Arc<()>, fields: Fields, steps: Steps, held: HeldAnswer, @@ -1787,6 +1790,7 @@ impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { id: dialog_id(KIND), + opening: Arc::new(()), feed: Feed::of(app, &fields), steps: Steps::opened(snapshot(&fields)), fields, @@ -1803,6 +1807,7 @@ impl RecolorDialog { /// The values, steps and requests, for the pump to work on with the app. fn take_work(&mut self) -> Work { Work { + opening: Arc::clone(&self.opening), fields: std::mem::take(&mut self.fields), steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())), filed: std::mem::take(&mut self.filed), diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index b56303f960..b4fa530205 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -447,6 +447,39 @@ fn a_gray_row_keeps_the_hsb_sliders_while_it_is_edited() { assert_eq!(field(&r, "sliderMode"), json!("hsb")); } +#[test] +fn other_library_picker_only_limits_the_recolor_opening_that_requested_it() { + let path = vectorcraft_testkit::temp_dir("recolor-other-library").join("Recolor Test.gpl"); + std::fs::write(&path, "GIMP Palette\nName: Recolor Test\n#\n12 34 56 Test Color\n").unwrap(); + let path = path.to_str().unwrap(); + for reopen in [true, false] { + let mut r = open(app(), json!({"colors": ["#123456"], "library": "document"})); + let picker = super::picks::scripted(&mut r.app()); + r.settled(); + tap(&mut r, "Other Library…"); + assert_eq!(picker.requests().len(), 1, "the dialog asked for a file"); + if reopen { + r.cancel(); + assert!(!r.is_open(), "the first opening closed while its answer was pending"); + r.app().run("ui.recolorDialog", json!({"colors": ["#abcdef"], "library": "document"})).unwrap(); + r.settled(); + } + assert_eq!(field(&r, "limitTo"), "document"); + + picker.answer(&[path]); + crate::file_asks::poll(&mut r.app()); + r.settled(); + let libraries = r.app().run("swatch.library.list", json!({})).unwrap(); + let imported = libraries["libraries"].as_array().unwrap().iter().find(|lib| lib["category"] == "loaded").expect("the library still loads"); + if reopen { + assert_eq!(field(&r, "limitTo"), "document", "the reopened dialog keeps its own Limit to Library choice"); + } else { + assert_eq!(field(&r, "limitTo"), imported["id"], "an answer for the current opening selects its library"); + } + r.cancel(); + } +} + /// With Limit to Library, a row whose new color is a spot color of the library shows Tint, whose T /// slider sets the row's tint of it; OK links the art to the spot color at that tint. #[test] From 37ec4c7a1a806992481e45b427f882566c533c15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:25 -0800 Subject: [PATCH 71/84] Scope texture replies to the Effect Gallery opening --- crates/ui-egui/src/dialogs/effect_gallery.rs | 42 ++++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6fc5ad7813..3b7116e63a 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,6 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -117,7 +118,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let shown = dialogs.with(|host| { host.get_mut_by_id::(id).map(|dialog| { let visible = dialog.entries(true); - (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), dialog.asked.take()) + let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); + (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) }) }); let Some((on, batch, asked)) = shown else { @@ -127,18 +129,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { // `run` reports a failed preview itself. let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); app.effect_dialogs.gallery = Some(open); - if let Some(layer) = asked { - ask_texture(app, id, layer); + if let Some((opening, layer)) = asked { + ask_texture(app, id, opening, layer); } } -/// Asks for the image Load Texture reads into the layer `layer`. The answer finds the layer by its own id, wherever -/// it moved, and is dropped for a layer deleted since or a gallery that closed (a layer id is never used twice). -fn ask_texture(app: &mut VectorcraftApp, id: DialogId, layer: LayerId) { +/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. +fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { - if let Some(dialog) = host.get_mut_by_id::(id) { + if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { dialog.answer_texture(layer, fields); } }); @@ -234,6 +235,8 @@ fn entries_of(layers: &[EffectLayer], index: &FilterIndex, visible_only: bool) - /// [`FilterGallerySession`], with a preview of the visible layers and OK held for [`commit`]. pub(crate) struct EffectGalleryDialog { id: DialogId, + /// Dialog IDs and layer IDs can both be reused when the gallery opens again. + opening: Arc<()>, open: bool, catalog: Catalog, index: FilterIndex, @@ -255,6 +258,7 @@ impl EffectGalleryDialog { let session = FilterGallerySession::new(&first, &catalog); EffectGalleryDialog { id: dialog_id(KEY), + opening: Arc::new(()), open: true, catalog, index, @@ -652,8 +656,7 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); } - /// Load Texture… in the Settings, answered after the stack changed: the image goes into the layer that asked - /// wherever it moved, and an answer for a deleted layer is dropped. + /// A delayed Load Texture… reply follows its layer when it moves and is dropped when the layer or its gallery closes. #[test] fn settings_load_texture_answers_into_the_gallery() { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; @@ -677,10 +680,13 @@ mod tests { }) .collect() }; - // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the stack before the answer. - let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&VectorcraftApp)| { + let rough_pastels = || { let layer = json!({ "filter": "artistic.roughPastels", "visible": true, "params": {} }); - set(app, &ctx, "effects", json!([layer, layer])); + json!([layer, layer]) + }; + // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the gallery before the answer. + let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&mut VectorcraftApp)| { + set(app, &ctx, "effects", rough_pastels()); set(app, &ctx, "select", json!(row)); // The Texture row's Browse press, as the dialog's pass records it. app.dialogs().unwrap().with(|host| { @@ -696,6 +702,18 @@ mod tests { assert_eq!(ask(&mut app, 1, &|_| {}), [false, true], "the selected layer asked"); assert_eq!(ask(&mut app, 0, &|app| set(app, &ctx, "move", json!({"from": 0, "to": 1}))), [false, true], "the layer that asked moved"); assert_eq!(ask(&mut app, 1, &|app| set(app, &ctx, "delete", json!(true))), [false], "the layer that asked was deleted"); + let reopen = |app: &mut VectorcraftApp| { + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(app, &ctx); + super::open(app, &json!({})).unwrap(); + }; + // Both openings start with identical stacks, which gives their corresponding layers the same session-local IDs. + reopen(&mut app); + let answers = ask(&mut app, 0, &|app| { + reopen(app); + set(app, &ctx, "effects", rough_pastels()); + }); + assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } } From b450c47f7eda2884f7667163491f0f48a49c0e0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:36 -0800 Subject: [PATCH 72/84] Cancel PDF page options when Escape shares the OK frame --- crates/ui-egui/src/dialogs/import_pdf.rs | 6 ++-- .../ui-egui/src/dialogs/tests_import_pdf.rs | 35 +++++++++++++------ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 99ce30805d..f230c01ea3 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,11 +372,13 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } + if out.closed.is_some() { + return Some(DialogResult::Cancel); + } if out.picked == Some(0) && !waiting { self.ok(); - return None; } - out.closed.map(|_| DialogResult::Cancel) + None } } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 4e9008a734..c748aa9d81 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -73,7 +73,7 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } -fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { +fn click_page_footer_ok(app: VectorcraftApp, dismiss: bool) -> egui_kittest::Harness<'static, VectorcraftApp> { let mut fonts = false; let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { @@ -87,21 +87,36 @@ fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, V app, ); h.run_steps(4); - h.get_by_label("OK").click(); + if dismiss { + let pos = h.get_by_label("OK").rect().center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.hover_at(pos); + h.event(button(true)); + h.step(); + h.input_mut().events.extend([ + button(false), + egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + ]); + } else { + h.get_by_label("OK").click(); + } h.run_steps(4); assert!(!is_open(h.state())); h } #[test] -fn pdf_page_footer_ok_opens_the_chosen_range() { - let mut app = app(); - io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); - set(&mut app, "allPages", json!(false)); - set(&mut app, "range", json!("2-3")); +fn pdf_page_footer_ok_opens_the_chosen_range_unless_dismissed() { + for dismiss in [false, true] { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); - let h = click_page_footer_ok(app); - assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); + let h = click_page_footer_ok(app, dismiss); + let expected: &[f64] = if dismiss { &[400.0] } else { &[200.0, 300.0] }; + assert_eq!(artboard_widths(h.state()), expected); + } } #[test] @@ -267,7 +282,7 @@ fn pdf_page_footer_ok_places_the_chosen_page() { set(&mut app, "page", json!(2)); set(&mut app, "cropTo", json!("art")); - let h = click_page_footer_ok(app); + let h = click_page_footer_ok(app, false); let (_, bounds) = placed(h.state()); assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); } From a67e60394404d830ebf65648b24c88cd19d2e4f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:36 -0800 Subject: [PATCH 73/84] Cancel a Graph design when Escape shares the OK frame --- crates/ui-egui/src/dialogs/graph_design.rs | 28 +++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index f361b5f8c6..cf0c4dc6e1 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,12 +519,14 @@ impl GraphDesignDialog { } true }); + if shown.closed.is_some() { + return Some(DialogResult::Cancel); + } if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); - return None; } - shown.closed.map(|_| DialogResult::Cancel) + None } } @@ -880,8 +882,8 @@ mod tests { } #[test] - fn graph_design_footer_ok_applies_column_and_marker_designs() { - for (graph_type, command) in [("column", "graph.column"), ("line", "graph.marker")] { + fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { + for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { let (mut app, ctx) = app_with_design(); select_graph(&mut app, graph_type); crate::menus::invoke(&mut app, command, json!({})); @@ -900,12 +902,26 @@ mod tests { app, ); h.run_steps(4); - h.get_by_label("OK").click(); + if dismiss { + let pos = h.get_by_label("OK").rect().center(); + let button = + |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.hover_at(pos); + h.event(button(true)); + h.step(); + h.input_mut().events.extend([ + button(false), + egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + ]); + } else { + h.get_by_label("OK").click(); + } h.run_steps(4); let app = h.state_mut(); assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); - assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], "New Design"); + let expected = if dismiss { Value::Null } else { json!("New Design") }; + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], expected); } } From f4704bb688be422a358207ebb6e6f547e2d3f43d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:35:37 -0800 Subject: [PATCH 74/84] Scripts: reject protected page-item mutations --- crates/engine/src/script/dom.rs | 35 ++++++++++++------- crates/engine/src/tests/script_dom.rs | 48 +++++++++++++++++++++++++++ docs/mcp.md | 6 ++-- docs/target-app-parity.md | 2 ++ 4 files changed, 77 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9c137c96bd..1f54403017 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1599,16 +1599,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in -/// is hidden or locked. Its name and note may still change. -fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { +/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on +/// locked artboards. Names and notes may still change. +fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); - d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) { + Some("a layer it is in is hidden or locked") + } else if on_locked_artboard(h, st, item.id) { + Some("it is on a locked artboard") + } else { + None + }; + why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why)) }); match refused { - Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))), None => Ok(()), } } @@ -1619,7 +1626,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1629,7 +1636,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1657,7 +1664,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { (now, keeps_other) }); if now.is_none() || keeps_other { - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; } set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } @@ -1741,7 +1748,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); @@ -1778,7 +1786,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { @@ -2024,7 +2033,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused, and so is an object in a hidden or locked layer. +/// compound path is refused. The item must be selectable and outside hidden or locked layers and +/// locked artboards. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -2037,7 +2047,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..9687a4a94f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1325,6 +1325,54 @@ fn duplicate_refuses_hidden_or_locked_art() { assert!(order.contains(&a) && order.contains(&b)); } +#[test] +fn setters_refuse_art_on_a_locked_artboard() { + let (mut s, _, _) = doc(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], refused = [];\ + var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\ + function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\ + function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\ + for(var i=0;i