From 4338ef75e35e1f92fa89e013a2770ca22cdd5867 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 17:28:38 -0500 Subject: [PATCH 01/50] MCP: render_preview and window captures decode the app's PNG under size limits (#5445) --- crates/mcp/src/tools/dispatch.rs | 3 ++- crates/mcp/src/tools/handlers.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 7c91c9c8b2..9e3af3dbaa 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -452,7 +452,8 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result { let r = b.call("ui.render", p)?; let encoded = r.get("pngBase64").and_then(Value::as_str).ok_or("renderer returned no image")?; let png = vectorcraft_format::base64_decode(encoded).ok_or("renderer returned bad base64")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read preview: {e}"))?; + // The render was asked for at most 4096 a side. + let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?; let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img }; let mut out = std::io::Cursor::new(Vec::new()); img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?; diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index c9d203c6b3..ea2c6ec706 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -442,12 +442,27 @@ pub(super) fn max_side(a: &Args) -> Result, String> { } } +/// The longest side of a window capture that is decoded (a screen is never wider). +const MAX_CAPTURE_SIDE: u32 = 16_384; + +/// `png` decoded, refused when a side is longer than `side` or the decode needs more than 256 MiB: +/// the picture is the app's reply, and its header names the size it is decoded at. +pub(super) fn decode_png(png: &[u8], side: u32) -> Result { + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(side); + limits.max_image_height = Some(side); + limits.max_alloc = Some(256 << 20); + reader.limits(limits); + reader.decode() +} + /// A window capture with `max_side`: scaled down when its longer side is larger, with its own size /// in `capturedWidth` / `capturedHeight` and the returned image's in `width` / `height`. Without /// `max_side` the capture and `info` stay as they are. fn fit_capture(png: Vec, max: Option, info: &mut Value) -> Result, String> { let Some(max) = max else { return Ok(png) }; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read capture: {e}"))?; + let img = decode_png(&png, MAX_CAPTURE_SIDE).map_err(|e| format!("read capture: {e}"))?; info["capturedWidth"] = json!(img.width()); info["capturedHeight"] = json!(img.height()); if img.width().max(img.height()) <= max { @@ -472,3 +487,17 @@ pub(super) fn image_result(png: &[u8], info: Value) -> ToolResult { is_error: false, } } + +#[cfg(test)] +mod decode_tests { + use super::decode_png; + + #[test] + fn a_picture_with_a_side_past_the_limit_is_not_decoded() { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::new(200, 10).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let png = png.into_inner(); + assert!(decode_png(&png, 100).is_err()); + assert_eq!(decode_png(&png, 200).unwrap().width(), 200); + } +} From c6e47fece3098aa39e0f42e27c5363bf50046c6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:09:51 -0800 Subject: [PATCH 02/50] Render: keep the automatic thread helper out of Wasm libraries --- crates/render/src/threads.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/render/src/threads.rs b/crates/render/src/threads.rs index dfd6bf757d..1070c29c6a 100644 --- a/crates/render/src/threads.rs +++ b/crates/render/src/threads.rs @@ -49,6 +49,7 @@ pub fn default_threads() -> u16 { /// [`default_threads`] when automatic, on `cpus` processors of which the process may use `usable` /// (0 = all). +#[cfg(any(test, not(target_arch = "wasm32")))] fn automatic_threads(cpus: usize, usable: usize) -> u16 { let cores = if usable == 0 { cpus } else { cpus.min(usable) }; (cores.saturating_sub(1)).min(8) as u16 From 1ad74d1ddffa0aafae21b794acabee0fda634897 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:52:40 -0800 Subject: [PATCH 03/50] Type: reject doubly signed OpenType feature tags --- crates/engine/src/cmd/textstyles/tests.rs | 15 +++++++++++++++ crates/text/src/features.rs | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 90bb32bbbb..19da4c8ab0 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -335,6 +335,21 @@ fn character_style_color_and_features_are_checked() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +#[test] +fn text_style_rejects_doubly_signed_feature_tags() { + let (mut s, id) = session_with_text("Text"); + let before = runs(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + for cmd in ["text.setStyle", "text.setRangeStyle"] { + for tag in ["--liga", "+-dnom", "-+ss01", "++liga"] { + let error = s.execute(cmd, &json!({"id": id, "start": 0, "end": 4, "features": [tag]})).unwrap_err().to_string(); + assert!(error.contains(&format!("`{tag}`")), "{cmd}: {error}"); + } + } + assert_eq!(runs(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + #[test] fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() { let (mut s, _) = session_with_text("Text"); diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index 3a75f25791..eac3b3c3f4 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -146,7 +146,7 @@ impl OtFeatures { /// Is `tag` (optionally prefixed with `-` or `+`) one this set understands? pub fn known_tag(tag: &str) -> bool { - let t = tag.trim_start_matches(['-', '+']); + let t = tag.strip_prefix(['-', '+']).unwrap_or(tag); matches!(t, "liga" | "calt" | "dlig" | "smcp" | "frac" | "onum" | "tnum" | "ordn" | "swsh") || EXTRA_FEATURES.contains(&t) } @@ -306,6 +306,9 @@ mod tests { assert!(OtFeatures::known_tag(t), "{t}"); } assert!(!OtFeatures::known_tag("ss21")); + for tag in ["--liga", "+-dnom", "-+ss01", "++liga"] { + assert!(!OtFeatures::known_tag(tag), "{tag}"); + } let o = OtFeatures::from_tags(["ss03", "pnum", "sups", "-liga"]); assert_eq!(o.to_tags(), vec!["-liga", "ss03", "pnum", "sups"]); assert_eq!(OtFeatures::from_tags(["ss03", "-ss03"]).to_tags(), Vec::::new(), "turned off again"); From 9250f2bfe6b20d74a698e49d292f92b4db9fae3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 09:47:07 -0800 Subject: [PATCH 04/50] Clear stale Find Font warning after successful replacement --- crates/ui-egui/src/app/commands.rs | 6 ++++++ crates/ui-egui/src/find_font.rs | 12 +++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 08e7960b3e..775248a611 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -188,6 +188,12 @@ impl VectorcraftApp { r.insert(0, font.to_string()); r.truncate(MAX_RECENT_FONTS); } + if id == "text.replaceFont" + && v.get("warning").is_none() + && self.ui.status.starts_with("some text is hidden or locked, so its font wasn't replaced") + { + self.ui.status.clear(); + } // A command's warning (Rasterize's when an image couldn't be decoded) shows in the // status bar, as a tool preview's does. if let Some(w) = v.get("warning").and_then(Value::as_str) { diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index af9a83af0b..588869226e 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -286,7 +286,7 @@ mod tests { /// Change All leaves locked text in its font, and the status bar says so. #[test] - fn change_all_says_when_locked_text_keeps_its_font() { + fn change_all_clears_the_skip_warning_after_unlocking_text() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); @@ -298,6 +298,16 @@ mod tests { assert_eq!(r["runs"], 0, "{r}"); assert_eq!(fonts(&mut app)[0]["family"], "Missing Family"); assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); + app.run("object.unlockAll", json!({})).unwrap(); + assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); + let r = change(&mut app, &d, &from, true).unwrap(); + assert_eq!(r["runs"], 1, "{r}"); + assert!(r.get("warning").is_none(), "{r}"); + assert_eq!(app.ui.status, ""); + app.ui.status = "Saved another document".into(); + let r = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r["runs"], 0, "{r}"); + assert_eq!(app.ui.status, "Saved another document"); } #[test] From cdd014c4e7b211adec4ada82b82fc6cb683eef3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:05:44 -0800 Subject: [PATCH 05/50] Type: the stop inside an upright ligature on a vertical path follows its drawn cell On a path, vertical type turns an upright glyph about its pen, so its cell runs from 0.12 em before the pen to 0.88 em after it without the font's vertical metrics. The ligature caret, a click and the selection measured the cell from the pen instead. They now take the cell where the glyph's transform draws it, with its placement, baseline shift, Horizontal Scale and Skew. --- crates/text/src/layout.rs | 15 ++++++ crates/text/src/lib.rs | 4 +- crates/text/src/tests/ligature_carets.rs | 60 ++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 9d7ed666ea..38688b8ce5 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -382,6 +382,21 @@ impl Ctx<'_> { } else { 0.0 }; + // On a path, an upright glyph turns about its pen: its cell runs along the path between + // where the glyph's transform sets the cell's foot and its top, moved by the shaper's + // placement and a baseline shift, and slanted by the path's effect. + let (width, width_start) = match (upright && self.on_path, g.sy) { + (true, sy) if sy != 0.0 => { + // In font units, with the Proportional Metrics change to its length. + let (cell, top) = upright_extent(g); + let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance) / sy; + let tangent = Vec2::new(angle.cos(), angle.sin()); + let along = |y: f64| (m * Point::new(0.0, y) - origin).dot(tangent); + let (start, end) = (along(cell + proportional - top), along(-top)); + if start.is_finite() && end > start { (end - start, start) } else { (width, width_start) } + } + _ => (width, width_start), + }; if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) { self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) }); } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 1d32036076..a49e187aed 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -166,7 +166,9 @@ pub struct PositionedGlyph { /// in text space: the font's placement of the glyph (`GPOS` x placement), less a leading space /// taken off, plus the manual kerning of right-to-left text, which moves the glyph right so that /// the space it adds lies on the glyph's left. 0 for a glyph standing upright or set across the - /// column in vertical type, and for an inline graphic. + /// column in vertical type, and for an inline graphic. An upright glyph in vertical type on a + /// path turns about its pen, and its cell starts one cell length before the cell's top: 0.12 em + /// before the pen without the font's vertical metrics. pub width_start: f64, } diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index ee42864c58..a0a194d9b1 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -459,6 +459,66 @@ fn an_upright_ligature_takes_its_caret_down_its_cell() { assert!((at(900) - 0.5).abs() < 1e-9, "{}", at(900)); } +/// On a path, an upright ligature in vertical type turns about its pen, so its cell runs from +/// 0.12 em before the pen to 0.88 em after it, with or without the font's vertical metrics. The +/// inner stop lies at the middle of that cell, and the first character's selection ends there. +#[test] +fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() { + for (font, family) in [(ligature_caret_font(None), LIGATURE_CARET_FAMILY), (vertical_ligature_caret_font(900), VERTICAL_LIGATURE_CARET_FAMILY)] { + let db = db_with(font); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1000.0, 0.0)); + let mut t = point("fi", family); + t.vertical = true; + t.runs[0].style.standard_vertical_roman = true; + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let l = layout(&db, &t); + assert!(l.on_path); + let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + assert_eq!(g.carets, vec![(1, 0.5)], "{family}"); + assert!((g.width - 100.0).abs() < 1e-9 && (g.width_start + 12.0).abs() < 1e-9, "{family}: {} {}", g.width, g.width_start); + let x = |b| caret_position(&l, b).0.x - g.origin.x; + assert!((x(1) - 38.0).abs() < 1e-6, "{family}: {}", x(1)); + let q = selection_quads(&l, 0, 1); + assert_eq!(q.len(), 1, "{q:?}"); + assert!(((q[0][1] - q[0][0]).hypot() - 38.0).abs() < 1e-6, "{family}: {q:?}"); + // A baseline shift moves the turned glyph along the path, and its stop with it. + let ink = g.outline.bounding_box().x0; + t.runs[0].style.baseline_shift = 10.0; + let l = layout(&db, &t); + let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let moved = s.outline.bounding_box().x0 - ink; + assert!(moved.abs() > 1.0, "{family}: the shift moves the glyph along the path: {moved}"); + let stop = caret_position(&l, 1).0.x - s.origin.x; + assert!((stop - 38.0 - moved).abs() < 1e-6, "{family}: {stop} against {}", 38.0 + moved); + // Horizontal Scale widens the glyph across the path; its stop stays inside the glyph. + t.runs[0].style.baseline_shift = 0.0; + t.runs[0].style.h_scale = 200.0; + let l = layout(&db, &t); + let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let bounds = s.outline.bounding_box(); + let stop = caret_position(&l, 1).0.x - s.origin.x; + assert!(bounds.x0 < stop && stop < bounds.x1 && stop > 0.0, "{family}: {stop} outside {bounds:?}"); + t.runs[0].style.h_scale = 100.0; + // Skew on a slanted path: the stop stays inside the drawn glyph along the path. + let mut slant = BezPath::new(); + slant.move_to((0.0, 0.0)); + slant.line_to((1000.0, 1000.0)); + t.runs[0].style.baseline_shift = 0.0; + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&slant), start: 0.0, end: None }; + t.path_effect = vectorcraft_doc::PathEffect::Skew; + let l = layout(&db, &t); + let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let tangent = Vec2::new(s.angle.cos(), s.angle.sin()); + let ink = s.outline.elements().iter().filter_map(|el| el.end_point()).map(|p| (p - s.origin).dot(tangent)); + let (lo, hi) = ink.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d))); + let (a, b) = caret_position(&l, 1); + let stop = (a.midpoint(b) - s.origin).dot(tangent); + assert!(lo < stop && stop < hi, "{family}: {stop} outside {lo}..{hi}"); + } +} + /// Tracking that makes an upright ligature's advance negative leaves it upright: it keeps its /// caret down its cell, and its cell starts where it does without tracking, with or without the /// font's vertical metrics. From 817bfceda381e7ff47ce738748a9ac7f08bd08ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 14:25:06 -0800 Subject: [PATCH 06/50] Resolve GDEF contour-point ligature carets --- crates/text/src/fontdb/face.rs | 87 ++++++++++++++++++++---- crates/text/src/tests/ligature_carets.rs | 43 ++++++++++++ docs/target-app-parity.md | 7 +- 3 files changed, 123 insertions(+), 14 deletions(-) diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 506c3b1bf1..ba11c4ae92 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -3,6 +3,61 @@ use super::names::{localized, name}; use super::traits::{FaceKeys, FontTraits}; use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId}; +/// Unhinted TrueType contour points in glyph order, including transformed composite components. +/// A cap and depth bound keep damaged fonts from making caret lookup unbounded. +fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize) -> Option> { + use skrifa::raw::TableProvider; + use skrifa::raw::tables::glyf::{Anchor, CompositeGlyphFlags, Glyph}; + + const MAX_DEPTH: usize = 16; + const MAX_POINTS: usize = 65_536; + if depth >= MAX_DEPTH { + return None; + } + let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?; + match glyph { + Glyph::Simple(simple) => { + if simple.num_points() > MAX_POINTS { + return None; + } + let points: Vec<_> = simple.points().map(|p| (f64::from(p.x), f64::from(p.y))).collect(); + (points.len() == simple.num_points()).then_some(points) + } + Glyph::Composite(composite) => { + let mut points = Vec::new(); + for component in composite.components() { + let child = outline_points(font, GlyphId::new(component.glyph.to_u32()), depth + 1)?; + let t = component.transform; + let xx = f64::from(t.xx.to_f32()); + let xy = f64::from(t.xy.to_f32()); + let yx = f64::from(t.yx.to_f32()); + let yy = f64::from(t.yy.to_f32()); + let transformed: Vec<_> = child.into_iter().map(|(x, y)| (xx * x + xy * y, yx * x + yy * y)).collect(); + let (dx, dy) = match component.anchor { + Anchor::Offset { x, y } => { + let (x, y) = (f64::from(x), f64::from(y)); + if component.flags.contains(CompositeGlyphFlags::SCALED_COMPONENT_OFFSET) { + (xx * x + xy * y, yx * x + yy * y) + } else { + (x, y) + } + } + Anchor::Point { base, component } => { + let (bx, by) = *points.get(usize::from(base))?; + let (cx, cy) = *transformed.get(usize::from(component))?; + (bx - cx, by - cy) + } + }; + if transformed.len() > MAX_POINTS.saturating_sub(points.len()) { + return None; + } + points.extend(transformed.into_iter().map(|(x, y)| (x + dx, y + dy))); + } + Some(points) + } + } +} + /// The family used when a requested family is unknown (Illustrator's Myriad Pro analogue). pub const FALLBACK_FAMILY: &str = "Source Sans 3"; @@ -244,11 +299,11 @@ impl FontFace { /// ), one between each two /// characters the glyph stands for, each an x in horizontal text and a y (up from the baseline) /// in vertical text. A coordinate with a variation index (format 3 in a variable font) takes its - /// delta from the `GDEF` item variation store at the face's location; a device table's - /// adjustments for pixel sizes are not applied. `None` when the font lists no carets for the - /// glyph, lists a number other than `count`, gives one by a contour point, or gives one a - /// variation index whose delta can't be read. - fn ligature_caret_coordinates(&self, gid: u32, count: usize) -> Option> { + /// delta from the `GDEF` item variation store at the face's location. Format 2 uses the + /// unhinted outline point at the font's default variation location. Device-table adjustments + /// for pixel sizes are not applied. `None` when the font lists no carets for the glyph, lists + /// a number other than `count`, or gives a coordinate that cannot be resolved. + fn ligature_caret_coordinates(&self, gid: u32, count: usize, vertical: bool) -> Option> { use skrifa::raw::TableProvider; use skrifa::raw::tables::gdef::CaretValue; use skrifa::raw::tables::layout::DeviceOrVariationIndex; @@ -280,17 +335,25 @@ impl FontFace { } } } - CaretValue::Format2(_) => None, + CaretValue::Format2(v) => { + // Raw glyf points have no variation deltas applied. Do not use one at a + // non-default location, where it could put the caret in the wrong place. + if self.location.coords().iter().any(|c| c.to_f32() != 0.0) { + return None; + } + let point = outline_points(&font, GlyphId::new(gid), 0)?.get(usize::from(v.caret_value_point_index())).copied()?; + Some(if vertical { point.1 } else { point.0 }) + } }) .collect::>>()?; (!carets.is_empty()).then_some(carets) } /// The caret positions inside ligature glyph `gid` set across, in font units from its left /// edge, left to right: the x coordinates of the font's ligature caret list. `None` when the - /// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour - /// point, or gives positions that are not increasing inside the glyph's advance. + /// font lists no carets for the glyph, lists a number other than `count`, or gives positions + /// that are not increasing inside the glyph's advance. pub fn ligature_carets(&self, gid: u32, count: usize) -> Option> { - let carets = self.ligature_caret_coordinates(gid, count)?; + let carets = self.ligature_caret_coordinates(gid, count, false)?; let advance = self.advance(gid); let inside = carets.iter().all(|x| *x > 0.0 && *x < advance) && carets.windows(2).all(|w| w[0] < w[1]); inside.then_some(carets) @@ -298,10 +361,10 @@ impl FontFace { /// The caret positions inside ligature glyph `gid` standing upright in vertical type, in font /// units down from the top of its cell, top to bottom: the y coordinates of the font's ligature /// caret list, for a cell `cell` long whose top is `top` above the baseline. `None` when the - /// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour - /// point, or gives positions that are not increasing inside the cell. + /// font lists no carets for the glyph, lists a number other than `count`, or gives positions + /// that are not increasing inside the cell. pub fn vertical_ligature_carets(&self, gid: u32, count: usize, top: f64, cell: f64) -> Option> { - let carets = self.ligature_caret_coordinates(gid, count)?; + let carets = self.ligature_caret_coordinates(gid, count, true)?; let inside = carets.iter().all(|y| *y < top && *y > top - cell) && carets.windows(2).all(|w| w[0] < w[1]); inside.then(|| carets.iter().rev().map(|y| top - y).collect()) } diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index a0a194d9b1..801713a351 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -19,6 +19,49 @@ fn db_with(font: Option>) -> FontDb { db } +/// Put a contour-point caret on the existing test ligature without changing its outline. +fn contour_caret_font(point_index: u16) -> Vec { + use write_fonts::FontBuilder; + use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph}; + use write_fonts::tables::layout::CoverageFormat1 as WriteCoverage; + use write_fonts::types::{GlyphId16, Tag}; + + let base = ligature_caret_font(None).expect("test font builds"); + let font = skrifa::FontRef::new(&base).expect("test font parses"); + let gid = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); + let mut builder = FontBuilder::new(); + let list = LigCaretList::new(WriteCoverage::new(vec![GlyphId16::new(gid)]).into(), vec![LigGlyph::new(vec![CaretValue::format_2(point_index)])]); + builder.add_table(&Gdef::new(None, None, Some(list), None)).expect("GDEF builds"); + for record in font.table_directory.table_records() { + let tag = Tag::new(&record.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(record.tag()).expect("base table reads").as_bytes()); + } + } + builder.build() +} + +#[test] +fn a_contour_point_caret_uses_its_unhinted_x_and_y() { + use skrifa::raw::TableProvider; + use skrifa::raw::tables::glyf::Glyph; + + let base = ligature_caret_font(None).expect("test font builds"); + let font = skrifa::FontRef::new(&base).expect("test font parses"); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let outline = font.loca(None).expect("loca reads").get(skrifa::GlyphId::new(gid), &font.glyf().expect("glyf reads")).expect("glyph reads"); + let Glyph::Simple(simple) = outline.into_glyph().expect("glyph has an outline") else { panic!("W is simple") }; + let (point_index, point) = + simple.points().enumerate().find(|(_, p)| p.x > 0 && p.x < 500 && p.y > -500 && p.y < 1000).expect("W has an interior contour point"); + let db = db_with(Some(contour_caret_font(u16::try_from(point_index).unwrap()))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").unwrap(); + assert_eq!(face.ligature_carets(gid, 1), Some(vec![f64::from(point.x)])); + assert_eq!(face.vertical_ligature_carets(gid, 1, 1000.0, 1500.0), Some(vec![1000.0 - f64::from(point.y)])); + + let bad = db_with(Some(contour_caret_font(u16::MAX))); + assert_eq!(bad.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(gid, 1), None); +} + fn point(text: &str, family: &str) -> TextObject { TextObject::point(Point::ZERO, text, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }) } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4370a3a0c..55dd266430 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,9 +1,11 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (ligature contour-point carets; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence +Ligature caret stops use a font's GDEF contour-point positions in horizontal and vertical text. They use unhinted outlines at the default variation location; invalid point indices use the existing evenly divided fallback. Scores and estimates are unchanged. + Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. **Feature evidence last updated:** 2026-11-03. @@ -21,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Ligature caret stops use GDEF contour-point positions in horizontal and vertical type at the font's default variation location; invalid point indices keep the evenly divided fallback. Scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | @@ -775,7 +778,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). While a Type tool edits type, a click that lands on no type ends the editing without making new type, and that tool stays active; the next click makes new type (#2871, #2854). - Inside a ligature (one glyph for several characters, such as fi), the Type tool's caret, clicks, arrow keys and selection stop between its characters, at the font's ligature carets ([OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef)) or, when the font does not list one valid caret for each stop, at the glyph's width divided equally. + Inside a ligature (one glyph for several characters, such as fi), the Type tool's caret, clicks, arrow keys and selection stop between its characters, at the font's ligature carets ([OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef)) or, when the font does not list one valid caret for each stop, at the glyph's width divided equally. Contour-point carets use the font's unhinted outline at its default variation location; pixel-size device adjustments are not applied. Duplicate Artboards, the Artboard tool's Alt-drag and Paste give the new artboard an id that no other artboard has, also when an artboard's id is the largest possible value (#1718). Deleting the copy or the original then leaves the other's guides. - **Touch Type:** a click with the Touch Type tool (Shift+T) selects one character and shows a box around it. Dragging the box or its lower-left handle moves the character. The upper-left handle scales it vertically, the lower-right handle scales it horizontally, the upper-right handle scales it proportionally, and the upper-middle handle rotates it. Each drag is one undo step that sets the character's kerning, baseline shift, scales or rotation, and the type stays editable (`text.touchType`; behavior reference: [Touch Type tool](https://web.archive.org/web/20261007185617/https://helpx.adobe.com/illustrator/using/tool-techniques/touch-type-tool.html), [Add text with the Type, Area Type, and Touch Type tools](https://web.archive.org/web/20260926095922/https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-text-illustrator-text-tools.html)). Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. From 98ef01a6d397afddf5f401b3c203058aeea2f3cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:02:20 -0800 Subject: [PATCH 07/50] Type: bound the glyphs a contour-point caret lookup reads A composite glyph whose components expand into glyphs with no points could make the contour-point caret lookup read billions of glyphs. The whole lookup now shares a budget of 65,536 glyph reads and gives no caret when it runs out, so the caret falls back to dividing the advance. --- crates/text/src/fontdb/face.rs | 15 +++-- crates/text/src/tests/ligature_carets.rs | 73 ++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index ba11c4ae92..3ec57c9efb 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -3,9 +3,14 @@ use super::names::{localized, name}; use super::traits::{FaceKeys, FontTraits}; use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId}; +/// The most glyphs one [`outline_points`] lookup reads, composite components included. +const MAX_OUTLINE_VISITS: usize = 65_536; + /// Unhinted TrueType contour points in glyph order, including transformed composite components. -/// A cap and depth bound keep damaged fonts from making caret lookup unbounded. -fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize) -> Option> { +/// A point cap, a depth bound and `visits`, the number of glyphs the whole lookup may still read, +/// keep damaged fonts from making caret lookup unbounded. Callers start `visits` at +/// [`MAX_OUTLINE_VISITS`]. +fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits: &mut usize) -> Option> { use skrifa::raw::TableProvider; use skrifa::raw::tables::glyf::{Anchor, CompositeGlyphFlags, Glyph}; @@ -14,6 +19,7 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize) -> Opt if depth >= MAX_DEPTH { return None; } + *visits = visits.checked_sub(1)?; let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?; match glyph { Glyph::Simple(simple) => { @@ -26,7 +32,7 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize) -> Opt Glyph::Composite(composite) => { let mut points = Vec::new(); for component in composite.components() { - let child = outline_points(font, GlyphId::new(component.glyph.to_u32()), depth + 1)?; + let child = outline_points(font, GlyphId::new(component.glyph.to_u32()), depth + 1, visits)?; let t = component.transform; let xx = f64::from(t.xx.to_f32()); let xy = f64::from(t.xy.to_f32()); @@ -341,7 +347,8 @@ impl FontFace { if self.location.coords().iter().any(|c| c.to_f32() != 0.0) { return None; } - let point = outline_points(&font, GlyphId::new(gid), 0)?.get(usize::from(v.caret_value_point_index())).copied()?; + let mut visits = MAX_OUTLINE_VISITS; + let point = outline_points(&font, GlyphId::new(gid), 0, &mut visits)?.get(usize::from(v.caret_value_point_index())).copied()?; Some(if vertical { point.1 } else { point.0 }) } }) diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 801713a351..508bfae1c0 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -62,6 +62,79 @@ fn a_contour_point_caret_uses_its_unhinted_x_and_y() { assert_eq!(bad.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(gid, 1), None); } +/// [`contour_caret_font`] with its `glyf` and `loca` replaced: the ligature is a composite of +/// eight copies of a glyph that is itself eight copies of the next, 15 levels down to a glyph with +/// no contours. Every other glyph is empty. +fn composite_fan_caret_font() -> Vec { + use skrifa::raw::TableProvider; + use write_fonts::FontBuilder; + use write_fonts::types::Tag; + + const FAN: usize = 8; + const LEVELS: usize = 15; + let base = contour_caret_font(0); + let font = skrifa::FontRef::new(&base).expect("test font parses"); + let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); + let num_glyphs = font.maxp().expect("maxp reads").num_glyphs(); + let short_loca = font.head().expect("head reads").index_to_loc_format() == 0; + let levels: Vec = (1..num_glyphs).filter(|g| *g != ligature).take(LEVELS).collect(); + let composite = |child: u16| { + let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0]; + for i in 0..FAN { + // ARGS_ARE_XY_VALUES, plus MORE_COMPONENTS on all but the last; byte offsets of 0. + let flags: u16 = if i + 1 < FAN { 0x0022 } else { 0x0002 }; + data.extend(flags.to_be_bytes()); + data.extend(child.to_be_bytes()); + data.extend([0, 0]); + } + data + }; + let mut glyf = Vec::new(); + let mut offsets = vec![0usize]; + for gid in 0..num_glyphs { + if gid == ligature { + glyf.extend(composite(levels[0])); + } else if let Some(level) = levels.iter().position(|g| *g == gid) { + match levels.get(level + 1) { + Some(child) => glyf.extend(composite(*child)), + // No contours, a zero bounding box and no instructions. + None => glyf.extend([0u8; 12]), + } + } + offsets.push(glyf.len()); + } + let loca: Vec = if short_loca { + offsets.iter().flat_map(|o| u16::try_from(o / 2).expect("short offset").to_be_bytes()).collect() + } else { + offsets.iter().flat_map(|o| u32::try_from(*o).expect("long offset").to_be_bytes()).collect() + }; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"glyf"), glyf); + builder.add_raw(Tag::new(b"loca"), loca); + for record in font.table_directory.table_records() { + let tag = Tag::new(&record.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(record.tag()).expect("base table reads").as_bytes()); + } + } + builder.build() +} + +/// A contour-point caret on a composite that expands to billions of glyphs with no points gives +/// no caret, and quickly, rather than reading every one of them. +#[test] +fn a_contour_point_caret_on_a_huge_empty_composite_gives_up() { + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let (send, receive) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let db = db_with(Some(composite_fan_caret_font())); + let carets = db.face(LIGATURE_CARET_FAMILY, "Regular").map(|face| face.ligature_carets(gid, 1)); + let _ = send.send(carets); + }); + let carets = receive.recv_timeout(std::time::Duration::from_secs(30)).expect("the caret lookup finishes"); + assert_eq!(carets, Some(None)); +} + fn point(text: &str, family: &str) -> TextObject { TextObject::point(Point::ZERO, text, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }) } From 9fd7d0a7336f99101cc6469f8d7fe563afcd64c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:09:16 -0800 Subject: [PATCH 08/50] Type: place a contour-point caret on a composite as the outline is drawn With SCALED_COMPONENT_OFFSET, a component's offset now scales each axis by the length of that axis's basis vector, as the outline loader does, instead of going through the whole matrix. A rotated or skewed component's caret no longer lands away from its drawn point. UNSCALED_COMPONENT_OFFSET now turns the scaling off when both flags are set. --- crates/text/src/fontdb/face.rs | 7 +- crates/text/src/tests/ligature_carets.rs | 105 +++++++++++++++++------ 2 files changed, 84 insertions(+), 28 deletions(-) diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 3ec57c9efb..382b96da2f 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -42,8 +42,11 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits let (dx, dy) = match component.anchor { Anchor::Offset { x, y } => { let (x, y) = (f64::from(x), f64::from(y)); - if component.flags.contains(CompositeGlyphFlags::SCALED_COMPONENT_OFFSET) { - (xx * x + xy * y, yx * x + yy * y) + // Each axis of a scaled offset scales by the length of its basis vector, as + // in skrifa's outline loader. UNSCALED_COMPONENT_OFFSET turns the scaling off. + let offset_flags = CompositeGlyphFlags::SCALED_COMPONENT_OFFSET | CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET; + if component.flags & offset_flags == CompositeGlyphFlags::SCALED_COMPONENT_OFFSET { + (x * xx.hypot(xy), y * yx.hypot(yy)) } else { (x, y) } diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 508bfae1c0..929ba50bc1 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -62,43 +62,32 @@ fn a_contour_point_caret_uses_its_unhinted_x_and_y() { assert_eq!(bad.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(gid, 1), None); } -/// [`contour_caret_font`] with its `glyf` and `loca` replaced: the ligature is a composite of -/// eight copies of a glyph that is itself eight copies of the next, 15 levels down to a glyph with -/// no contours. Every other glyph is empty. -fn composite_fan_caret_font() -> Vec { +/// `count` glyph ids of [`contour_caret_font`] other than the ligature's. +fn spare_gids(count: usize) -> Vec { + let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); + (1..).filter(|g| *g != ligature).take(count).collect() +} + +/// [`contour_caret_font`], whose caret is the ligature's point 0, with its `glyf` and `loca` +/// replaced: each `(gid, data)` in `glyphs` gives that glyph's `glyf` data, and every other glyph +/// is empty. +fn glyf_caret_font(glyphs: &[(u16, Vec)]) -> Vec { use skrifa::raw::TableProvider; use write_fonts::FontBuilder; use write_fonts::types::Tag; - const FAN: usize = 8; - const LEVELS: usize = 15; let base = contour_caret_font(0); let font = skrifa::FontRef::new(&base).expect("test font parses"); - let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); let num_glyphs = font.maxp().expect("maxp reads").num_glyphs(); let short_loca = font.head().expect("head reads").index_to_loc_format() == 0; - let levels: Vec = (1..num_glyphs).filter(|g| *g != ligature).take(LEVELS).collect(); - let composite = |child: u16| { - let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0]; - for i in 0..FAN { - // ARGS_ARE_XY_VALUES, plus MORE_COMPONENTS on all but the last; byte offsets of 0. - let flags: u16 = if i + 1 < FAN { 0x0022 } else { 0x0002 }; - data.extend(flags.to_be_bytes()); - data.extend(child.to_be_bytes()); - data.extend([0, 0]); - } - data - }; let mut glyf = Vec::new(); let mut offsets = vec![0usize]; for gid in 0..num_glyphs { - if gid == ligature { - glyf.extend(composite(levels[0])); - } else if let Some(level) = levels.iter().position(|g| *g == gid) { - match levels.get(level + 1) { - Some(child) => glyf.extend(composite(*child)), - // No contours, a zero bounding box and no instructions. - None => glyf.extend([0u8; 12]), + if let Some((_, data)) = glyphs.iter().find(|(g, _)| *g == gid) { + glyf.extend(data); + // Keep every offset even for the short `loca` format. + if glyf.len() % 2 == 1 { + glyf.push(0); } } offsets.push(glyf.len()); @@ -120,6 +109,70 @@ fn composite_fan_caret_font() -> Vec { builder.build() } +/// [`glyf_caret_font`] whose ligature is a composite of eight copies of a glyph that is itself +/// eight copies of the next, 15 levels down to a glyph with no contours. +fn composite_fan_caret_font() -> Vec { + const FAN: usize = 8; + let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); + let levels = spare_gids(15); + let composite = |child: u16| { + let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0]; + for i in 0..FAN { + // ARGS_ARE_XY_VALUES, plus MORE_COMPONENTS on all but the last; byte offsets of 0. + let flags: u16 = if i + 1 < FAN { 0x0022 } else { 0x0002 }; + data.extend(flags.to_be_bytes()); + data.extend(child.to_be_bytes()); + data.extend([0, 0]); + } + data + }; + let mut glyphs = vec![(ligature, composite(levels[0]))]; + for (level, gid) in levels.iter().enumerate() { + match levels.get(level + 1) { + Some(child) => glyphs.push((*gid, composite(*child))), + // No contours, a zero bounding box and no instructions. + None => glyphs.push((*gid, vec![0; 12])), + } + } + glyf_caret_font(&glyphs) +} + +/// A contour-point caret on a composite's point uses the component offset the outline loader +/// uses. The ligature is one component, a glyph with a single point at (50, 0), turned a quarter +/// turn and scaled by 1.5 with a two-by-two matrix and placed at (100, 0). With +/// SCALED_COMPONENT_OFFSET the offset's x scales by the length of the x basis, 1.5, so the point +/// lands at x = 150; with UNSCALED_COMPONENT_OFFSET as well the offset stays (100, 0). +#[test] +fn a_contour_point_caret_on_a_composite_takes_its_scaled_offset() { + let gid = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"); + let [leaf] = spare_gids(1)[..] else { panic!("one spare glyph") }; + // One on-curve point at (50, 0) with word coordinates, and no instructions. + let mut point = vec![0, 1, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0x01]; + point.extend(50i16.to_be_bytes()); + point.extend(0i16.to_be_bytes()); + let composite = |offset_flags: u16| { + // ARG_1_AND_2_ARE_WORDS, ARGS_ARE_XY_VALUES and WE_HAVE_A_TWO_BY_TWO. + let flags = 0x0083 | offset_flags; + let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0]; + data.extend(flags.to_be_bytes()); + data.extend(leaf.to_be_bytes()); + data.extend(100i16.to_be_bytes()); + data.extend(0i16.to_be_bytes()); + // xx = 0, yx = 1.5, xy = -1.5, yy = 0 in F2Dot14. + for f2dot14 in [0x0000u16, 0x6000, 0xa000, 0x0000] { + data.extend(f2dot14.to_be_bytes()); + } + data + }; + let caret = |offset_flags: u16| { + let db = db_with(Some(glyf_caret_font(&[(gid, composite(offset_flags)), (leaf, point.clone())]))); + db.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(u32::from(gid), 1) + }; + // SCALED_COMPONENT_OFFSET, then with UNSCALED_COMPONENT_OFFSET too. + assert_eq!(caret(0x0800), Some(vec![150.0])); + assert_eq!(caret(0x1800), Some(vec![100.0])); +} + /// A contour-point caret on a composite that expands to billions of glyphs with no points gives /// no caret, and quickly, rather than reading every one of them. #[test] From 309b092f7249d440bab57b5d54d088bda9a81f37 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:51:59 -0800 Subject: [PATCH 09/50] Remove copied Action Options wording from documentation --- docs/ui-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26d3dd6790..77a9ca64a2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; the Action Options row cites the public Actions panel page; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The Action Options row cites the public Actions panel page and describes its controls. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | @@ -316,7 +317,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | | Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; the reference app's `.aia` files and Reset, Clear and Replace Actions remain | -| Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action") | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). The color shows nowhere until Button Mode exists | +| Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). The color shows nowhere until Button Mode exists | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | | Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode, which shows the color, remains | From 19edd2bcc9dc670814cc6717b3a9537e7ca54d4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:45:40 -0800 Subject: [PATCH 10/50] Docs: replace quoted help-page sentences with plain statements MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/mcp.md (dataset.import) and docs/gaps.md (Recolor Artwork › Assign, Average & Join) quoted sentences from the reference app's help pages. Each quote is replaced by a plain statement of the behavior, and each help-page link stays as the source. --- docs/gaps.md | 4 ++-- docs/mcp.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 8b707fd9f6..53b3e97f87 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -88,7 +88,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. -- **Done (part of #4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes ("double-click it and select a color in the Color Picker"). OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. A Lab new color is kept, but can't be typed yet: the picker's Lab fields work in RGB, as for fill and stroke. **Missing:** Lab entry in the picker, swatch libraries in the picker and the row's right-click menu (Pick from Swatches, Limit to Library). +- **Done (part of #4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. A Lab new color is kept, but can't be typed yet: the picker's Lab fields work in RGB, as for fill and stroke. **Missing:** Lab entry in the picker, swatch libraries in the picker and the row's right-click menu (Pick from Swatches, Limit to Library). - **Done (#3416):** Recolor Artwork Edit chips scroll to the last color while the heading, color wheel and actions stay visible. Screen resize and UI scaling, Preview, Confirm, Cancel, Undo and #1733 wheel drags are covered in `tests/recolor.rs`. No gap entry closed; estimates unchanged. @@ -143,7 +143,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (#1251):** Eyedropper source reads are independent of locks and isolation, including Shift/Shift+Alt and gradient stops. Source and selection preservation, unchanged Alt reverse/selection restrictions, hidden art and Undo/Redo have regression coverage. This addresses the reported behavior, with no new full-parity measurement. - **Done (#1253):** adding paint to an unpainted zero-width stroke restores the existing 1 pt default, including new-art defaults and Swap Fill/Stroke. The real Eyedropper inheritance sequence, targeted appearance items, preserved widths and Undo/Redo have regression coverage. - **Done:** a busy cursor while a file opens off the UI thread or a labelled background save or export runs (`Cursor::Busy` in `crates/tools/src/cursors.toml`). Heavy synchronous effect previews remain open. -- **Done:** Average and Join in one step, with a corner or smooth choice for the joined anchor: Object › Path › Average & Join… (`path.averageJoin {to: "corner"|"smooth"}`, Cmd+Alt+Shift+J, Ctrl+Alt+Shift+J on Windows) moves the two direct-selected open path ends, or the nearest ends of two selected open paths (both ends of one, closing it), to their midpoint and joins them there in one undo step. The public [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists the shortcut as "Create corner or smooth join" ("Select the paths" on Windows, "Select the anchor point" on macOS). The dialog (Points: Corner / Smooth) opens on Corner and then on the choice confirmed last in the session: VectorCraft's reading, as the page doesn't say. Inside the estimate below. +- **Done:** Average and Join in one step, with a corner or smooth choice for the joined anchor: Object › Path › Average & Join… (`path.averageJoin {to: "corner"|"smooth"}`, Cmd+Alt+Shift+J, Ctrl+Alt+Shift+J on Windows) moves the two direct-selected open path ends, or the nearest ends of two selected open paths (both ends of one, closing it), to their midpoint and joins them there in one undo step. The public [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists the shortcut as "Create corner or smooth join", with the paths selected on Windows and the anchor point selected on macOS. The dialog (Points: Corner / Smooth) opens on Corner and then on the choice confirmed last in the session: VectorCraft's reading, as the page doesn't say. Inside the estimate below. - **Implemented (#1760):** Effect › Warp has a shared style selector with original previews, orientation buttons and percent sliders. Existing effects retain their stack slot and target. Focused checks passed and original captures were reviewed; optional Properties integration and remembered defaults remain outside this change. - **Done (#2120):** Smart Guides line extension: dragging the end of a straight segment with Direct Selection or Curvature, the point snaps to the segment's own direction at any angle and the guide runs along it from the other end. Inside the estimate below. - **Done (#1692):** Tab in the Color Picker moves through one color model's fields before the next. Completed upstream before the layout change (#2008). diff --git a/docs/mcp.md b/docs/mcp.md index 0ca4e32353..2f750cbdd5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1685,11 +1685,11 @@ already walks Image Trace. Short agent entry points: `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also - reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included), as the + reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included). The + first row holds the field names, as the [set-up page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/set-up-data-source-files.html) - describes the first row: "Specify your data field name in the first row of your spreadsheet." The rows replace every - data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; the document's variables - and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error + describes. The rows replace every data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; + the document's variables and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image From aca6e98423447d22a6c97c35709b895cd9f120e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:54:55 -0800 Subject: [PATCH 11/50] Keep Blend reset after a dropped press --- crates/tools/src/meshblend.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index a9f3928ec0..eaa13cf422 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -90,7 +90,7 @@ impl Tool for BlendTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let options = |t: &mut Self| { - (t.first, t.chained) = (None, false); + (t.first, t.chained, t.before_press) = (None, false, None); vec![Action::Dialog(BLEND_OPTIONS.into(), json!({}))] }; // A first pick whose object is no longer in the document (deleted, or undone away) is @@ -157,7 +157,7 @@ impl Tool for BlendTool { /// click picks a new first object. The document and the selection stay as they are. fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { if key == crate::ToolKey::Escape { - (self.first, self.chained) = (None, false); + (self.first, self.chained, self.before_press) = (None, false, None); } vec![] } @@ -171,7 +171,7 @@ impl Tool for BlendTool { vec![] } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { - (self.first, self.chained) = (None, false); + (self.first, self.chained, self.before_press) = (None, false, None); vec![] } /// Choosing the Blend tool again finishes the blend: it drops the object picked first and @@ -382,6 +382,28 @@ mod tests { assert!(create("mesh").unwrap().chosen_again(&c).is_empty()); } + #[test] + fn resetting_blend_during_a_press_survives_its_drop() { + let (d, a) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + for reset in 0..3 { + let mut t = BlendTool { first: Some((a, None)), chained: true, ..Default::default() }; + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 450.0, 450.0)).is_empty()); + match reset { + 0 => assert!(t.key(&c, ToolKey::Escape, Mods::default()).is_empty()), + 1 => assert!(t.chosen_again(&c).is_empty()), + _ => assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 450.0, 450.0)), + vec![Action::Dialog(BLEND_OPTIONS.into(), json!({}))], + ), + } + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 450.0, 450.0)).is_empty()); + assert_eq!((t.first, t.chained), (None, false)); + } + } + #[test] fn blend_tool_picks_again_when_its_first_pick_is_gone() { let (mut d, a) = doc_with_rect(); From 4c0e0b959a9b297798c8c14c80c1c618ec4ebfbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:43:26 -0800 Subject: [PATCH 12/50] Commit pending dimensions only on pointer release --- crates/tools/src/dimension.rs | 43 +++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 2290f5d2fd..046d149193 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -352,13 +352,16 @@ impl Tool for DimensionTool { } PointerKind::Down => { if self.pending.is_some() && !self.dragging { - // The second click of a picked measurement places it. - return self.place(cx, ev.pos); + self.press = Some((ev.pos, None)); + return vec![]; } self.press = Some((ev.pos, self.target(cx, ev.pos))); vec![] } PointerKind::Drag => { + if self.pending.is_some() && !self.dragging && self.press.is_some() { + return self.preview(cx, ev.pos); + } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() && start.distance(ev.pos) > cx.tol(3.0) @@ -374,8 +377,11 @@ impl Tool for DimensionTool { if self.dragging { return self.place(cx, ev.pos); } + if self.pending.is_some() { + return if self.press.take().is_some() { self.place(cx, ev.pos) } else { vec![] }; + } match self.press.take() { - Some((start, target)) if self.pending.is_none() => self.click(cx, start, target, ev.mods), + Some((start, target)) => self.click(cx, start, target, ev.mods), _ => vec![], } } @@ -397,7 +403,12 @@ impl Tool for DimensionTool { return self.key(cx, ToolKey::Escape, Mods::default()); } self.press = None; - vec![] + if self.pending.is_some() && self.began { + self.began = false; + vec![Action::Cancel] + } else { + vec![] + } } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.key(cx, ToolKey::Escape, Mods::default()) @@ -507,4 +518,28 @@ mod tests { assert!(!t.busy()); assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing"); } + + #[test] + fn a_dropped_placement_press_does_not_commit_the_dimension() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let mut t = DimensionTool::default(); + for (x, y) in [(400.0, 400.0), (450.0, 420.0)] { + assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, x, y)).is_empty()); + } + assert!(t.pending.is_some()); + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 470.0, 450.0)).first(), Some(Action::Begin(_)))); + assert!(t.pointer(&c, &ev(PointerKind::Down, 470.0, 450.0)).is_empty()); + assert_eq!(t.drop_press(&c), vec![Action::Cancel]); + assert!(t.pointer(&c, &ev(PointerKind::Up, 470.0, 450.0)).is_empty()); + assert!(t.pending.is_some(), "the dimension can still be placed"); + assert!(t.pointer(&c, &ev(PointerKind::Down, 480.0, 460.0)).is_empty()); + let dragged = t.pointer(&c, &ev(PointerKind::Drag, 490.0, 470.0)); + assert!(matches!(dragged.last(), Some(Action::Preview(_, _))), "{dragged:?}"); + let placed = t.pointer(&c, &ev(PointerKind::Up, 490.0, 470.0)); + assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}"); + } } From aeafc359ea8a91e44776a4934825df144bdd5574 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 11:20:09 -0800 Subject: [PATCH 13/50] Measure tool: Shift keeps the end on the pointer's step after the grid rounds it With a Constrain Angle other than 0, the grid point a Shift-drag's end rounds to can lie nearer another 45-degree step, and the measurement then reported that step. A Shift-drag from (0, 0) to (5, -3) with a 30-degree Constrain Angle and a 9 pt grid measured -15 degrees instead of 30. The end is now turned back onto the step nearest the pointer's direction, keeping its length. --- crates/tools/src/xform/measure.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index 140697dd6a..cf04c85c5b 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -27,7 +27,8 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) { /// it. With Shift held, the end stays on the 45° step from the Constrain Angle nearest the /// pointer's direction: `p` is projected onto the step, then snapped along it as the Line Segment /// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or -/// in line with a ruler guide) is projected instead. +/// in line with a ruler guide) is projected instead. When the snapped point lies nearer another +/// step (the grid rounds it past the halfway angle), it is turned back onto the pointer's step. pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point { if !shift { return crate::guides::snap_draw(cx, p, &[]).0; @@ -42,7 +43,9 @@ pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Po let s = if to_point { crate::guides::snap_draw(cx, p, &[]).0 } else { p }; let q = a + u * (s - a).dot(u); let leave = crate::guides::Leave::segment(cx, a, true); - crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0 + let r = crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0; + let v = r - a; + if v.cross(u).abs() <= 1e-9 * v.hypot().max(1.0) { r } else { a + u * v.hypot() } } impl Tool for MeasureTool { @@ -222,6 +225,27 @@ mod tests { assert!((o["dy"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); } + /// With a Constrain Angle of 30°, the grid point a Shift-drag's end rounds to can lie nearer + /// another step; the end stays on the step nearest the pointer's direction. + #[test] + fn shift_drag_keeps_its_step_after_the_grid_rounds_it() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.snap_to_grid = true; + cx.constrain_angle = 30.0; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureTool::default(); + // (5, -3) points 31° up, so the step is 30°; the end lands at about (5.05, -2.92), which + // the 9 pt grid rounds to (9, 0), nearer the -15° step. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 5.0, -3.0).with_mods(shift)); + let o = t.options(); + assert!((o["angle"].as_f64().unwrap() - 30.0).abs() < 1e-9, "{o}"); + } + /// With Snap to Point alone, a Shift-drag's end slides along its 45° step to a ruler guide. #[test] fn shift_drag_meets_a_ruler_guide() { From 9051b700280896e7dfc9e2326db830025bf412f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 11:34:00 -0800 Subject: [PATCH 14/50] Measure tool: Shift does not turn the end to the opposite step With Snap to Point alone, an anchor behind the start could pull the projected end behind it, and the measurement read 180 degrees from the pointer's step. Such an end is now turned back onto the pointer's step, keeping its length, as an end rounded nearer another step is. --- crates/tools/src/xform/measure.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index cf04c85c5b..62b2071806 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -28,7 +28,8 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) { /// pointer's direction: `p` is projected onto the step, then snapped along it as the Line Segment /// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or /// in line with a ruler guide) is projected instead. When the snapped point lies nearer another -/// step (the grid rounds it past the halfway angle), it is turned back onto the pointer's step. +/// step (the grid rounds it past the halfway angle) or behind the start, it is turned back onto +/// the pointer's step. pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point { if !shift { return crate::guides::snap_draw(cx, p, &[]).0; @@ -45,7 +46,7 @@ pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Po let leave = crate::guides::Leave::segment(cx, a, true); let r = crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0; let v = r - a; - if v.cross(u).abs() <= 1e-9 * v.hypot().max(1.0) { r } else { a + u * v.hypot() } + if v.cross(u).abs() <= 1e-9 * v.hypot().max(1.0) && v.dot(u) >= 0.0 { r } else { a + u * v.hypot() } } impl Tool for MeasureTool { @@ -246,6 +247,30 @@ mod tests { assert!((o["angle"].as_f64().unwrap() - 30.0).abs() < 1e-9, "{o}"); } + /// With Snap to Point alone, an anchor behind the start can pull the projected end behind it; + /// the end is turned back onto the pointer's step instead of reading 180°. + #[test] + fn shift_drag_keeps_its_step_when_an_anchor_lies_behind_the_start() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.snap_tolerance = 4.0; + cx.snapping_tolerance = 4.0; + assert!(cx.snap_to_point); + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureTool::default(); + // From (200.3, 196.005), the pointer at (202.3, 196.805) points 0° and snaps to the anchor + // at (200, 200), which projects onto the 0° line at (200, 196.005), behind the start. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.3, 196.005)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 202.3, 196.805).with_mods(shift)); + let o = t.options(); + assert!(o["angle"].as_f64().unwrap().abs() < 1e-9, "{o}"); + assert!((o["dx"].as_f64().unwrap() - 0.3).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + } + /// With Snap to Point alone, a Shift-drag's end slides along its 45° step to a ruler guide. #[test] fn shift_drag_meets_a_ruler_guide() { From 04e154510af1ddb58890b90b5fdb522549e48827 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 11:35:19 -0800 Subject: [PATCH 15/50] Edit Original: read PhotoCraft's App Paths entry as UTF-16 on Windows The lookup ran reg.exe and decoded its output as UTF-8, but reg.exe writes in the console's code page, so a registered path with characters outside ASCII came back wrong, and characters outside that code page came back as "?". The path is now read with RegGetValueW. --- apps/vectorcraft/Cargo.toml | 5 +- apps/vectorcraft/src/host_services.rs | 89 ++++++++++++++++++--------- 2 files changed, 64 insertions(+), 30 deletions(-) diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 47d26eb7b6..f462132317 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -56,8 +56,9 @@ pollster = "1" # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. # Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the # cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which -# src/caps_lock.rs uses to read whether Caps Lock is on. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`, +# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } # The renderer's worker count follows those cores (src/windows_cores.rs). vectorcraft-render = { workspace = true } diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 16fe1d469c..379d6fd242 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -461,24 +461,13 @@ pub(crate) fn windows_candidates( } /// The paths PhotoCraft's installer registers under App Paths, for the current user and then for -/// everyone (`reg query`, so no extra dependency; a hidden console window). +/// everyone. #[cfg(windows)] fn registered_photocraft() -> Vec { - use std::os::windows::process::CommandExt as _; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - // reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead. - let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()); - ["HKCU", "HKLM"] + use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] .into_iter() - .filter_map(|hive| { - let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"); - let out = std::process::Command::new(root.join("System32").join("reg.exe")) - .args(["query", &key, "/ve"]) - .creation_flags(CREATE_NO_WINDOW) - .output() - .ok()?; - registered_path(&String::from_utf8_lossy(&out.stdout)) - }) + .filter_map(|hive| registry_default_path(hive, r"Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe")) .collect() } @@ -487,11 +476,35 @@ fn registered_photocraft() -> Vec { Vec::new() } -/// The path in `reg query … /ve` output like -/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`. +/// The default `REG_SZ` value of `subkey` under `hive` as a path ([`registered_path`]), or `None` +/// when the key or the value is missing. The value is read as UTF-16, so a folder name in any +/// script comes back as stored. +#[cfg(windows)] +#[allow(unsafe_code)] +fn registry_default_path(hive: windows::Win32::System::Registry::HKEY, subkey: &str) -> Option { + use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW}; + use windows::core::PCWSTR; + let subkey: Vec = subkey.encode_utf16().chain([0]).collect(); + let mut size = 0u32; + // SAFETY: `subkey` is a NUL-terminated UTF-16 string that outlives the call, a null value name + // reads the default value, and with no buffer the call only writes the value's size to `size`. + unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, None, Some(&mut size)) }.ok().ok()?; + let mut value = vec![0u16; (size as usize).div_ceil(2)]; + let mut size = u32::try_from(value.len() * 2).ok()?; + // SAFETY: as above, and `value` holds the `size` bytes the call may write. + unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, Some(value.as_mut_ptr().cast()), Some(&mut size)) } + .ok() + .ok()?; + registered_path(&value) +} + +/// The path in a registry string value read as UTF-16, up to its first NUL, without surrounding +/// spaces or quotes, like `C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`. #[cfg_attr(not(any(windows, test)), allow(dead_code))] -pub(crate) fn registered_path(text: &str) -> Option { - text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from) +pub(crate) fn registered_path(value: &[u16]) -> Option { + let end = value.iter().position(|&c| c == 0).unwrap_or(value.len()); + let text = String::from_utf16(&value[..end]).ok()?; + Some(text.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from) } /// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on @@ -616,17 +629,37 @@ mod open_with_tests { ); } - /// The registered path is read from `reg query … /ve` output, spaces and quotes included; - /// no value, no path. + /// The registered path is read from the UTF-16 value up to its NUL, spaces, quotes and + /// characters outside ASCII included; an empty value or one that is not UTF-16 gives no path. #[test] - fn the_registered_path_is_read_from_reg_query() { - let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n"; - assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))); + fn the_registered_path_is_read_from_the_utf16_value() { + let wide = |s: &str| s.encode_utf16().chain([0, 0]).collect::>(); assert_eq!( - registered_path(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""), - Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe")) + registered_path(&wide(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")), + Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")) ); - assert_eq!(registered_path("ERROR: The system was unable to find the specified registry key or value."), None); - assert_eq!(registered_path(" (Default) REG_SZ "), None); + assert_eq!( + registered_path(&wide(" \"C:\\Prögram Fïles\\Тест\\写真\\photocraft.exe\" ")), + Some(std::path::PathBuf::from(r"C:\Prögram Fïles\Тест\写真\photocraft.exe")) + ); + assert_eq!(registered_path(&wide("")), None); + assert_eq!(registered_path(&[0xD800, 0]), None); + } + + /// On Windows a registered path with characters outside the console's code page is read as + /// stored, from a scratch key under the current user's hive. + #[cfg(windows)] + #[test] + fn a_registered_path_outside_ascii_is_read_as_stored() { + let key = format!(r"Software\VectorCraftTest-app-paths-{}", std::process::id()); + let path = r"C:\Prögram Fïles\Тест\写真\photocraft.exe"; + let reg = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()).join(r"System32\reg.exe"); + let full = format!(r"HKCU\{key}"); + let added = std::process::Command::new(®).args(["add", &full, "/ve", "/t", "REG_SZ", "/d", path, "/f"]).output().unwrap(); + assert!(added.status.success(), "{added:?}"); + let read = super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key); + let _ = std::process::Command::new(®).args(["delete", &full, "/f"]).output(); + assert_eq!(read, Some(std::path::PathBuf::from(path))); + assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted"); } } From dc8808fe5ef1b75fbd4a829cb5174cb68b123722 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 10:01:03 -0800 Subject: [PATCH 16/50] Read compound effects when opening effect dialogs --- crates/engine/src/cmd/appearance.rs | 17 ++ crates/ui-egui/src/dialogs/effect.rs | 30 +++- crates/ui-egui/src/panels/tests_appearance.rs | 158 ++++++++++++++++++ crates/ui-egui/src/panels/tests_effectedit.rs | 8 +- 4 files changed, 203 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index dc83d24bd5..92ee0c03a6 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -178,6 +178,23 @@ pub(crate) struct ActiveItem { } impl Session { + /// The method returns explicit target parameters and the selected appearance effect list. + pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> { + let mut ids = appearance_targets(self, params).ok()?; + let item = item_target(self, params, "effect.apply").ok()?; + let anchor = item.anchor(self, &ids); + let node = self.active()?.doc.node(*ids.get(anchor)?)?; + let at = item.effects_item(&node.appearance, "effect.apply").ok()?; + let effects = node.appearance.effects_at(at)?; + ids.swap(0, anchor); + let ids: Vec = ids.into_iter().map(|id| id.0).collect(); + let aligned = match item { + ItemTarget::Item { aligned, .. } => aligned, + ItemTarget::Top => aligned(params), + }; + Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice())) + } + /// The Appearance panel's active fill/stroke: a paint-order index into the first selected /// object's stack, while the selection it was chosen for is unchanged. pub fn appearance_item(&self) -> Option { diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 85282add14..15d0b7004d 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -43,6 +43,7 @@ fn heading_label(d: &Dialog) -> String { /// Fields: `__effect`, `__label`, `__item?` (as given to `effect.dialog`), `__target` and /// `__index` (the applied effect's item and position). OK edits it; `discard: true` then OK adds /// a new one. +/// `__editTarget` stores the targets used when editing the applied effect. pub const EXISTS: &str = "effectExists"; pub(super) const EXISTS_SPEC: DialogSpec = DialogSpec { @@ -67,7 +68,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // The list the effect goes to: `item` as given, else the active item's (the object's without // one). A new effect keeps `item` unresolved, so `effect.apply` targets each object as usual. let target = p.get("item").cloned().unwrap_or_else(|| json!(app.session.appearance_item())); - let applied = target_effects(app, &target); + let (edit_target, applied) = target_effects(app, p); + let target = edit_target.get("item").cloned().unwrap_or(target); let mut fields = Map::new(); fields.insert("__effect".into(), json!(id)); fields.insert("__label".into(), json!(info.label.trim_end_matches('…'))); @@ -85,12 +87,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { return Err(format!("effect {k} is `{}`, not `{id}`", e.id)); } fields.insert("__item".into(), target); + fields.insert("__editTarget".into(), edit_target); fields.insert("__index".into(), json!(k)); fields.extend(params_of(e)); } None => { if let Some(k) = applied.iter().rposition(|e| e.id == id) { fields.insert("__target".into(), target); + fields.insert("__editTarget".into(), edit_target); fields.insert("__index".into(), json!(k)); app.ui.dialog = Some(Dialog { kind: EXISTS.into(), fields }); return Ok(json!({ "pending": EXISTS })); @@ -106,11 +110,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// The function reads effects at `item` (an index or null) from the targeted node or first selected object. -fn target_effects(app: &VectorcraftApp, item: &Value) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; - let node = st.selection.subjects().first().and_then(|id| st.doc.node(*id)); - node.and_then(|n| n.appearance.effects_at(item.as_u64().map(|i| i as usize))).cloned().unwrap_or_default() +/// The function returns target parameters and effects at `item` (an index or null). +/// An omitted `item` uses the active row. +fn target_effects(app: &VectorcraftApp, p: &Value) -> (Value, Vec) { + let mut params = json!({"aligned": p.get("aligned").and_then(Value::as_bool).unwrap_or(false)}); + if let Some(item) = p.get("item") { + params["item"] = item.clone(); + } + app.session.appearance_effect_target(¶ms).map(|(target, effects)| (target, effects.to_vec())).unwrap_or_else(|| (json!({}), vec![])) } /// An applied effect's values over its defaults. @@ -128,6 +135,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result let target = fields.remove("__target").unwrap_or(Value::Null); if d.bool("discard") { fields.remove("__index"); + fields.remove("__editTarget"); let id = d.str("__effect"); let defaults = vectorcraft_effects::default_params(&id); fields.extend(defaults.and_then(|v| v.as_object().cloned()).unwrap_or_default()); @@ -136,7 +144,10 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result } } else { let k = fields.get("__index").and_then(Value::as_u64).unwrap_or(0) as usize; - fields.extend(target_effects(app, &target).get(k).map(params_of).unwrap_or_default()); + let edit_target = fields.get("__editTarget").cloned().unwrap_or_else(|| json!({"item": target})); + let applied = app.session.appearance_effect_target(&edit_target).map(|(_, effects)| effects.to_vec()).unwrap_or_default(); + let params = applied.get(k).map(params_of).unwrap_or_default(); + fields.extend(params); fields.insert("__item".into(), target); } fields.insert("preview".into(), json!(true)); @@ -804,7 +815,10 @@ fn command(d: &Dialog) -> (&'static str, Value) { let params = form::params(d); let item = d.fields.get("__item").cloned(); if let Some(index) = d.fields.get("__index") { - let mut p = json!({"index": index, "item": item.unwrap_or(Value::Null), "params": params}); + let mut p = d.fields.get("__editTarget").filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})); + p["index"] = index.clone(); + p["item"] = item.unwrap_or(Value::Null); + p["params"] = params; let id = d.str("__effect"); // The displayed style comes from the first target. Preserve other targets' Warp IDs // unless the user deliberately chooses Style, including after a preview rollback. diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index dc56d99e8a..ba4eebddab 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -870,6 +870,164 @@ fn transform_effect_name_edits_the_displayed_appearance_target() { } } +#[test] +fn transform_effect_dialog_reads_the_selected_compound_members_owner() { + for item in [None, Some(0)] { + let mut app = app_with_rect(); + let member = app.session.doc().unwrap().selection.subjects()[0]; + let other = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [member.0, other]})).unwrap(); + let compound = app.run("object.compoundPath.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": item, "params": {"moveH": 12, "copies": 2}})).unwrap(); + app.run("select.set", json!({"ids": [member.0]})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": item, "index": 0})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.f64("moveH", 0.0), 12.0); + assert_eq!(d.f64("copies", 0.0), 2.0); + d.fields.insert("moveH".into(), json!(35)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + let effects = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(compound)).unwrap().appearance; + assert_eq!(effects.effects_at(item).unwrap()[0].params["moveH"].as_f64(), Some(35.0)); + assert_eq!(effects.effects_at(item).unwrap()[0].params["copies"].as_f64(), Some(2.0)); + app.run("edit.undo", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": item})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, "effectExists"); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.f64("moveH", 0.0), 12.0); + d.fields.insert("moveH".into(), json!(60)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::cancel(&mut app); + let effects = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(compound)).unwrap().appearance; + assert_eq!(effects.effects_at(item).unwrap()[0].params["moveH"].as_f64(), Some(12.0)); + } +} + +#[test] +fn transform_effect_dialog_keeps_the_active_items_selection_anchor() { + for item in [None, Some(json!(0)), Some(Value::Null)] { + let mut app = app_with_rect(); + let back = app.session.doc().unwrap().selection.subjects()[0]; + for at in [json!(0), Value::Null] { + app.run("effect.apply", json!({"effect": "distort.transform", "item": at, "params": {"moveH": 99}})).unwrap(); + } + let front = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap()["id"].clone(); + for at in [json!(0), Value::Null] { + app.run("effect.apply", json!({"effect": "distort.transform", "item": at, "params": {"moveH": 12}})).unwrap(); + } + app.run("select.set", json!({"ids": [front, back.0]})).unwrap(); + app.run("appearance.setActiveItem", json!({"index": 0})).unwrap(); + let mut p = json!({"effect": "distort.transform"}); + if let Some(item) = &item { + p["item"] = item.clone(); + } + app.run("effect.dialog", p).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, "effectExists"); + crate::dialogs::confirm(&mut app).unwrap(); + let expected = if item.is_none() { 12.0 } else { 99.0 }; + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("moveH", 0.0), expected); + } +} + +#[test] +fn explicit_effect_items_use_paint_order_with_a_selected_compound_member() { + let mut app = app_with_rect(); + let back = app.session.doc().unwrap().selection.subjects()[0]; + for item in [json!(0), Value::Null] { + app.run("effect.apply", json!({"effect": "distort.transform", "item": item, "params": {"moveH": 99}})).unwrap(); + } + let member = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap()["id"].clone(); + let inner = app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [member, inner]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + for item in [json!(0), Value::Null] { + app.run("effect.apply", json!({"effect": "distort.transform", "item": item, "params": {"moveH": 12}})).unwrap(); + } + app.run("select.set", json!({"ids": [member, back.0]})).unwrap(); + for item in [json!(0), Value::Null] { + app.run("effect.dialog", json!({"effect": "distort.transform", "item": item, "index": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("moveH", 0.0), 99.0); + crate::dialogs::cancel(&mut app); + } +} + +#[test] +fn editing_an_active_effect_keeps_aligned_rows_in_mixed_stacks() { + let mut app = app_with_rect(); + let back = app.session.doc().unwrap().selection.subjects()[0]; + app.run("appearance.addStroke", json!({})).unwrap(); + app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"moveH": 99}})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 1, "params": {"moveH": 12}})).unwrap(); + let front = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"moveH": 12}})).unwrap(); + app.run("select.set", json!({"ids": [front, back.0]})).unwrap(); + app.run("appearance.setActiveItem", json!({"index": 0})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform", "index": 0})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.f64("moveH", 0.0), 12.0); + d.fields.insert("moveH".into(), json!(35)); + app.run("appearance.setActiveItem", json!({"index": null})).unwrap(); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let front = &doc.node(vectorcraft_doc::NodeId(front)).unwrap().appearance; + let back = &doc.node(back).unwrap().appearance; + assert_eq!(front.effects_at(Some(0)).unwrap()[0].params["moveH"], 35); + assert_eq!(back.effects_at(Some(1)).unwrap()[0].params["moveH"], 35); + assert_eq!(back.effects_at(Some(0)).unwrap()[0].params["moveH"], 99); +} + +#[test] +fn editing_an_effect_keeps_its_original_item_when_the_active_row_changes() { + for prompt in [false, true] { + let mut app = app_with_rect(); + let id = app.session.doc().unwrap().selection.subjects()[0]; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"moveH": 99}})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"moveH": 12}})).unwrap(); + app.run("appearance.setActiveItem", json!({"index": 0})).unwrap(); + let mut p = json!({"effect": "distort.transform"}); + if !prompt { + p["index"] = json!(0); + } + app.run("effect.dialog", p).unwrap(); + app.run("appearance.setActiveItem", json!({"index": null})).unwrap(); + if prompt { + crate::dialogs::confirm(&mut app).unwrap(); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.f64("moveH", 0.0), 12.0); + d.fields.insert("moveH".into(), json!(35)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + let appearance = &app.session.doc().unwrap().doc.node(id).unwrap().appearance; + assert_eq!(appearance.effects_at(Some(0)).unwrap()[0].params["moveH"].as_f64(), Some(35.0)); + assert_eq!(appearance.effects[0].params["moveH"].as_f64(), Some(99.0)); + } +} + +#[test] +fn new_effects_keep_implicit_item_targeting_until_confirmation() { + for prompt in [false, true] { + let mut app = app_with_rect(); + let id = app.session.doc().unwrap().selection.subjects()[0]; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"moveH": 99}})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"moveH": 12}})).unwrap(); + app.run("appearance.setActiveItem", json!({"index": 0})).unwrap(); + app.run("effect.dialog", json!({"effect": if prompt { "distort.transform" } else { "distort.roughen" }})).unwrap(); + app.run("appearance.setActiveItem", json!({"index": null})).unwrap(); + if prompt { + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + } + crate::dialogs::confirm(&mut app).unwrap(); + let appearance = &app.session.doc().unwrap().doc.node(id).unwrap().appearance; + assert_eq!(appearance.effects_at(Some(0)).unwrap().len(), 1); + assert_eq!(appearance.effects.len(), 2); + } +} + #[test] fn transform_effect_typed_scale_changes_the_painted_object() { for layer_target in [false, true] { diff --git a/crates/ui-egui/src/panels/tests_effectedit.rs b/crates/ui-egui/src/panels/tests_effectedit.rs index a27a60cb62..48dfdfc25f 100644 --- a/crates/ui-egui/src/panels/tests_effectedit.rs +++ b/crates/ui-egui/src/panels/tests_effectedit.rs @@ -59,7 +59,10 @@ fn an_effect_name_opens_its_dialog_prefilled_and_ok_edits_it_in_place() { let texts = frame_events(&ctx, &mut app, vec![], appearance::show); click(&ctx, &mut app, text_rect(&texts, "Roughen").center(), appearance::show); let d = app.ui.dialog.clone().expect("the effect's dialog"); - assert_eq!((d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone()), ("effect", 9.0, json!(0))); + assert_eq!( + (d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone(), d.fields["__item"].clone()), + ("effect", 9.0, json!(0), Value::Null) + ); // The dialog previews; OK keeps the new value on the same effect as one undo step. let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); out.textures_delta.clear(); @@ -115,9 +118,10 @@ fn choosing_an_applied_effect_asks_to_edit_it_or_add_another() { assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"})); crate::dialogs::confirm(&mut app).unwrap(); let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone(), d.fields["__item"].clone()), ("effect", 9.0, json!(0), json!(0))); + assert_eq!((d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone()), ("effect", 9.0, json!(0))); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(effects(&app, Some(0)).len(), 1); + assert!(effects(&app, None).is_empty()); // "Add New": a fresh dialog with the defaults, which adds a second one. app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); From 40175d90c7549b249f5273658a15fd3e82e3ed30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:31:41 -0800 Subject: [PATCH 17/50] Geometry: inverses and conjugates by small affines are no longer refused A projection now counts as invertible when its determinant, or its adjugate's determinant, is more than 1e-15 times the largest of the six products that determinant sums. The adjugate of the adjugate is the map times a number, so the inverse of a projection that inverts also inverts, is stored and reads back. The adjugate's cofactors are formed with exact products, so the inverse of that inverse gives back the original map up to scale, within 1e-6 of each row's largest entry, and a map whose third row is the sum of its first two is still refused. Homography::conjugated and Node::transform_projection judged the affine map by an absolute determinant of 1e-15, so a scale by 1e-8 left type and symbol instances in perspective with their old projection. Both now use Homography::affine_is_invertible, which compares the determinant with the two products it sums at any scale of the map. An affine map whose determinant or inverse is not finite, such as a scale by 1e200 or 1e-200, is inverted through Homography::inverse. When the direct product underflows to a map that is not invertible, as for a projection stored at a subnormal scale, conjugated forms it again with its powers of two kept apart. - crates/geom/src/projective.rs: the_inverse_of_an_invertible_map_is_invertible, conjugating_does_not_depend_on_the_scale_of_the_affine, conjugating_a_map_at_a_tiny_scale_gives_an_invertible_map - crates/doc/src/node/tests.rs: a_projection_follows_the_transform_or_is_removed covers an invertible scale by 1e-8 and a singular map at that size --- crates/doc/src/node/tests.rs | 11 +- crates/doc/src/perspective.rs | 2 +- crates/geom/src/projective.rs | 228 +++++++++++++++++++++++++++------- docs/target-app-parity.md | 2 +- 4 files changed, 198 insertions(+), 45 deletions(-) diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 1669de1a27..cde4004aea 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -390,10 +390,19 @@ fn a_projection_follows_the_transform_or_is_removed() { let mut n = instance(far); n.transform(Affine::scale(1e150), false); assert_eq!(projection(&n), None); - // A transform that is not invertible leaves the projection as it is. + // A transform that is not invertible leaves the projection as it is, at any scale. let mut n = instance(far); n.transform(Affine::scale(0.0), false); assert_eq!(projection(&n), Some(far.to_array())); + let mut n = instance(far); + n.transform(Affine::new([1e-8, 2e-8, 2e-8, 4e-8, 0.0, 0.0]), false); + assert_eq!(projection(&n), Some(far.to_array())); + // A scale by 1e-8 is invertible: a move by 10 becomes a move by 1e-7. + let ten = Homography::from_affine(Affine::translate((10.0, 0.0))); + let mut n = instance(ten); + n.transform(Affine::scale(1e-8), false); + let q = n.projection().unwrap().apply(Point::new(3e-8, 7e-8)).unwrap(); + assert!(q.distance(Point::new(1.3e-7, 7e-8)) < 1e-20, "{q:?}"); } #[test] diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index 6ec18bcfa2..ab347529e6 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -63,7 +63,7 @@ impl Node { pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { if let Some(p) = self.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) && let Some(h) = p.homography() - && a.determinant().abs() >= 1e-15 + && Homography::affine_is_invertible(a) { p.projection = h.conjugated(a).map(|h| h.to_array()); } diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 070048f38c..e35637468c 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -93,35 +93,36 @@ impl Homography { self.inverse().is_some() } - /// Whether every entry is finite and the determinant's magnitude is more than 1e-15 times that - /// of the largest of the six products it sums (a test that gives the same answer at any scale - /// of the map). Each product is formed as a mantissa product and an exponent sum, and all six - /// are divided by the power of two of the largest before they are summed, so the largest is at - /// least 1/8 and below 1 and none of them overflows. + /// Whether every entry is finite and [`significant_det`] holds for the map or for its + /// adjugate (the inverse times the determinant). Both tests give the same answer at any scale + /// of the map. The adjugate of the adjugate is the map times a number, so, apart from + /// rounding, a map passes when its inverse passes and fails when its inverse fails. fn has_significant_det(&self) -> bool { if !self.is_finite() { return false; } - let terms = self.det_terms(); - let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { - return false; - }; - let terms = terms.map(|(m, x)| ldexp(m, x - e)); - let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); - let d: f64 = terms.iter().sum(); - d.abs() > 1e-15 * largest + significant_det(self.det_terms()) || significant_det(split_det_terms(&self.adjugate())) } /// The six signed products the determinant sums, each as a mantissa product and an exponent /// sum. fn det_terms(&self) -> [(f64, i32); 6] { + split_det_terms(&self.0.map(|row| row.map(frexp))) + } + + /// The adjugate (the transposed matrix of cofactors), each entry as a mantissa and a power of + /// two. Each cofactor's two products are formed exactly before they are subtracted, so an + /// entry is within a few units in the last place of the exact cofactor of the stored numbers. + /// The entries must be finite. + fn adjugate(&self) -> [[(f64, i32); 3]; 3] { let f = self.0.map(|row| row.map(frexp)); - // The columns each of the six products takes from rows 0, 1 and 2, and its sign. - let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; - cols.map(|(a, b, c, sign)| { - let (a, b, c) = (f[0][a], f[1][b], f[2][c]); - (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) - }) + let c = |r0: usize, c0: usize, r1: usize, c1: usize| split_minor(f[r0][c0], f[r1][c1], f[r0][c1], f[r1][c0]); + let neg = |(m, e): (f64, i32)| (-m, e); + [ + [c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)], + [neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))], + [c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)], + ] } /// The same map with every entry divided by one power of two, chosen so that the largest of the @@ -162,26 +163,17 @@ impl Homography { } /// The adjugate divided by the determinant; `None` when an entry is not finite, the - /// determinant is 0, or the result has an entry that is not finite or a determinant of 0 (its - /// six products, each held as a mantissa and a power of two, sum to 0, as when a row underflows - /// to 0). Every cofactor and the determinant are held as a mantissa and a power of two, so an - /// entry of the result is lost only when that entry itself is beyond the range of `f64`. + /// determinant is 0, or the result has an entry that is not finite or fails + /// [`Self::has_significant_det`] (as when a row underflows to 0). Every cofactor and the + /// determinant are held as a mantissa and a power of two, so an entry of the result is lost + /// only when that entry itself is beyond the range of `f64`. fn adjugate_inverse(&self) -> Option { if !self.is_finite() { return None; } let f = self.0.map(|row| row.map(frexp)); let mul = |a: (f64, i32), b: (f64, i32)| (a.0 * b.0, a.1 + b.1); - let c = |r0: usize, c0: usize, r1: usize, c1: usize| { - let (a, b) = (mul(f[r0][c0], f[r1][c1]), mul(f[r0][c1], f[r1][c0])); - split_sum(&[a, (-b.0, b.1)]) - }; - let neg = |(m, e): (f64, i32)| (-m, e); - let adj = [ - [c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)], - [neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))], - [c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)], - ]; + let adj = self.adjugate(); // The determinant expanded along the first row, as `det` sums it. let (dm, de) = split_sum(&[mul(f[0][0], adj[0][0]), mul(f[0][1], adj[1][0]), mul(f[0][2], adj[2][0])]); if dm == 0.0 { @@ -195,7 +187,7 @@ impl Homography { } let out = Self(out); // H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0. - (out.is_finite() && split_sum(&out.det_terms()).0 != 0.0).then_some(out) + out.has_significant_det().then_some(out) } /// `self ∘ other`: `other` first. @@ -217,19 +209,31 @@ impl Homography { c.is_finite().then_some(c) } + /// Whether every entry of `a` is finite and the determinant of its linear part has a magnitude + /// more than 1e-15 times the larger of the two products it sums (a test that gives the same + /// answer at any scale of `a`). + pub fn affine_is_invertible(a: Affine) -> bool { + Self::from_affine(a).has_significant_det() + } + /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it - /// maps from and to is moved by `a`). When the product overflows, every entry is formed with - /// its powers of two kept apart, and the product is returned divided by the largest magnitude - /// in its `w` row (the same map, with a `w` row whose largest entry is 1). `None` when `a` - /// isn't invertible, or when the product overflows and the result at that scale has an entry - /// that is not finite or is not invertible. + /// maps from and to is moved by `a`). When the product overflows, or underflows to a map that + /// is not invertible, every entry is formed with its powers of two kept apart, and the product + /// is returned divided by the largest magnitude in its `w` row (the same map, with a `w` row + /// whose largest entry is 1). `None` when `a` isn't invertible + /// ([`Self::affine_is_invertible`]), or when the result at that scale has an entry that is not + /// finite or is not invertible. `a⁻¹` is + /// [`Affine::inverse`] when `a`'s determinant and that inverse are finite, and + /// [`Self::inverse`] of `a` otherwise. pub fn conjugated(&self, a: Affine) -> Option { - if a.determinant().abs() < 1e-15 { + if !Self::affine_is_invertible(a) { return None; } - let (to, from) = (Self::from_affine(a), Self::from_affine(a.inverse())); + let to = Self::from_affine(a); + let inv = a.inverse(); + let from = if a.determinant().is_finite() && inv.is_finite() { Self::from_affine(inv) } else { to.inverse()? }; let c = to.then_after(self).then_after(&from); - if c.is_finite() { + if c.is_finite() && c.has_significant_det() { return Some(c); } // Each entry of the product is a sum of nine terms to[r][i]·self[i][j]·from[j][k]. Every @@ -299,6 +303,53 @@ fn frexp(v: f64) -> (f64, i32) { (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e + bias) } +/// The six signed products the determinant of `f` sums, each as a mantissa product and an exponent +/// sum. +fn split_det_terms(f: &[[(f64, i32); 3]; 3]) -> [(f64, i32); 6] { + // The columns each of the six products takes from rows 0, 1 and 2, and its sign. + let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; + cols.map(|(a, b, c, sign)| { + let (a, b, c) = (f[0][a], f[1][b], f[2][c]); + (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) + }) +} + +/// Whether the sum of the six products in `terms` has a magnitude more than 1e-15 times that of +/// the largest of them. All six are divided by the power of two of the largest before they are +/// summed, so the largest is at least 1/8 and below 1 and none of them overflows. `false` when +/// every product is 0. +fn significant_det(terms: [(f64, i32); 6]) -> bool { + let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { + return false; + }; + let terms = terms.map(|(m, x)| ldexp(m, x - e)); + let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); + let d: f64 = terms.iter().sum(); + d.abs() > 1e-15 * largest +} + +/// `a·d − b·c` for numbers split as by [`frexp`], as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power +/// of two. Each product is formed exactly as a rounded value and its rounding error, and the four +/// parts are summed with the error of the first subtraction kept, so the result is within a few +/// units in the last place of the exact value unless the two products agree to about 32 digits. +fn split_minor(a: (f64, i32), d: (f64, i32), b: (f64, i32), c: (f64, i32)) -> (f64, i32) { + let exact = |x: (f64, i32), y: (f64, i32), sign: f64| { + let hi = x.0 * y.0; + (sign * hi, sign * x.0.mul_add(y.0, -hi), x.1 + y.1) + }; + let parts = [exact(a, d, 1.0), exact(b, c, -1.0)]; + let Some(e) = parts.iter().filter(|p| p.0 != 0.0).map(|p| p.2).max() else { + return (0.0, 0); + }; + let [(h0, l0), (h1, l1)] = parts.map(|(h, l, x)| (ldexp(h, x - e), ldexp(l, x - e))); + // Knuth's two-sum: `s + err` is exactly `h0 + h1`. + let s = h0 + h1; + let t = s - h0; + let err = (h0 - (s - t)) + (h1 - t); + let (m, x) = frexp(s + (err + (l0 + l1))); + (m, e + x) +} + /// The sum of `m·2^e` over `terms`, in order, as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power of /// two. Every term is first divided by the power of two of the largest nonzero one, so none of /// them overflows. @@ -566,6 +617,99 @@ mod tests { } } + #[test] + fn the_inverse_of_an_invertible_map_is_invertible() { + // The inverse's determinant is about 1e-16 of its largest product, but its adjugate is + // the map itself times a number. + let skew = Homography([[-1000.0, -1e-8, -1e-5], [0.0, 1e-4, -1e7], [1e-8, 0.0, 1e-8]]); + let inv = skew.inverse().unwrap(); + assert_eq!(Homography::from_array(inv.to_array()), Some(inv)); + let back = inv.inverse().unwrap_or_else(|| panic!("{inv:?}")); + // The same map as `skew`, to within the rounding of the stored inverse: each entry within + // 1e-6 of the largest magnitude in its row, and points map to within 1e-6 of where `skew` + // maps them. + let k = back.0[2][0] / skew.0[2][0]; + assert!(k > 0.0, "{k}"); + for (r, row) in back.0.iter().enumerate() { + let size = skew.0[r].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + for (c, v) in row.iter().enumerate() { + assert!((v / k - skew.0[r][c]).abs() <= 1e-6 * size, "{back:?}"); + } + } + for p in [Point::new(3.0, -2.0), Point::new(-0.5, 7.0)] { + let q = skew.apply(p).unwrap(); + assert!(back.apply(p).unwrap().distance(q) <= 1e-6 * q.to_vec2().hypot(), "{p:?}"); + } + // Maps whose determinant is 0 are refused, though the cofactors of the first one cancel + // to about 2e-12 of their products: its rows are close to parallel and the third is the sum of + // the first two. + let two = pow2(40); + let near = + Homography([[two + 1.0, two + 3.0, two + 7.0], [two + 2.0, two + 5.0, two + 11.0], [2.0 * two + 3.0, 2.0 * two + 8.0, 2.0 * two + 18.0]]); + let flat = Homography([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.25, 0.5, 1.0]]); + let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f))); + for h in [near, flat] { + for f in [pow2(-900), pow2(-40), 1.0, pow2(40), pow2(900)] { + let s = times(h, f); + assert!(!s.is_invertible(), "{f} {s:?}"); + assert_eq!(s.inverse(), None, "{f}"); + assert_eq!(Homography::from_array(s.to_array()), None, "{f}"); + } + } + } + + #[test] + fn conjugating_does_not_depend_on_the_scale_of_the_affine() { + let unit = |h: Homography| { + let k = h.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + Homography(h.0.map(|row| row.map(|v| v / k))) + }; + let m = h().0; + for s in [1e-200, 1e-8, 1.0, 1e8, 1e200] { + let t = Affine::scale(s); + let c = h().conjugated(t).unwrap_or_else(|| panic!("{s}")); + // The scale times h() times its inverse. + let want = unit(Homography([[m[0][0], m[0][1], s * m[0][2]], [m[1][0], m[1][1], s * m[1][2]], [m[2][0] / s, m[2][1] / s, m[2][2]]])); + for (v, w) in unit(c).to_array().iter().zip(want.to_array()) { + assert!((v - w).abs() <= 1e-12 * w.abs().max(1.0), "{s}: {c:?}"); + } + // At 1e-200 the w row's first two entries are about 1e197, so these points, whose w is + // about 1, count as on the horizon (see `apply`). + if s < 1e-8 { + continue; + } + for p in [Point::new(3.0, 7.0), Point::new(-40.0, 12.0)] { + let want = t * h().apply(p).unwrap(); + assert!(c.apply(t * p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot(), "{s} {p:?}"); + } + } + // An affine whose columns are parallel is refused at every scale. + for s in [1e-200, 1e-8, 1.0, 1e8, 1e200] { + let flat = Affine::new([s, 2.0 * s, 2.0 * s, 4.0 * s, 5.0, 6.0]); + assert_eq!(h().conjugated(flat), None, "{s}"); + assert_eq!(h().conjugated(Affine::scale(s) * Affine::scale_non_uniform(1.0, 0.0)), None, "{s}"); + } + assert_eq!(h().conjugated(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])), None); + assert_eq!(h().conjugated(Affine::scale(f64::INFINITY)), None); + } + + #[test] + fn conjugating_a_map_at_a_tiny_scale_gives_an_invertible_map() { + // Against these affines the first two rows of the direct product underflow to 0. + let tiny = Homography(Homography::IDENTITY.0.map(|row| row.map(|v| v * 5e-324))); + for s in [1e-200, 1e-8] { + let c = tiny.conjugated(Affine::scale(s)).unwrap_or_else(|| panic!("{s}")); + assert_eq!(Homography::from_array(c.to_array()), Some(c), "{s}"); + let k = c.0[2][2]; + for (r, row) in c.0.iter().enumerate() { + for (j, v) in row.iter().enumerate() { + let want = if r == j { k } else { 0.0 }; + assert!(k != 0.0 && (v - want).abs() <= 1e-12 * k.abs(), "{s}: {c:?}"); + } + } + } + } + #[test] fn a_map_at_a_tiny_scale_maps_points_as_at_unit_scale() { for f in [5e-324, 1e-300] { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 55dd266430..2bbeeb404a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest absolute value in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. - A projection gives the same answers when every one of its numbers is multiplied by the same factor. A point is on or past its horizon when its w is at most 1e-9 times the largest absolute value in the bottom row, so a point with a negative w is past it. The projection is invertible when the absolute value of its determinant is more than 1e-15 times the largest absolute value among the six products the determinant sums, so a negative determinant counts the same as a positive one. A stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Regression: `the_checks_do_not_depend_on_the_scale_of_the_map` in `crates/geom/src/projective.rs`. + A projection gives the same answers when every one of its numbers is multiplied by the same factor. A point is on or past its horizon when its w is at most 1e-9 times the largest absolute value in the bottom row, so a point with a negative w is past it. The projection is invertible when the absolute value of its determinant, or of its adjugate's determinant, is more than 1e-15 times the largest absolute value among the six products that determinant sums, so a negative determinant counts the same as a positive one, and the inverse of a projection that inverts also inverts and is stored and read back. A stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Moving or transforming in perspective sees the projection through the move's affine map, and that map counts as invertible on the same test of its determinant, so a move scaled by 1e-8 or 1e8 is applied and one that flattens the art to a line is refused. Regressions: `the_checks_do_not_depend_on_the_scale_of_the_map`, `the_inverse_of_an_invertible_map_is_invertible` and `conjugating_does_not_depend_on_the_scale_of_the_affine` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From 1246c62095ae2139ed8cdbe071722a64348ea67f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:35:09 -0800 Subject: [PATCH 18/50] DXF: paths of lines and circular arcs export as polylines with bulges A path made of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) was written as one SPLINE, or as a flattened polyline in R12. It is now one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed. Each run of cubics on one circle becomes one arc. A path with any other curve stays a SPLINE, and whole circles, arcs and ellipses keep their CIRCLE, ARC and ELLIPSE entities. - The circle test's tolerance is 5e-4 of the smaller of the radius and the curve's extent, so a shallow curve that is not circular is no longer written as an ARC. - The drawing extents take each ARC's and each bulge's furthest points. Part of #1299 --- crates/cad/src/scene.rs | 121 +++++++++++++++++++--- crates/cad/src/tests.rs | 208 +++++++++++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 311 insertions(+), 19 deletions(-) diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index d7e20654a1..72fa4f7b34 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -1,7 +1,7 @@ //! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint //! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes -//! polylines and cubic splines with a lineweight and dashes, or filled outlines where the look -//! needs them. +//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or +//! filled outlines where the look needs them. use std::collections::HashMap; use std::io::Cursor; @@ -66,6 +66,8 @@ struct CircularSub { centre: Point, radius: f64, samples: Vec, + /// The signed angle (radians) the curve turns through about `centre` in document space. + turn: f64, } fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: f64) -> Point { @@ -122,7 +124,12 @@ fn circular_subpath(sub: &Sub) -> Option { if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-9 { return None; } - let tolerance = (radius * 5e-4).max(1e-6); + // The tolerance is a fraction of the smaller of the radius and the curve's extent, so the large + // radius of a shallow curve does not loosen it. + let (lo, hi) = samples + .iter() + .fold((samples[0], samples[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))); + let tolerance = (radius.min(lo.distance(hi)) * 5e-4).max(1e-6); if samples.iter().any(|p| (centre.distance(*p) - radius).abs() > tolerance) { return None; } @@ -181,7 +188,76 @@ fn circular_subpath(sub: &Sub) -> Option { } else if total_turn.abs() < 1e-6 || total_turn.abs() >= std::f64::consts::TAU - 1e-3 { return None; } - Some(CircularSub { centre, radius, samples }) + Some(CircularSub { centre, radius, samples, turn: total_turn }) +} + +/// The points of the circle about `centre` of `radius` furthest left, right, up and down that lie on +/// its arc from `from` through `turn` radians, for the drawing extents. +fn arc_extrema(centre: Point, radius: f64, from: Point, turn: f64) -> Vec { + let start = (from.y - centre.y).atan2(from.x - centre.x); + (0..4) + .map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2) + .filter(|a| ((a - start) * turn.signum()).rem_euclid(std::f64::consts::TAU) <= turn.abs()) + .map(|a| Point::new(centre.x + radius * a.cos(), centre.y + radius * a.sin())) + .collect() +} + +/// The most cubics one bulge arc is fitted to; the cubics after them start the next arc. +const MAX_ARC_RUN: usize = 64; + +/// A subpath of straight segments and circular arcs as polyline vertices, in document space. +struct BulgedSub { + /// The anchors, without a closed subpath's repeated start. + pts: Vec, + /// For each anchor, the angle (radians, document space) the segment that starts there turns + /// through: 0 for a straight segment. + turns: Vec, + /// The arcs' extreme points ([`arc_extrema`]), for the drawing extents. + extrema: Vec, +} + +/// Fit a subpath with curves to straight segments and circular arcs: each run of cubics on one +/// circle, turning one way and less than a whole turn, becomes one arc ([`circular_subpath`]'s +/// tolerance). `None` when the subpath has no curves or a curve that is not a circular arc. +fn bulged_subpath(sub: &Sub) -> Option { + if !sub.segs.iter().any(|s| matches!(s, Seg::Cubic(..))) { + return None; + } + let mut pts = vec![sub.start]; + let mut turns = vec![]; + let mut extrema = vec![]; + let mut from = sub.start; + let mut i = 0; + while let Some(seg) = sub.segs.get(i) { + if let Seg::Line(p) = *seg { + turns.push(0.0); + pts.push(p); + from = p; + i += 1; + continue; + } + let mut best = None; + let mut j = i; + while j < sub.segs.len() && j - i < MAX_ARC_RUN && matches!(sub.segs[j], Seg::Cubic(..)) { + let run = Sub { start: from, segs: sub.segs[i..=j].to_vec(), closed: false }; + let Some(arc) = circular_subpath(&run) else { break }; + best = Some((j, arc)); + j += 1; + } + let (j, arc) = best?; + turns.push(arc.turn); + extrema.extend(arc_extrema(arc.centre, arc.radius, from, arc.turn)); + from = sub.segs[j].end(); + pts.push(from); + i = j + 1; + } + if sub.closed && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) { + pts.pop(); + } else { + // The segment from the last anchor: the straight closing edge, or none for an open subpath. + turns.push(0.0); + } + (pts.len() >= 2).then_some(BulgedSub { pts, turns, extrema }) } /// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle @@ -846,7 +922,9 @@ impl<'a> Scene<'a> { } /// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for - /// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones. + /// other straight subpaths, circles, arcs and ellipses where the curves are one, polylines + /// with bulges for subpaths of straight segments and circular arcs, and cubic splines for + /// other curved ones (flattened polylines in R12). /// `width`: the stroke weight, which DXF before 2000 gives polylines as a width. fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) { let v = self.o.version; @@ -863,7 +941,7 @@ impl<'a> Scene<'a> { // A LINE has no width, so a stroke before 2000 keeps its polyline width. match (sub.closed, width, pts.as_slice()) { (false, None, &[a, b]) => self.line(a, b, style), - _ => self.polyline(&pts, sub.closed, style, width), + _ => self.polyline(&pts, &[], sub.closed, style, width), } } else if (v.handles() || width.is_none()) && self.circular(&sub, style) { // Native circles/arcs are preferred by CAD/CAM software. In R12, however, a @@ -871,6 +949,12 @@ impl<'a> Scene<'a> { // its width. Non-circular curves continue through the existing fallback. } else if v.handles() && self.elliptical(&sub, style) { // R13 and later write an ellipse as a native ELLIPSE. + } else if let Some(b) = bulged_subpath(&sub) { + // Straight segments and circular arcs: one polyline whose bulges draw the arcs. + b.extrema.iter().for_each(|p| _ = self.pt(*p)); + let flip = if self.to_dxf.determinant() < 0.0 { -1.0 } else { 1.0 }; + let bulges: Vec = b.turns.iter().map(|t| flip * (t / 4.0).tan()).collect(); + self.polyline(&b.pts, &bulges, sub.closed, style, width); } else if v.handles() { self.spline(&sub, style); } else { @@ -883,7 +967,7 @@ impl<'a> Scene<'a> { } } for pts in polygons(&path) { - self.polyline(&pts, sub.closed, style, width); + self.polyline(&pts, &[], sub.closed, style, width); } } } @@ -900,8 +984,9 @@ impl<'a> Scene<'a> { } /// A polyline through `pts` (document space): lightweight from R14, else a polyline with a - /// vertex entity per point. - fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option) { + /// vertex entity per point. `bulges`: the bulge (group 42) of the segment that starts at each + /// point, in drawing space; empty for straight segments only. + fn polyline(&mut self, pts: &[Point], bulges: &[f64], closed: bool, style: &EntityStyle, width: Option) { if pts.len() < 2 { return; } @@ -917,8 +1002,11 @@ impl<'a> Scene<'a> { if let Some(w) = width { self.e.num(43, w); } - for p in &pts { + for (i, p) in pts.iter().enumerate() { self.e.xy(10, p.x, p.y); + if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) { + self.e.num(42, b); + } } return; } @@ -930,13 +1018,16 @@ impl<'a> Scene<'a> { self.e.num(40, w); self.e.num(41, w); } - for p in &pts { + for (i, p) in pts.iter().enumerate() { let vh = self.handle(); self.e.entity("VERTEX", vh, h, &layer, style, "AcDbVertex"); if self.o.version.handles() { self.e.raw(100, "AcDb2dVertex"); } self.e.xyz(10, p.x, p.y); + if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) { + self.e.num(42, b); + } } let end = self.handle(); self.e.entity("SEQEND", end, h, &layer, style, ""); @@ -960,8 +1051,8 @@ impl<'a> Scene<'a> { return false; } - // Count sampled points in the drawing extents. For a full circle include all cardinal - // points exactly; for an arc, the dense samples conservatively cover its visible span. + // Count the curve's extreme points in the drawing extents: all four cardinal points of a + // full circle; an arc's ends and the cardinal points on it. if sub.closed { let r = circle.radius; for p in [ @@ -973,8 +1064,8 @@ impl<'a> Scene<'a> { self.pt(p); } } else { - for p in &circle.samples { - self.pt(*p); + for p in [sub.start, last].into_iter().chain(arc_extrema(circle.centre, circle.radius, sub.start, circle.turn)) { + self.pt(p); } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index e4984c3332..d99858511e 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -275,6 +275,197 @@ fn circles_and_circular_arcs_are_native_dxf_entities() { } } +/// A cubic arc about `c` of radius `r` from `deg0` to `deg1` (degrees, y down), from the current +/// point, which is the arc's start. +fn arc_cubic(b: &mut vectorcraft_geom::BezPath, c: Point, r: f64, deg0: f64, deg1: f64) { + let (a0, a1) = (deg0.to_radians(), deg1.to_radians()); + let k = 4.0 / 3.0 * ((a1 - a0) / 4.0).tan() * r; + let (p0, p3) = (Point::new(c.x + r * a0.cos(), c.y + r * a0.sin()), Point::new(c.x + r * a1.cos(), c.y + r * a1.sin())); + b.curve_to(Point::new(p0.x - k * a0.sin(), p0.y + k * a0.cos()), Point::new(p3.x + k * a1.sin(), p3.y - k * a1.cos()), p3); +} + +/// A slot (two lines, two half circles) about y = 50, a D shape (a half circle closed by its +/// diameter) and a rounded rectangle with 10 pt corners. +fn lines_and_arcs() -> [PathData; 3] { + let mut slot = vectorcraft_geom::BezPath::new(); + slot.move_to((60.0, 30.0)); + slot.line_to((140.0, 30.0)); + arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, -90.0, 0.0); + arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, 0.0, 90.0); + slot.line_to((60.0, 70.0)); + arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0); + arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0); + slot.close_path(); + let mut d = vectorcraft_geom::BezPath::new(); + d.move_to((150.0, 20.0)); + arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, -90.0, 0.0); + arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, 0.0, 90.0); + d.close_path(); + [PathData::from_bezpath(&slot), PathData::from_bezpath(&d), shapes::rounded_rectangle(Rect::new(20.0, 20.0, 100.0, 80.0), 10.0)] +} + +/// A polyline entity's vertices as (x, y, bulge): an LWPOLYLINE's, or those of the VERTEX +/// entities that follow a POLYLINE at `e[i]`. +fn vertices(e: &[Pairs], i: usize) -> Vec<(f64, f64, f64)> { + let mut out = vec![]; + let mut read = |o: &Pairs| { + for (code, value) in o { + let v: f64 = value.trim().parse().unwrap_or(0.0); + match code { + 10 => out.push((v, 0.0, 0.0)), + 20 => out.last_mut().expect("x before y").1 = v, + 42 => out.last_mut().expect("a vertex before its bulge").2 = v, + _ => {} + } + } + }; + if kind(&e[i]) == "LWPOLYLINE" { + read(&e[i]); + } else { + e[i + 1..].iter().take_while(|o| kind(o) == "VERTEX").for_each(&mut read); + } + out +} + +#[test] +fn paths_of_lines_and_circular_arcs_are_polylines_with_bulges() { + let [slot, d_shape, rounded] = lines_and_arcs(); + let d = doc_with(|d| { + let black = || Paint::solid(Color::BLACK); + let mut open = vectorcraft_geom::BezPath::new(); + open.move_to((10.0, 90.0)); + open.line_to((30.0, 90.0)); + arc_cubic(&mut open, Point::new(30.0, 80.0), 10.0, 90.0, 0.0); + vec![ + path(d, slot, Paint::None, black(), 1.0), + path(d, d_shape, Paint::None, black(), 1.0), + path(d, rounded, Paint::None, black(), 1.0), + path(d, PathData::from_bezpath(&open), Paint::None, black(), 1.0), + ] + }); + let b = (std::f64::consts::PI / 8.0).tan(); + for version in DxfVersion::ALL { + let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap(); + let e = entities(&out); + let polys: Vec = (0..e.len()).filter(|i| matches!(kind(&e[*i]), "LWPOLYLINE" | "POLYLINE")).collect(); + let k = kinds(&out); + assert_eq!(polys.len(), 4, "{version:?}: {k:?}"); + assert!(!k.iter().any(|k| matches!(k.as_str(), "SPLINE" | "ARC" | "CIRCLE")), "{version:?}: {k:?}"); + let want = if version.lwpolyline() { "LWPOLYLINE" } else { "POLYLINE" }; + assert!(polys.iter().all(|i| kind(&e[*i]) == want), "{version:?}: {k:?}"); + let flags: Vec = polys.iter().map(|i| get(&e[*i], 70).unwrap().parse::().unwrap() & 1).collect(); + assert_eq!(flags, [1, 1, 1, 0], "{version:?}: closed, closed, closed, open"); + // The slot's half circles turn clockwise with y up: a bulge of -1 after each long side. + assert_eq!(vertices(&e, polys[0]), [(60.0, 70.0, 0.0), (140.0, 70.0, -1.0), (140.0, 30.0, 0.0), (60.0, 30.0, -1.0)], "{version:?}"); + // The D shape: the half circle, then the straight closing edge. + assert_eq!(vertices(&e, polys[1]), [(150.0, 80.0, -1.0), (150.0, 20.0, 0.0)], "{version:?}"); + // The rounded rectangle: eight anchors, a quarter circle (bulge tan 22.5°) at each corner. + let r = vertices(&e, polys[2]); + assert_eq!(r.len(), 8, "{version:?}: {r:?}"); + let bulges: Vec = r.iter().map(|v| v.2).filter(|b| *b != 0.0).collect(); + assert!(close_to(&bulges, &[-b; 4], 1e-6), "{version:?}: {r:?}"); + // An open line then a quarter circle turning counterclockwise with y up. + let o = vertices(&e, polys[3]); + assert!( + close_to(&o.iter().flat_map(|v| [v.0, v.1, v.2]).collect::>(), &[10.0, 10.0, 0.0, 30.0, 10.0, b, 40.0, 20.0, 0.0], 1e-6), + "{version:?}: {o:?}" + ); + } +} + +#[test] +fn polylines_with_bulges_read_back_as_the_same_outline() { + for (i, shape) in lines_and_arcs().into_iter().enumerate() { + let original = shape.to_bezpath(); + let d = doc_with(|d| vec![path(d, shape, Paint::None, Paint::solid(Color::BLACK), 1.0)]); + let out = export(&d, &opts(&d)).unwrap(); + assert_eq!(kinds(&out), ["LWPOLYLINE"], "shape {i}"); + let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let back = import(&out.bytes, &o).unwrap().document; + let mut paths = vec![]; + back.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + paths.push(path.to_bezpath()); + } + }); + assert_eq!(paths.len(), 1, "shape {i}"); + assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "shape {i} reads back closed"); + let (a, b) = (original.bounding_box(), paths[0].bounding_box()); + assert!(close_to(&[a.width(), a.height()], &[b.width(), b.height()], 1e-2), "shape {i}: {a:?} against {b:?}"); + // Every point read back lies on the original outline, once both are centered. + let shift = a.center() - b.center(); + let outline: Vec = original.segments().flat_map(|s| (0..=64).map(move |t| s.eval(f64::from(t) / 64.0))).collect(); + for seg in paths[0].segments() { + for t in 0..=16 { + let p = seg.eval(f64::from(t) / 16.0) + shift; + let near = outline + .windows(2) + .map(|w| { + let (u, v) = (w[1] - w[0], p - w[0]); + let s = if u.hypot2() > 0.0 { (v.dot(u) / u.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + (v - u * s).hypot() + }) + .fold(f64::INFINITY, f64::min); + assert!(near < 1e-2, "shape {i}: {p:?} is {near} pt off the outline"); + } + } + } +} + +#[test] +fn a_path_with_a_curve_that_is_not_a_circular_arc_stays_a_spline() { + // The slot with one end drawn by a longer-handled curve. + let mut slot = vectorcraft_geom::BezPath::new(); + slot.move_to((60.0, 30.0)); + slot.line_to((140.0, 30.0)); + slot.curve_to((165.0, 30.0), (165.0, 70.0), (140.0, 70.0)); + slot.line_to((60.0, 70.0)); + arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0); + arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0); + slot.close_path(); + let d = doc_with(|d| { + vec![ + path(d, PathData::from_bezpath(&slot), Paint::None, Paint::solid(Color::BLACK), 1.0), + path(d, shapes::ellipse(Rect::new(150.0, 20.0, 190.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0), + ] + }); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "CIRCLE"]); +} + +#[test] +fn drawing_extents_reach_the_extreme_points_of_arcs() { + // An arc about (100, 50) of radius 40 from -60° to 30° passes x = 140 at 0°, between the points + // along it that recognition samples. + let arc = |closed: bool| { + let mut b = vectorcraft_geom::BezPath::new(); + let start = Point::new(100.0 + 40.0 * 60f64.to_radians().cos(), 50.0 - 40.0 * 60f64.to_radians().sin()); + b.move_to(start); + arc_cubic(&mut b, Point::new(100.0, 50.0), 40.0, -60.0, 30.0); + if closed { + b.close_path(); + } + PathData::from_bezpath(&b) + }; + for (closed, entity) in [(false, "ARC"), (true, "LWPOLYLINE")] { + let d = doc_with(|d| vec![path(d, arc(closed), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + let out = export(&d, &opts(&d)).unwrap(); + assert_eq!(kinds(&out), [entity]); + let x: f64 = header(&pairs(&out.bytes), "$EXTMAX").unwrap().trim().parse().unwrap(); + assert!((x - 140.0).abs() < 1e-6, "{entity}: $EXTMAX x {x}"); + } +} + +#[test] +fn a_shallow_curve_that_is_not_circular_is_not_an_arc() { + // 100 pt across and 1.5 pt deep: the circle through its ends and middle has a radius of about + // 834 pt, and the curve is 0.12 pt off it a quarter of the way along. + let mut b = vectorcraft_geom::BezPath::new(); + b.move_to((0.0, 50.0)); + b.curve_to((20.0, 48.0), (80.0, 48.0), (100.0, 50.0)); + let d = doc_with(|d| vec![path(d, PathData::from_bezpath(&b), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE"]); +} + /// The path `p` with `xf` applied. fn transformed(p: &PathData, xf: Affine) -> PathData { PathData::from_bezpath(&(xf * p.to_bezpath())) @@ -391,11 +582,12 @@ fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() { vec![ path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0), path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0), - // An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). + // An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). Its + // quarters fit shallow circular arcs within the tolerance, so it is a polyline with bulges. path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0), ] }); - assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "LWPOLYLINE"]); } #[test] @@ -462,8 +654,12 @@ fn closed_circular_arc_with_a_closing_chord_is_not_a_circle() { vec![path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0)] }); + // The three quarters turn counterclockwise with y up (bulge tan 67.5°), then the chord closes it. let modern = export(&d, &opts(&d)).unwrap(); - assert_eq!(kinds(&modern), ["SPLINE"]); + assert_eq!(kinds(&modern), ["LWPOLYLINE"]); + let v = vertices(&entities(&modern), 0); + let flat: Vec = v.iter().flat_map(|v| [v.0, v.1, v.2]).collect(); + assert!(close_to(&flat, &[80.0, 50.0, 67.5f64.to_radians().tan(), 50.0, 20.0, 0.0], 1e-6), "{v:?}"); let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap(); assert!(kinds(&r12).iter().any(|k| k == "POLYLINE")); assert!(!kinds(&r12).iter().any(|k| k == "CIRCLE")); @@ -497,9 +693,13 @@ fn a_closed_sliver_along_a_circle_is_not_a_circle() { vec![path(d, PathData::from_bezpath(&sliver), Paint::None, Paint::solid(Color::BLACK), 1.0)] }); + // Two arcs, out along the circle and back: one polyline with a bulge each way. let modern = export(&d, &opts(&d)).unwrap(); assert_ne!(kinds(&modern), ["CIRCLE"]); - assert_eq!(kinds(&modern), ["SPLINE"]); + assert_eq!(kinds(&modern), ["LWPOLYLINE"]); + let bulges: Vec = vertices(&entities(&modern), 0).iter().map(|v| v.2).collect(); + let b = 10f64.to_radians().tan(); + assert!(close_to(&bulges, &[-b, b], 1e-6) || close_to(&bulges, &[b, -b], 1e-6), "{bulges:?}"); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2bbeeb404a..20dae8ba93 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1168,6 +1168,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. - EPS and PostScript `.ai` import undoes the TIFF predictor (`/Predictor 2`) of `FlateDecode` and `LZWDecode` data at 1, 2, 4 and 16 bits a component as well as 8: each component adds the same component of the pixel to its left within its bit width, 16-bit components add as big-endian numbers, and each row starts again (ISO 32000-1 §7.4.4.4; `crates/eps/src/import/tests_images.rs`, `crates/engine/src/cmd/fileio/tests_epsimport.rs`). At those depths the image drew the stored differences instead of its samples. - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); CNC preset and VCarve QA remain pending. + - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). From 65f55d65ea9681ab40ec50c24a204f3b90cece5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:03:59 -0800 Subject: [PATCH 19/50] .ai save: errors and notes name the legacy or non-PDF-compatible .ai Option errors and notes for a .ai save called the file a "PDF-compatible .ai" even when the save wrote a version 7 file (aiVersion: "7") or a file without PDF content (pdfCompatible: false). - Option errors: a version 7 .ai is now called a "legacy .ai (version 7)" in the errors for its artboard, artboards and range options. A .ai saved without PDF content is called a "non-PDF-compatible .ai" in every .ai option error (includeLinked and embedProfiles included), and a "non-PDF-compatible .ait template" when Save as Template writes it. aiVersion: "7" takes precedence over pdfCompatible: false, as it does when the file is written. - The error for encoding a version 7 .ai of several artboards as one file names the legacy .ai. - The note for a native option the file does not read (version, preview, precision) names the same kind of file. - The error for aiVersion: "7" on a .ait template no longer says that a .ait template is always PDF-compatible, since Save as Template writes one without PDF content. It now reads "aiVersion 7 writes legacy .ai files, not .ait templates", with its rows in the message catalogs updated. A PDF-compatible file keeps its name. --- crates/engine/src/cmd/fileio/encode.rs | 5 ++- crates/engine/src/cmd/fileio/legacy_ai.rs | 12 +++++-- crates/engine/src/cmd/fileio/save.rs | 38 ++++++++++++++++++----- crates/engine/src/tests/legacy_ai.rs | 25 +++++++++++++++ crates/engine/src/tests/saveoptions.rs | 27 ++++++++++++++++ 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/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- 27 files changed, 117 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index a807010711..b125e48a88 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -420,7 +420,10 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result> { /// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame). pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec, Vec)> { let f = super::writable(C, Some(format), None)?; - encode_all(doc, f.id, p)?.single(f) + let enc = encode_all(doc, f.id, p)?; + // The error for a version 7 .ai of several artboards names the legacy .ai. + let legacy = f.id == "ai" && super::legacy_ai::wanted(C, f, p)?; + enc.single(&if legacy { super::legacy_ai::named(f) } else { *f }) } /// [`encode`], with every file the export writes. diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 1d9d23590f..d4820242d9 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -41,7 +41,7 @@ use super::super::{Affine, EngineError, NodeId, Result, bad}; use super::{ArtboardPick, Encoded, Format}; /// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown -/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only. +/// version is an error, and so is version 7 for a `.ait` template, which is never a legacy file. pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result { let legacy = match p.get("aiVersion") { None | Some(Value::Null) => false, @@ -51,11 +51,17 @@ pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result { Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))), }; if legacy && f.id == "ait" { - return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible")); + return Err(bad(cmd, "aiVersion 7 writes legacy .ai files, not .ait templates")); } Ok(legacy) } +/// `f` (the `.ai` format, whose label names the PDF-compatible file) named, in its errors, as the +/// legacy `.ai` file. +pub(super) fn named(f: &Format) -> Format { + Format { label: "legacy .ai (version 7)", ..*f } +} + /// What a legacy `.ai` does with the images it can't hold (`transparentImages`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SeeThrough { @@ -109,7 +115,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result } let mode = see_through(cmd, p)?; let (hidden, outline_text) = (hidden_objects(cmd, p)?, outline_text(cmd, p)?); - let picked: ArtboardPick = super::encode::options(f, p)?; + let picked: ArtboardPick = super::encode::options(&named(f), p)?; let boards = picked.resolve(n).map_err(|e| bad(cmd, e))?.unwrap_or_else(|| (0..n).collect()); let mut enc = Encoded { warnings: vec![FIDELITY.to_string()], ..Encoded::default() }; if boards.len() > 1 { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index de67968dad..89339850ea 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -249,11 +249,6 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? { return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once"))); } - let notes = NATIVE_OPTIONS - .iter() - .filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k)) - .map(|k| format!("`{k}` was not used: {} files don't read it", format.label)) - .collect(); let mut given: Map = match p.get("options") { Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(), None | Some(Value::Null) => Map::new(), @@ -293,6 +288,12 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { if let Some(path) = &path { super::check_not_lossy_overwrite(st, path, p, cmd)?; } + let written = written_as(cmd, format, &Value::Object(options.clone())); + let notes = NATIVE_OPTIONS + .iter() + .filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k)) + .map(|k| format!("`{k}` was not used: {} files don't read it", written.label)) + .collect(); Ok(SavePlan { mode, path, format, options, name, folder, modified, notes }) } @@ -576,6 +577,25 @@ fn blank_pages(doc: &Document) -> Document { /// Why a `.ai` file saved without PDF content looks empty elsewhere. const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages"; +/// `f` (`.ai` or `.ait`) named, in its option errors, as a file saved without PDF content. +fn without_pdf(f: &Format) -> Format { + let label = if f.id == "ait" { "non-PDF-compatible .ait template" } else { "non-PDF-compatible .ai" }; + Format { label, ..*f } +} + +/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7 +/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved +/// without PDF content. +fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { + if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) { + super::legacy_ai::named(f) + } else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) { + without_pdf(f) + } else { + *f + } +} + /// `e`, an error of the export encoders, under the save command `cmd` instead of /// `document.export`. fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError { @@ -585,8 +605,9 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError { } } -/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the -/// same file). +/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file): +/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7 +/// `.ai` files (`aiVersion: "7"`). pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result { if super::legacy_ai::wanted(cmd, f, p)? { return super::legacy_ai::encode(cmd, f, doc, p); @@ -605,8 +626,9 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res } } } - let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?; let pdf_compatible = bool_or(¶ms, "pdfCompatible", true); + let f = &if pdf_compatible { *f } else { without_pdf(f) }; + let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?; if !pdf_compatible { let picked: ArtboardPick = super::encode::options(f, ¶ms)?; let picked = picked.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?; diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 90c728a2fc..70218cf76a 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -93,6 +93,31 @@ fn the_default_stays_pdf_compatible_and_other_versions_are_refused() { assert_eq!(v["options"]["aiVersion"]["value"], "pdf", "{v}"); } +#[test] +fn errors_name_the_legacy_ai_not_the_pdf_compatible_one() { + let mut s = three_boards(); + for (cmd, p) in [ + ("file.saveCopy", json!({"format": "ai", "aiVersion": "7", "artboard": "2"})), + ("document.export", json!({"format": "ai", "aiVersion": "7", "range": 2})), + ] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("legacy .ai (version 7) options: invalid type") && !e.contains("PDF-compatible"), "{cmd}: {e}"); + } + // Version 7 writes a legacy .ai whatever pdfCompatible says, and its errors and notes name it. + let e = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string(); + assert!(e.contains("legacy .ai (version 7) options: invalid type"), "{e}"); + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "artboard": 1, "version": 3})).unwrap(); + assert!(r["warnings"].to_string().contains("`version` was not used: legacy .ai (version 7) files don't read it"), "{r}"); + // Several artboards are several files, which one encoded file can't hold. + let d = &s.doc().unwrap().doc; + let e = crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7"})).unwrap_err().to_string(); + assert!(e.contains("legacy .ai (version 7) writes one file per artboard here") && !e.contains("PDF-compatible"), "{e}"); + assert!(crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7", "artboard": 2})).is_ok()); + // The PDF-compatible file keeps its name. + let e = s.execute("document.export", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string(); + assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("legacy"), "{e}"); +} + #[test] fn transparency_and_appearances_are_written_as_plain_art_and_type_as_text() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index d52cbba610..2a55357eb7 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -213,6 +213,33 @@ fn ai_without_pdf_content_and_compression() { assert!(loose.len() > packed.len(), "{} vs {}", loose.len(), packed.len()); } +#[test] +fn ai_option_errors_name_a_file_saved_without_pdf_content() { + let mut s = three_boards(); + for p in + [json!({"format": "ai", "pdfCompatible": false, "artboard": "2"}), json!({"format": "ai", "pdfCompatible": false, "includeLinked": "yes"})] + { + let e = s.execute("file.saveCopy", &p).unwrap_err().to_string(); + assert!(e.contains("non-PDF-compatible .ai options: invalid type"), "{p}: {e}"); + } + let e = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string(); + assert!(e.contains("`document.export`") && e.contains("non-PDF-compatible .ai options: invalid type"), "{e}"); + let p = json!({"format": "ait", "pdfCompatible": false, "includeLinked": "yes"}); + let e = s.execute("file.saveAsTemplate", &p).unwrap_err().to_string(); + assert!(e.contains("non-PDF-compatible .ait template options: invalid type"), "{e}"); + // A template saved without PDF content is written. + let r = s.execute("file.saveAsTemplate", &json!({"format": "ait", "pdfCompatible": false})).unwrap(); + assert!(r["warnings"].to_string().contains("without PDF content"), "{r}"); + // So are the notes on native options the file doesn't read. + let r = s.execute("file.saveCopy", &json!({"format": "ai", "pdfCompatible": false, "version": 3})).unwrap(); + assert!(r["warnings"].to_string().contains("`version` was not used: non-PDF-compatible .ai files don't read it"), "{r}"); + // A PDF-compatible file keeps its name. + let e = s.execute("file.saveCopy", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string(); + assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("non-PDF"), "{e}"); + let r = s.execute("file.saveCopy", &json!({"format": "ai", "version": 3})).unwrap(); + assert!(r["warnings"].to_string().contains("`version` was not used: PDF-compatible .ai files don't read it"), "{r}"); +} + #[test] fn a_remembered_artboard_the_document_no_longer_has_is_dropped() { let dir = Folder::new("remembered-artboards"); diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 705c5d7e76..20744b85ee 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4256,7 +4256,7 @@ imageTrace Outline Obris @msg Save for Web: the image is empty Sačuvaj za web: slika je prazna @msg Save writes {_1}, not {_2}: use document.export for other formats Sačuvaj zapisuje {_1}, a ne {_2}: za druge formate koristite document.export @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Sačuvaj zapisuje {_1}, a ne {_2}: za zapisivanje koristite file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje naslijeđene .ai datoteke; .ait predložak je uvijek kompatibilan s PDF-om +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje naslijeđene .ai datoteke, a ne .ait predloške @msg Saved recovery data for {title} Sačuvani podaci za oporavak za {title} @msg Saved to User Defined: {_1} Sačuvano u korisnički definisano: {_1} @msg Saved {path} Sačuvano: {path} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 97d2024dde..02ccc19399 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4920,7 +4920,7 @@ digits Malayalam Malaiàlam @msg a {width}×{height} screenshot's byte count overflows el recompte de bytes d’una captura de pantalla de {width}×{height} es desborda @msg action is required cal una acció @msg add a format to export afegiu un format per exportar -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 escriu fitxers .ai heretats; una plantilla .ait sempre és compatible amb PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 escriu fitxers .ai heretats, no plantilles .ait @msg already editing a pattern ja s’està editant un motiu @msg an exporter always gets an export's budget: leave `budget` out un exportador sempre rep el pressupost d’una exportació: ometeu `budget` @msg an image has no pixels and was left out una imatge no té píxels i s’ha omès diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 56228845db..aa81fbca3c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4304,7 +4304,7 @@ imageTrace Outline Obrys @msg Save for Web: the image is empty Uložit pro web: obraz je prázdný @msg Save writes {_1}, not {_2}: use document.export for other formats Uložení zapisuje {_1}, ne {_2}: pro jiné formáty použijte document.export @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Uložení zapisuje {_1}, ne {_2}: k jeho zápisu použijte file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje starší soubory .ai; šablona .ait je vždy kompatibilní s PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje starší soubory .ai, ne šablony .ait @msg Saved recovery data for {title} Data pro obnovení uložena pro {title} @msg Saved to User Defined: {_1} Uloženo do uživatelských knihoven: {_1} @msg Saved {path} Uloženo: {path} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 11793dc22b..0e1bf7ece6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3911,7 +3911,7 @@ theme Appearance Erscheinungsbild @msg Save for Web: the image is empty Für Web speichern: Das Bild ist leer @msg Save writes {_1}, not {_2}: use document.export for other formats „Speichern“ schreibt {_1}, nicht {_2}: Verwenden Sie document.export für andere Formate @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it „Speichern“ schreibt {_1}, nicht {_2}: Verwenden Sie dafür file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 schreibt ältere .ai-Dateien; eine .ait-Vorlage ist immer PDF-kompatibel +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 schreibt ältere .ai-Dateien, keine .ait-Vorlagen @msg Saved recovery data for {title} Wiederherstellungsdaten für {title} gespeichert @msg Saved to User Defined: {_1} In „Benutzerdefiniert“ gespeichert: {_1} @msg Saved {path} {path} gespeichert diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 687a4a8e88..01471ba16b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2203,7 +2203,7 @@ axis Both Και τα δύο @msg Save for Web: the image is empty Αποθήκευση για ιστό: η εικόνα είναι κενή @msg Save writes {_1}, not {_2}: use document.export for other formats Η αποθήκευση γράφει {_1}, όχι {_2}: χρησιμοποιήστε το document.export για άλλες μορφές @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Η αποθήκευση γράφει {_1}, όχι {_2}: χρησιμοποιήστε το file.saveAsTemplate για να το γράψετε -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible Το aiVersion 7 γράφει αρχεία .ai παλαιού τύπου· ένα πρότυπο .ait είναι πάντα συμβατό με PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates Το aiVersion 7 γράφει αρχεία .ai παλαιού τύπου, όχι πρότυπα .ait @msg Saved recovery data for {title} Αποθηκεύτηκαν δεδομένα ανάκτησης για το {title} @msg Saved to User Defined: {_1} Αποθηκεύτηκε στις προσαρμοσμένες ρυθμίσεις: {_1} @msg Saved {path} Αποθηκεύτηκε το {path} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index eb0aeaeaba..b68ba40d6f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3996,7 +3996,7 @@ axis Both Ambos @msg Save for Web: the image is empty Guardar para web: la imagen está vacía @msg Save writes {_1}, not {_2}: use document.export for other formats Guardar escribe {_1}, no {_2}: usa document.export para otros formatos @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Guardar escribe {_1}, no {_2}: usa file.saveAsTemplate para escribirlo -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 escribe archivos .ai heredados; una plantilla .ait siempre es compatible con PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 escribe archivos .ai heredados, no plantillas .ait @msg Saved recovery data for {title} Se guardaron los datos de recuperación de {title} @msg Saved to User Defined: {_1} Se guardó en Definido por el usuario: {_1} @msg Saved {path} Se guardó {path} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 806ad1dbd7..e44dac5b1a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4218,7 +4218,7 @@ imageTrace Outline Ääriviiva @msg Save for Web: the image is empty Tallenna verkkoon: kuva on tyhjä @msg Save writes {_1}, not {_2}: use document.export for other formats Tallenna kirjoittaa muotoa {_1}, ei {_2}: käytä muille muodoille komentoa document.export @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Tallenna kirjoittaa muotoa {_1}, ei {_2}: kirjoita se komennolla file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 kirjoittaa vanhoja .ai-tiedostoja; .ait-malli on aina PDF-yhteensopiva +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 kirjoittaa vanhoja .ai-tiedostoja, ei .ait-malleja @msg Saved recovery data for {title} Tallennettiin palautustiedot: {title} @msg Saved to User Defined: {_1} Tallennettiin kohteeseen Käyttäjän määrittämä: {_1} @msg Saved {path} Tallennettiin {path} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f646102576..e435b22b8b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3986,7 +3986,7 @@ axis Both Les deux @msg Save for Web: the image is empty Enregistrer pour le Web : l’image est vide @msg Save writes {_1}, not {_2}: use document.export for other formats Enregistrer écrit du {_1}, pas du {_2} : utilisez document.export pour les autres formats @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Enregistrer écrit du {_1}, pas du {_2} : utilisez file.saveAsTemplate pour l’écrire -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 écrit des fichiers .ai hérités, alors qu’un modèle .ait est toujours compatible PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 écrit des fichiers .ai hérités, pas des modèles .ait @msg Saved recovery data for {title} Données de récupération enregistrées pour {title} @msg Saved to User Defined: {_1} Enregistré dans Défini par l’utilisateur : {_1} @msg Saved {path} {path} enregistré diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d5c9f279ad..1b6037294e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5103,7 +5103,7 @@ imageTrace Outline Körvonal @msg Save for Web: the image is empty Mentés webre: a kép üres @msg Save writes {_1}, not {_2}: use document.export for other formats a Mentés ezt írja: {_1}, ezt nem: {_2}; más formátumhoz használd a document.export parancsot @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it a Mentés ezt írja: {_1}, ezt nem: {_2}; ennek írásához használd a file.saveAsTemplate parancsot -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible az aiVersion 7 régi .ai fájlokat ír; egy .ait sablon mindig PDF-kompatibilis +@msg aiVersion 7 writes legacy .ai files, not .ait templates az aiVersion 7 régi .ai fájlokat ír, nem .ait sablonokat @msg saved panel layout is invalid; reset the workspace first a mentett panelelrendezés érvénytelen; előbb állítsd vissza a munkaterületet @msg Saved recovery data for {title} Helyreállítási adatok mentve: {title} @msg Saved to User Defined: {_1} Mentve a felhasználóiak közé: {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c95b9d71d5..f51eb524aa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4038,7 +4038,7 @@ axis Both Entrambi @msg Save for Web: the image is empty Salva per il web: l'immagine è vuota @msg Save writes {_1}, not {_2}: use document.export for other formats Salva scrive {_1}, non {_2}: usa document.export per gli altri formati @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Salva scrive {_1}, non {_2}: usa file.saveAsTemplate per scriverlo -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 scrive file .ai tradizionali; un modello .ait è sempre compatibile PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 scrive file .ai tradizionali, non modelli .ait @msg Saved recovery data for {title} Dati di recupero salvati per {title} @msg Saved to User Defined: {_1} Salvato in Definito dall'utente: {_1} @msg Saved {path} Salvato {path} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index eb3d1fc5e9..8630535a52 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4153,7 +4153,7 @@ swatch Bright Violet ビビッドバイオレット @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: この環境にはファイルシステムがありません (開くには dataBase64 を渡し、dataBase64 を受け取るにはパスを省略してください) @msg Save writes {_1}, not {_2}: use document.export for other formats 保存できる形式は {_1} のみで、{_2} 形式では保存できません: ほかの形式には document.export を使用してください @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 保存できる形式は {_1} のみで、{_2} 形式では保存できません: この形式で保存するには file.saveAsTemplate を使用してください -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 は従来の .ai ファイルを書き出します。.ait テンプレートは常に PDF 互換です +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 は従来の .ai ファイルを書き出し、.ait テンプレートは書き出しません @msg no changes since the last save 前回の保存以降、変更はありません @msg unknown format `{f}` (Save writes {_1}) `{f}` は不明な形式です (保存できる形式: {_1}) @msg `svg` must be an object of SVG options (see document.formats) `svg` には SVG オプションのオブジェクトを指定してください (document.formats を参照) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a504987b65..6cf5cdb6b4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5521,7 +5521,7 @@ imageTrace Outline კონტური @msg its editing data is for a {w} × {h} pt page, the file's {pw} × {ph} pt page at {scale} მისი რედაქტირების მონაცემები {w} × {h} pt გვერდს ეკუთვნის: ეს ფაილის {pw} × {ph} pt გვერდია მასშტაბით {scale} @msg no history to clear გასასუფთავებელი ისტორია არ არის @msg {_1} files are written by file.saveAsTemplate {_1} ფაილებს წერს file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 წერს ძველი ფორმატის .ai ფაილებს; .ait შაბლონი ყოველთვის PDF-თან თავსებადია +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 წერს ძველი ფორმატის .ai ფაილებს და არა .ait შაბლონებს @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest ფაილის ცვლადების ბიბლიოთეკა მხოლოდ ნაწილობრივ იქნა წაკითხული (გამოტოვებული ჩანაწერები: {_1}): პანელი „ცვლადები“ დანარჩენს აჩვენებს @msg the file's variable library couldn't be read: the Variables panel doesn't list it ფაილის ცვლადების ბიბლიოთეკის წაკითხვა ვერ მოხერხდა: პანელი „ცვლადები“ მას არ აჩვენებს @msg a variable of unknown kind can't be bound to objects უცნობი სახის ცვლადის ობიექტებთან დაკავშირება შეუძლებელია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1702c2d15d..338be6dce0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4080,7 +4080,7 @@ theme Appearance 외관 @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: 여기에는 파일 시스템이 없습니다(열려면 dataBase64를 전달하고, dataBase64를 얻으려면 경로를 생략하세요) @msg Save writes {_1}, not {_2}: use document.export for other formats 저장은 {_2}이(가) 아닌 {_1}(으)로 기록합니다. 다른 형식은 document.export를 사용하세요 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 저장은 {_2}이(가) 아닌 {_1}(으)로 기록합니다. 이 형식으로 기록하려면 file.saveAsTemplate를 사용하세요 -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7은(는) 레거시 .ai 파일을 기록합니다. .ait 템플릿은 항상 PDF 호환입니다 +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7은(는) 레거시 .ai 파일을 기록하며 .ait 템플릿은 기록하지 않습니다 @msg no changes since the last save 마지막 저장 이후 변경 내용이 없습니다 @msg unknown format `{f}` (Save writes {_1}) 알 수 없는 형식 `{f}`(저장은 {_1}(으)로 기록) @msg `svg` must be an object of SVG options (see document.formats) `svg`는 SVG 옵션 개체여야 합니다(document.formats 참조) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a2bce6ac59..4cb23d6ac5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4127,7 +4127,7 @@ imageTrace Outline Kontur @msg Save for Web: the image is empty Zapisz dla Internetu: obraz jest pusty @msg Save writes {_1}, not {_2}: use document.export for other formats Zapis tworzy {_1}, nie {_2}: dla innych formatów użyj document.export @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Zapis tworzy {_1}, nie {_2}: aby go zapisać, użyj file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje starsze pliki .ai; szablon .ait jest zawsze zgodny z PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje starsze pliki .ai, a nie szablony .ait @msg Saved recovery data for {title} Zapisano dane odzyskiwania dla {title} @msg Saved to User Defined: {_1} Zapisano w zdefiniowanych przez użytkownika: {_1} @msg Saved {path} Zapisano {path} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b6efe4bf7b..f53f0798e9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3590,7 +3590,7 @@ axis Both Ambos @msg Save for Web: the image is empty Salvar para Web: a imagem está vazia @msg Save writes {_1}, not {_2}: use document.export for other formats Salvar grava {_1}, não {_2}: use document.export para outros formatos @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Salvar grava {_1}, não {_2}: use file.saveAsTemplate para gravá-lo -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 grava arquivos .ai legados; um modelo .ait é sempre compatível com PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 grava arquivos .ai legados, não modelos .ait @msg Saved recovery data for {title} Dados de recuperação de {title} salvos @msg Saved to User Defined: {_1} Salvo em Definido pelo usuário: {_1} @msg Saved {path} {path} salvo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 999b1f1553..c5a493ad84 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4033,7 +4033,7 @@ axis Both Оба @msg Save for Web: the image is empty Сохранить для web: изображение пусто @msg Save writes {_1}, not {_2}: use document.export for other formats Сохранение записывает {_1}, а не {_2}: используйте document.export для других форматов @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Сохранение записывает {_1}, а не {_2}: чтобы записать его, используйте file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 записывает устаревшие файлы .ai; шаблон .ait всегда совместим с PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 записывает устаревшие файлы .ai, а не шаблоны .ait @msg Saved recovery data for {title} Сохранены данные восстановления для {title} @msg Saved to User Defined: {_1} Сохранено в «Пользовательский»: {_1} @msg Saved {path} Сохранено: {path} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7f815addf6..77d5c41b6d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3907,7 +3907,7 @@ axis Both Båda @msg Save for Web: the image is empty Spara för webb: bilden är tom @msg Save writes {_1}, not {_2}: use document.export for other formats Spara skriver {_1}, inte {_2}: använd document.export för andra format @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Spara skriver {_1}, inte {_2}: använd file.saveAsTemplate för att skriva det -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 skriver äldre .ai-filer; en .ait-mall är alltid PDF-kompatibel +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 skriver äldre .ai-filer, inte .ait-mallar @msg Saved recovery data for {title} Sparade återställningsdata för {title} @msg Saved to User Defined: {_1} Sparat i Användardefinierat: {_1} @msg Saved {path} Sparade {path} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 0517c552a8..efbcf69343 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5402,7 +5402,7 @@ theme Appearance Görünüm @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS} veri setinden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_ROWS} tane okur @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS} değişkenden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_COLS} tane okur @msg x and y must be finite x ve y sonlu olmalıdır -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 eski .ai dosyalarını yazar; bir .ait şablonu her zaman PDF uyumludur +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 eski .ai dosyalarını yazar, .ait şablonlarını yazmaz @msg Edit Original opens image and document files only; “{name}” is not one Özgünü Düzenle yalnızca görüntü ve belge dosyalarını açar; “{name}” bunlardan biri değil @msg its editing data is for a {w} × {h} pt page, not the file's {pw} × {ph} pt page düzenleme verileri {w} × {h} pt boyutunda bir sayfa içindir, dosyanın {pw} × {ph} pt sayfası için değil @msg its editing data is for a {w} × {h} pt page, the file's {pw} × {ph} pt page at {scale} düzenleme verileri {w} × {h} pt boyutunda bir sayfa içindir, dosyanın {scale} ölçeğindeki {pw} × {ph} pt sayfası diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 71d3310321..b7d8962a90 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4022,7 +4022,7 @@ axis Both Обидві @msg Save for Web: the image is empty Зберегти для Інтернету: зображення пусте @msg Save writes {_1}, not {_2}: use document.export for other formats Збереження записує {_1}, а не {_2}: використовуйте document.export для інших форматів @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Збереження записує {_1}, а не {_2}: щоб записати його, використовуйте file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 записує застарілі файли .ai; шаблон .ait завжди сумісний із PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 записує застарілі файли .ai, а не шаблони .ait @msg Saved recovery data for {title} Збережено дані відновлення для {title} @msg Saved to User Defined: {_1} Збережено в «Користувацькі»: {_1} @msg Saved {path} Збережено: {path} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8110a2d206..41a5d4c64a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4757,7 +4757,7 @@ theme Appearance Giao diện @msg Save for Web: the image is empty Lưu cho Web: ảnh trống @msg Save writes {_1}, not {_2}: use document.export for other formats Lưu ghi {_1}, không phải {_2}: dùng document.export cho các định dạng khác @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Lưu ghi {_1}, không phải {_2}: dùng file.saveAsTemplate để ghi định dạng này -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 ghi tệp .ai cũ; mẫu .ait luôn tương thích PDF +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 ghi tệp .ai cũ, không ghi mẫu .ait @msg saved panel layout is invalid; reset the workspace first bố cục bảng đã lưu không hợp lệ; hãy đặt lại không gian làm việc trước @msg Saved recovery data for {title} Đã lưu dữ liệu phục hồi cho {title} @msg Saved to User Defined: {_1} Đã lưu vào Người dùng tùy chỉnh: {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index aaf791fea2..8e383be64c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5434,7 +5434,7 @@ lighting Light 光源 Enable Guides for 9-Slice Scaling 启用 9-slice 缩放参考线 @msg cancelled; nothing was changed 已取消;未做任何更改 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 保存会写入 {_1},而不是 {_2}:要写入该格式请使用 file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 写入旧版 .ai 文件;.ait 模板始终与 PDF 兼容 +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 写入旧版 .ai 文件,不写入 .ait 模板 @msg a mask has more than one art block 蒙版包含多个图稿块 @msg mask art ends outside a mask dictionary 蒙版图稿在蒙版字典之外结束 @msg `{key}` must be a #rrggbb color `{key}` 必须是 #rrggbb 格式的颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0bf8bf80b..e401ee090f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2496,7 +2496,7 @@ file-filter Templates 範本 @msg the action has no steps 動作沒有步驟 @msg cancelled; nothing was changed 已取消;未做任何變更 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 「儲存」會寫入 {_1},而非 {_2}:若要寫入該格式,請使用 file.saveAsTemplate -@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 會寫入舊版 .ai 檔案;.ait 範本一律與 PDF 相容 +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 會寫入舊版 .ai 檔案,不會寫入 .ait 範本 @msg a mask has more than one art block 遮色片含有多個圖稿區塊 @msg mask art ends outside a mask dictionary 遮色片圖稿在遮色片字典之外結束 @msg `{key}` must be a #rrggbb color `{key}` 必須是 #rrggbb 格式的顏色 From 8f66e2b694ef0c2688eac9e4930621065a6f359c Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:10:59 +0530 Subject: [PATCH 20/50] Focusing an open tab closes Home, checks read roots and waits for dialogs Follow-ups to #5369 (#5420), from its last review: - Home shown over the document asked for again gives way to it. - Automation confined to some folders can't reach an open document outside them: open_file checks read access before looking for a tab. - While a dialog or a drag acts on the active document, a document asked for again comes to the front once it ends (opening::poll), as a file that finishes opening already does. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/io/open.rs | 14 +++++++- crates/ui-egui/src/opening.rs | 16 +++++++-- crates/ui-egui/src/tests/home.rs | 60 ++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index ace4f2694e..370fc9c069 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -247,6 +247,8 @@ fn try_activate_open_document(app: &mut VectorcraftApp, path: &str) -> Result Result /// [`open_path`]; with `background`, a document (not a file that installs, imports or asks /// first) is decoded off the UI thread ([`crate::opening::start`]). pub(crate) fn open_file(app: &mut VectorcraftApp, path: &str, background: bool) -> Result { + // Automation confined to some folders reaches no file outside them, open in a tab or not. + vectorcraft_engine::file_access::check_read(path)?; // File › Open, Open Recent, the Home screen, a drop and the Finder all focus a document that - // is already open, or still being read, instead of opening a second copy. + // is already open, or still being read, instead of opening a second copy. While a dialog or + // a drag acts on the active document, its tab comes to the front once that ends + // ([`crate::opening::poll`]), as a file that finishes opening then does. + if document_index_for_path(app, path).is_some() && !crate::opening::may_switch(app) { + if !app.opening.activate.iter().any(|p| same_open_path(p, path)) { + app.opening.activate.push(path.to_string()); + } + return Ok(Value::Null); + } if let Some(r) = try_activate_open_document(app, path)? { return Ok(r); } diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 6de2fe0f74..37eca5b627 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -29,6 +29,9 @@ pub struct Pending { #[derive(Default)] pub struct Opening { pub pending: Vec, + /// Open documents asked for again while the active one couldn't change: their tabs come to + /// the front once it can ([`may_switch`]). + pub activate: Vec, } /// Is a long operation running that should show the busy cursor and status spinner (background @@ -84,6 +87,12 @@ pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec) -> Result bool { + let s = &app.session; + !(app.ui.dialog.is_some() || s.in_interaction() || (s.tool_busy() && s.pointer_held())) +} + /// Open the files that are ready (each frame). Not while a dialog is open: a document that opens /// becomes the active one, and the dialog's OK acts on the active document (#1694: Save As /// options confirmed after another file had finished opening saved that file's art under the @@ -94,10 +103,13 @@ pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec) -> Result (VectorcraftApp, std::path::PathBuf, String) { + let services = crate::Services { + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services); + let d = std::env::temp_dir().join(format!("vc-reopen-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let path = d.join("doc.vectorcraft").to_string_lossy().to_string(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("file.new", json!({})).unwrap(); + assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(1))); + (app, d, path) +} + +/// Home shown over the document asked for gives way to it, as it does to any other tab (#5369). +#[test] +fn reopening_the_active_document_closes_home() { + let (mut app, d, path) = saved_and_another("home"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("app.home", json!({})).unwrap(); + assert!(crate::menus::home_showing(&app)); + assert_eq!(crate::io::open_reporting(&mut app, &path).unwrap()["activated"], true); + assert!(!crate::menus::home_showing(&app)); + let _ = std::fs::remove_dir_all(d); +} + +/// Automation confined to a folder can't reach an open document saved outside it (#5369). +#[test] +fn a_confined_open_does_not_reach_an_open_document_outside_its_roots() { + use vectorcraft_engine::file_access; + let (mut app, d, path) = saved_and_another("roots"); + let inside = d.join("inside"); + std::fs::create_dir_all(&inside).unwrap(); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + assert!(file_access::confine(roots.as_ref(), || app.run("file.open", json!({"path": path}))).is_err()); + assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(1))); + let _ = std::fs::remove_dir_all(d); +} + +/// While a dialog acts on the active document, an open document asked for again comes to the +/// front only once the dialog closes, so the dialog's OK acts on its own document (#5369). +#[test] +fn reopening_while_a_dialog_is_open_waits_for_it_to_close() { + let (mut app, d, path) = saved_and_another("dialog"); + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + assert_eq!(crate::io::open_reporting(&mut app, &path).unwrap(), serde_json::Value::Null); + crate::opening::poll(&mut app); + assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(1)), "still the dialog's document"); + app.ui.dialog = None; + crate::opening::poll(&mut app); + assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(0))); + let _ = std::fs::remove_dir_all(d); +} From 72cf1a9b3ccf3b60c97de75287ed3b26ac559018 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:56:56 +0530 Subject: [PATCH 21/50] Queued tab activations keep the file access scope they were asked in A document asked for again while a dialog was open was queued by path only, and opened later in the scope of the frame that ran the queue. A request confined to automation roots could then read a file outside them, if the document was closed meanwhile and its path became a link out of the roots. Each queued activation now carries its ScopeHandle and runs in it, as background opens already do. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/io/open.rs | 5 +++-- crates/ui-egui/src/opening.rs | 8 ++++---- crates/ui-egui/src/tests/home.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 370fc9c069..d9d2b470a0 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -282,8 +282,9 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, path: &str, background: bool) // a drag acts on the active document, its tab comes to the front once that ends // ([`crate::opening::poll`]), as a file that finishes opening then does. if document_index_for_path(app, path).is_some() && !crate::opening::may_switch(app) { - if !app.opening.activate.iter().any(|p| same_open_path(p, path)) { - app.opening.activate.push(path.to_string()); + if !app.opening.activate.iter().any(|(p, _)| same_open_path(p, path)) { + let scope = vectorcraft_engine::file_access::ScopeHandle::capture(); + app.opening.activate.push((path.to_string(), scope)); } return Ok(Value::Null); } diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 37eca5b627..e234634937 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -30,8 +30,8 @@ pub struct Pending { pub struct Opening { pub pending: Vec, /// Open documents asked for again while the active one couldn't change: their tabs come to - /// the front once it can ([`may_switch`]). - pub activate: Vec, + /// the front once it can ([`may_switch`]), each in the file access scope it was asked in. + pub activate: Vec<(String, ScopeHandle)>, } /// Is a long operation running that should show the busy cursor and status spinner (background @@ -106,9 +106,9 @@ pub fn poll(app: &mut VectorcraftApp) { if !may_switch(app) { return; } - for path in std::mem::take(&mut app.opening.activate) { + for (path, scope) in std::mem::take(&mut app.opening.activate) { // Closed meanwhile, it opens again; a failure is reported to the user there. - let _ = crate::io::open_reporting(app, &path); + let _ = scope.run(|| crate::io::open_reporting(app, &path)); } let mut i = 0; while let Some(p) = app.opening.pending.get(i) { diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 9474408b7a..96f50716db 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -409,3 +409,32 @@ fn reopening_while_a_dialog_is_open_waits_for_it_to_close() { assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(0))); let _ = std::fs::remove_dir_all(d); } + +/// A document asked for under automation roots while a dialog is open comes to the front, or +/// opens again, in those roots once the dialog closes, not in the scope of the frame that runs it +/// (#5369): closed meanwhile and now a link to a file outside the roots, it is not read. +#[cfg(unix)] +#[test] +fn a_queued_reopen_keeps_the_roots_it_was_asked_in() { + use vectorcraft_engine::file_access; + let (mut app, d, _) = saved_and_another("queued-roots"); + let (inside, outside) = (d.join("inside"), d.join("outside")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let path = inside.join("doc.vectorcraft").to_string_lossy().to_string(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + assert_eq!(file_access::confine(roots.as_ref(), || crate::io::open_reporting(&mut app, &path)).unwrap(), serde_json::Value::Null); + // Closed, and its file swapped for a link to one outside the roots. + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + let away = outside.join("doc.vectorcraft"); + std::fs::rename(&path, &away).unwrap(); + std::os::unix::fs::symlink(&away, &path).unwrap(); + app.ui.dialog = None; + crate::opening::poll(&mut app); + assert_eq!(app.session.documents().len(), 1, "the file outside the roots is not opened"); + let _ = std::fs::remove_dir_all(d); +} From e2c8c503c1dc35673b3a2c636677c3be166cf974 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:28:47 +0530 Subject: [PATCH 22/50] opening::poll stops once a queued reopen asks a question A document asked for again while a dialog was open, and closed meanwhile, opens again when the dialog closes and may ask about its links or fonts. poll went on to finish the files read meanwhile, and each became the active document under that dialog. It now checks may_switch after each queued activation and leaves the rest, and the files ready to open, for a later frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/opening.rs | 14 ++++++++---- crates/ui-egui/src/opening/tests.rs | 35 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index e234634937..1a816f2d8b 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -103,10 +103,16 @@ pub(crate) fn may_switch(app: &VectorcraftApp) -> bool { /// waiting between its clicks (the Dimension tool after its first point): the file opens, and the /// tool starts afresh, as when the user switches documents. pub fn poll(app: &mut VectorcraftApp) { - if !may_switch(app) { - return; - } - for (path, scope) in std::mem::take(&mut app.opening.activate) { + // One at a time: a document that opens again (closed meanwhile) may ask about its links or + // fonts, and the rest wait for that dialog too. + loop { + if !may_switch(app) { + return; + } + if app.opening.activate.is_empty() { + break; + } + let (path, scope) = app.opening.activate.remove(0); // Closed meanwhile, it opens again; a failure is reported to the user there. let _ = scope.run(|| crate::io::open_reporting(app, &path)); } diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 3b5d3a4045..ee5d0a224c 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -348,3 +348,38 @@ fn a_file_asked_for_again_while_it_is_read_opens_once() { } assert_eq!(app.session.documents().len(), 1); } + +/// A document asked for again while a dialog was open, closed meanwhile, opens again once the +/// dialog closes and asks about its fonts; a file read meanwhile waits for that question too, so +/// the dialog acts on its own document (#5369). +#[test] +fn a_queued_reopen_that_asks_holds_back_files_ready_to_open() { + let dir = std::env::temp_dir().join(format!("vectorcraft-opening-queued-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + let doc = dir.join("doc.vectorcraft").to_string_lossy().into_owned(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("text.create", json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font Family"})).unwrap(); + app.run("document.save", json!({"path": doc})).unwrap(); + app.run("file.new", json!({})).unwrap(); + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + crate::io::open_reporting(&mut app, &doc).unwrap(); + assert_eq!(app.opening.activate.len(), 1); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + start(&mut app, "/art/Other.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); + // Time for the other file to be read; it waits for the dialog meanwhile. + let t0 = std::time::Instant::now(); + while t0.elapsed().as_millis() < 500 { + poll(&mut app); + std::thread::yield_now(); + } + assert_eq!(app.opening.pending.len(), 1); + app.ui.dialog = None; + poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::missing_fonts::KIND)); + assert_eq!(app.session.doc().unwrap().path.as_deref(), Some(&*doc), "the dialog's document stays active"); + assert_eq!(app.opening.pending.len(), 1, "the other file waits"); + let _ = std::fs::remove_dir_all(dir); +} From 079f5389a6b6ffd808bc6c110ce193019fd4f998 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:53:19 +0530 Subject: [PATCH 23/50] opening::poll stops once a file it opens asks a question Of two files read off the UI thread and ready in the same frame, the first could open and ask about its links or fonts, and the second then became the active document under that dialog. poll now checks may_switch after each file it opens too, and leaves the rest for a later frame. The queued-reopen test also checks that a later queued activation stays queued. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/opening.rs | 4 ++++ crates/ui-egui/src/opening/tests.rs | 36 +++++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 1a816f2d8b..fb2949dd49 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -132,6 +132,10 @@ pub fn poll(app: &mut VectorcraftApp) { app.ui.status.clear(); } p.scope.run(|| finish(app, &p.path, r)); + // A file that opened and asks about its links or fonts holds back the others too. + if !may_switch(app) { + return; + } } } diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index ee5d0a224c..fa90d3cd51 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -359,14 +359,19 @@ fn a_queued_reopen_that_asks_holds_back_files_ready_to_open() { std::fs::create_dir_all(&dir).unwrap(); let mut app = VectorcraftApp::new(Session::new(), Services::default()); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); - let doc = dir.join("doc.vectorcraft").to_string_lossy().into_owned(); + let (doc, other) = (dir.join("doc.vectorcraft"), dir.join("other.vectorcraft")); + let (doc, other) = (doc.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("text.create", json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font Family"})).unwrap(); app.run("document.save", json!({"path": doc})).unwrap(); app.run("file.new", json!({})).unwrap(); + app.run("document.save", json!({"path": other})).unwrap(); + app.run("file.new", json!({})).unwrap(); app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); crate::io::open_reporting(&mut app, &doc).unwrap(); - assert_eq!(app.opening.activate.len(), 1); + crate::io::open_reporting(&mut app, &other).unwrap(); + assert_eq!(app.opening.activate.len(), 2); + app.session.execute("file.close", &json!({"index": 1})).unwrap(); app.session.execute("file.close", &json!({"index": 0})).unwrap(); start(&mut app, "/art/Other.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); // Time for the other file to be read; it waits for the dialog meanwhile. @@ -380,6 +385,33 @@ fn a_queued_reopen_that_asks_holds_back_files_ready_to_open() { poll(&mut app); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::missing_fonts::KIND)); assert_eq!(app.session.doc().unwrap().path.as_deref(), Some(&*doc), "the dialog's document stays active"); + assert_eq!(app.opening.activate.first().map(|(p, _)| p), Some(&other), "the later activation waits"); assert_eq!(app.opening.pending.len(), 1, "the other file waits"); let _ = std::fs::remove_dir_all(dir); } + +/// Of two files read off the UI thread and ready in the same frame, the first that opens and asks +/// about its fonts holds back the second, so the question acts on its own document (#5369). +#[test] +fn a_file_that_opens_and_asks_holds_back_the_next_one_ready() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("text.create", json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font Family"})).unwrap(); + let asks = vectorcraft_format::save(&app.session.doc().unwrap().doc, false); + app.session.execute("file.close", &json!({})).unwrap(); + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + start(&mut app, "/art/Asks.vectorcraft", asks).unwrap(); + start(&mut app, "/art/Plain.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); + // Time for both files to be read; they wait for the dialog meanwhile. + let t0 = std::time::Instant::now(); + while t0.elapsed().as_millis() < 500 { + poll(&mut app); + std::thread::yield_now(); + } + assert_eq!(app.opening.pending.len(), 2); + app.ui.dialog = None; + poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::missing_fonts::KIND)); + assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Asks.vectorcraft"), "the dialog's document stays active"); + assert_eq!(app.opening.pending.len(), 1, "the next file waits"); +} From 0e64aca557462bb6507f6a2e8e2a50a86122f8db Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 20:03:22 +0000 Subject: [PATCH 24/50] Bound work: flattening of huge curves, print layout past the page limit, script-check file names --- crates/brush/src/track.rs | 3 ++- crates/brush/src/warp.rs | 2 +- crates/geom/src/lib.rs | 10 +++++++++- crates/metafile/src/wmf.rs | 2 +- crates/pdf/src/print/layout.rs | 11 +++++++++++ crates/pdf/src/tests/print.rs | 8 ++++++++ crates/scriptcheck/src/report.rs | 26 ++++++++++++++++++++++---- 7 files changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/brush/src/track.rs b/crates/brush/src/track.rs index 7d87991864..6c65246176 100644 --- a/crates/brush/src/track.rs +++ b/crates/brush/src/track.rs @@ -236,7 +236,8 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec { return out; } let mut els = vec![]; - kurbo::flatten(bp.iter(), tol.max(1e-4), |el| { + // Guarded: kurbo works out every subdivision of a curve even when the callback drops them. + vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| { if els.len() < MAX_FLATTENED { els.push(el); } diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index ae0c170f3b..c52f7f6309 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -103,7 +103,7 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { let mut bp = BezPath::new(); sp.to_bezpath_into(&mut bp); let mut pts = vec![]; - kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| { + vectorcraft_geom::flatten(bp.iter(), flat_tol.max(1e-4), |e| { if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e { pts.push(q); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 118d3f0b91..b58a31ad3e 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -29,6 +29,11 @@ pub const EPS: f64 = 1e-9; /// Most line segments [`flatten`] makes of one curve, whatever its size and the tolerance. pub const MAX_FLATTEN_PER_CURVE: f64 = 4096.0; +/// A curve whose control polygon is longer than this is drawn as a line by [`flatten`]: kurbo +/// squares and cubes coordinates when it sizes its work, and with coordinates this large that +/// overflows to infinity and it reserves a buffer no machine has. (Far beyond any drawing.) +pub const MAX_FLATTEN_LENGTH: f64 = 1e60; + /// [`kurbo::flatten`], each curve's tolerance raised so that it makes at most about /// [`MAX_FLATTEN_PER_CURVE`] segments. kurbo sizes its work and a buffer from the curve's /// coordinates before producing anything, so a small curve with far-out handles (from a file, or @@ -60,7 +65,7 @@ pub fn flatten(path: impl IntoIterator, tolerance: f64, mut callb }; last = Some(to); let (Some(from), Some(length)) = (from, length) else { continue }; - if !length.is_finite() { + if length.is_nan() || length > MAX_FLATTEN_LENGTH { callback(PathEl::LineTo(to)); continue; } @@ -198,6 +203,9 @@ mod tests { assert_eq!(ours, theirs); let nan = [PathEl::MoveTo(Point::ZERO), PathEl::QuadTo(Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0))]; assert_eq!(count(&nan, 0.25), 2); + // Finite coordinates whose squares overflow are a line to the end too. + let huge = [PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::new(1e200, 0.0), Point::new(-1e200, 1e200), Point::new(1.0, 0.0))]; + assert_eq!(count(&huge, 0.25), 2); } #[test] diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index 0e4b82e08e..33a1b081d9 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -75,7 +75,7 @@ pub(crate) fn checksum(header: &[u8]) -> u16 { fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec, bool)> { let mut out: Vec<(Vec, bool)> = vec![]; let mut cur: Vec = vec![]; - kurbo::flatten(bp.iter(), tol, |el| match el { + vectorcraft_geom::flatten(bp.iter(), tol, |el| match el { PathEl::MoveTo(p) => { if cur.len() > 1 { out.push((std::mem::take(&mut cur), false)); diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index d3a54f896c..21462e6b95 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -165,6 +165,10 @@ fn turns(set: &PrintSettings, (w, h): (f64, f64), flipped: bool) -> (Affine, (f6 (v, (w, h)) } +fn too_many_pages() -> PdfError { + PdfError::BadSetting(format!("the job would print more than {} pages", super::MAX_PAGES)) +} + /// The pages of `doc` (whose layers are those that print) as `set` lays them out, the tiles of /// each artboard when tiling, and warnings (art that doesn't fit the imageable area). pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec) -> Result<(Vec, Vec), PdfError> { @@ -174,6 +178,10 @@ pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec super::MAX_PAGES { + return Err(too_many_pages()); + } let what = artboard.map_or_else(|| "The art".to_string(), |i| format!("Artboard {}", i + 1)); if !(r.width() > 0.0 && r.height() > 0.0) { warnings.push(format!("{what} has no area and was left out")); @@ -297,6 +305,9 @@ pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec super::MAX_PAGES { + return Err(too_many_pages()); + } for &t in &pick { let w = window(t); let view = turn * Affine::translate((at.0 - w.x0, at.1 - w.y0)); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 019beddd73..a6b4d27842 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -239,6 +239,14 @@ fn tiles_cover_the_artboard_with_overlap() { assert!(preview(&d, &settings(json!({"scaling": "tileFull", "overlap": 400}))).is_err(), "overlap of half a tile"); } +#[test] +fn a_job_of_too_many_artboards_is_refused_while_laying_out() { + let mut d = doc(100.0, 100.0, &[]); + d.artboards.extend((2..=MAX_PAGES as u32 + 2).map(|i| artboard(i, 0.0))); + let e = preview(&d, &settings(json!({}))).unwrap_err().to_string(); + assert!(e.contains("more than 2000 pages"), "{e}"); +} + #[test] fn artboard_range_skip_blank_and_ignore() { let mut d = diff --git a/crates/scriptcheck/src/report.rs b/crates/scriptcheck/src/report.rs index 1c55ce1b41..b21feb20e6 100644 --- a/crates/scriptcheck/src/report.rs +++ b/crates/scriptcheck/src/report.rs @@ -370,14 +370,14 @@ impl<'l> Acc<'l> { pub fn problem(&mut self, code: &'static str, line: Option, file: Option<&str>, detail: Option<&str>) { if self.room(self.problems.len()) { let detail = detail.map(|d| self.echo(d)); - self.problems.push(Problem { code, line, file: file.map(str::to_string), detail }); + self.problems.push(Problem { code, line, file: file.map(|f| self.echo(f)), detail }); } } pub fn directive(&mut self, name: &'static str, value: &str, line: usize, form: &'static str, file: Option<&str>) { if self.room(self.directives.len()) { let value = self.echo(value); - self.directives.push(Directive { name, value, line, form, file: file.map(str::to_string) }); + self.directives.push(Directive { name, value, line, form, file: file.map(|f| self.echo(f)) }); } } @@ -394,14 +394,14 @@ impl<'l> Acc<'l> { version: part(t.version), locale: part(t.locale), line, - file: file.map(str::to_string), + file: file.map(|f| self.echo(f)), }; self.targets.push(target); } pub fn include(&mut self, value: &str, line: usize, file: Option<&str>, status: IncludeStatus, path: Option<&str>) { if self.room(self.includes.len()) { - let include = Include { value: self.echo(value), line, file: file.map(str::to_string), status, path: path.map(|p| self.echo(p)) }; + let include = Include { value: self.echo(value), line, file: file.map(|f| self.echo(f)), status, path: path.map(|p| self.echo(p)) }; self.includes.push(include); } } @@ -461,3 +461,21 @@ fn echo_cow(s: &str, max: usize) -> Cow<'_, str> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_file_of_a_row_is_cut_like_the_rest_of_the_echo() { + let limits = Limits::default(); + let mut acc = Acc::new(&limits); + let long = "d/".repeat(5000); + acc.problem("x", Some(1), Some(&long), None); + acc.directive("include", "v", 1, "form", Some(&long)); + acc.target("illustrator", 1, Some(&long)); + for file in [&acc.problems[0].file, &acc.directives[0].file, &acc.targets[0].file] { + assert_eq!(file.as_deref().map(|f| f.chars().count()), Some(limits.echo)); + } + } +} From 9cd997b9aac07c8dad19c2f830407a346922d027 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 23:37:02 +0000 Subject: [PATCH 25/50] address review: draw a line for curves with far-out start or control points in flatten --- crates/geom/src/lib.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index b58a31ad3e..12a7492e7f 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -65,7 +65,14 @@ pub fn flatten(path: impl IntoIterator, tolerance: f64, mut callb }; last = Some(to); let (Some(from), Some(length)) = (from, length) else { continue }; - if length.is_nan() || length > MAX_FLATTEN_LENGTH { + // A short polygon far from the origin still overflows kurbo's `p * (mt * 2.0)` products. + let far = |p: Point| !(p.x.abs() <= MAX_FLATTEN_LENGTH && p.y.abs() <= MAX_FLATTEN_LENGTH); + let controls_far = match el { + PathEl::QuadTo(a, _) => far(a), + PathEl::CurveTo(a, b, _) => far(a) || far(b), + _ => false, + }; + if length.is_nan() || length > MAX_FLATTEN_LENGTH || far(from) || far(to) || controls_far { callback(PathEl::LineTo(to)); continue; } @@ -206,6 +213,13 @@ mod tests { // Finite coordinates whose squares overflow are a line to the end too. let huge = [PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::new(1e200, 0.0), Point::new(-1e200, 1e200), Point::new(1.0, 0.0))]; assert_eq!(count(&huge, 0.25), 2); + // A short polygon out near f64::MAX: a line, and every point it emits is finite. + let m = f64::MAX / 2.0; + let far = [PathEl::MoveTo(Point::new(m, m)), PathEl::CurveTo(Point::new(m, m), Point::new(m, m), Point::new(m, m))]; + let mut points = vec![]; + flatten(far.iter().copied(), 0.25, |e| points.push(e)); + assert_eq!(points.len(), 2); + assert!(points.iter().all(|e| matches!(e, PathEl::MoveTo(p) | PathEl::LineTo(p) if p.is_finite())), "{points:?}"); } #[test] From e9510956172c5e48f555db7a93e2d139d757830f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:44:24 +0100 Subject: [PATCH 26/50] Path booleans: refuse out-of-range input, guard the contour pass, cuts report refusals (#5465) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/cut.rs | 94 +++++++++++++++++++++++------------ crates/pathops/src/boolean.rs | 88 ++++++++++++++++++++++++++++++-- 2 files changed, 147 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/cut.rs b/crates/engine/src/cmd/cut.rs index 90bd276c9b..04fa0c7f00 100644 --- a/crates/engine/src/cmd/cut.rs +++ b/crates/engine/src/cmd/cut.rs @@ -138,8 +138,12 @@ fn cut_targets(s: &Session) -> Result> { /// What a cut does to one object: its new pieces (none deletes it). type Plan = Vec<(NodeId, Vec)>; -/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step. -fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Option>) -> Result { +/// What a cut makes of one object: its pieces (`None`: unchanged), or the pathops refusal. +type Cut = std::result::Result>, po::PathOpsError>; + +/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step. A shape the +/// booleans refuse (too complex, too far out) fails the command with the art untouched: it is not "nothing on that side". +fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Cut) -> Result { let targets = cut_targets(s)?; if targets.is_empty() { return Err(bad(cmd, "select paths or compound paths")); @@ -151,7 +155,8 @@ fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, Fill if pd.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())) { return Err(bad(cmd, "paths contain invalid coordinates")); } - if let Some(pieces) = cut(&pd, rule) { + let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("a shape cannot be cut: {e}")))?; + if let Some(pieces) = pieces { plan.push((id, pieces)); } } @@ -184,9 +189,9 @@ fn reach(pd: &PathData) -> Rect { } /// `pd ∩ region`, dropping slivers. -fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> PathData { - let r = po::boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect); - if po::area(&r, FillRule::NonZero) <= 1e-6 { PathData::default() } else { r } +fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> std::result::Result { + let r = po::try_boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect, po::DEFAULT_PRECISION)?; + Ok(if po::try_area(&r, FillRule::NonZero)? <= 1e-6 { PathData::default() } else { r }) } // ---------- Line Cut ---------- @@ -198,24 +203,26 @@ fn line_cut(s: &mut Session, p: &Value) -> Result { } /// `pd` split by the line: the pieces on both sides, `None` when the line misses it. -fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option> { +fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Cut { if pd.is_closed() { let around = reach(pd); - let a = intersect(pd, rule, &axis.half_plane(1.0, around)); - let b = intersect(pd, rule, &axis.half_plane(-1.0, around)); + let a = intersect(pd, rule, &axis.half_plane(1.0, around))?; + let b = intersect(pd, rule, &axis.half_plane(-1.0, around))?; if a.is_empty() || b.is_empty() { - return None; + return Ok(None); } - return Some(components(&a).into_iter().chain(components(&b)).collect()); + return Ok(Some(components(&a).into_iter().chain(components(&b)).collect())); } // Open paths: the parts on each side (each pass removes the other side). - let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?; - let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?; - Some(if pd.subpaths.len() == 1 { + let (Some(a), Some(b)) = (erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0), erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)) + else { + return Ok(None); + }; + Ok(Some(if pd.subpaths.len() == 1 { a.into_iter().chain(b).collect() } else { vec![PathData::new(a.into_iter().chain(b).flat_map(|p| p.subpaths).collect())] - }) + })) } // ---------- Rectangle Cut ---------- @@ -238,25 +245,30 @@ fn rect_cut(s: &mut Session, p: &Value) -> Result { } /// `pd` cropped to `rect`: `None` when it lies inside, no pieces when it lies outside. -fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option> { - let b = pd.bounds()?; +fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Cut { + let Some(b) = pd.bounds() else { return Ok(None) }; if rect.inflate(1e-9, 1e-9).contains_rect(b) { - return None; + return Ok(None); } if pd.is_closed() { - let r = - intersect(pd, rule, &polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)])); - return Some(if r.is_empty() { vec![] } else { vec![r] }); + let r = intersect( + pd, + rule, + &polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]), + )?; + return Ok(Some(if r.is_empty() { vec![] } else { vec![r] })); } let inside = rect.inflate(1e-9, 1e-9); // Sampled at least every half of the rectangle's shorter side, so a line through it is found. let step = rect.width().min(rect.height()) / 2.0; - let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?; - Some(if pd.subpaths.len() == 1 || pieces.is_empty() { + let Some(pieces) = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1)) else { + return Ok(None); + }; + Ok(Some(if pd.subpaths.len() == 1 || pieces.is_empty() { pieces } else { vec![PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect())] - }) + })) } // ---------- Mirror & Cut ---------- @@ -287,7 +299,7 @@ fn mirror_cut(s: &mut Session, p: &Value) -> Result { other => return Err(bad(C, format!("unknown axis `{other}` (vertical|horizontal|free)"))), }; let sign = keep_sign(&axis, str_param(p, "keep")).map_err(|e| bad(C, e))?; - run_cut(s, C, "Mirror & Cut", &|pd, rule| Some(mirror(pd, rule, &axis, sign))) + run_cut(s, C, "Mirror & Cut", &|pd, rule| mirror(pd, rule, &axis, sign).map(Some)) } /// The sign of [`Axis::side`] on the side `keep` names (default: left, or top when the axis runs @@ -309,22 +321,22 @@ fn keep_sign(axis: &Axis, keep: Option<&str>) -> std::result::Result Vec { +fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> std::result::Result, po::PathOpsError> { let m = axis.reflection(); if pd.is_closed() { - let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd))); + let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)))?; if kept.is_empty() { - return vec![]; + return Ok(vec![]); } - let joined = po::boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union); - return if joined.is_empty() { vec![] } else { vec![joined] }; + let joined = po::try_boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union, po::DEFAULT_PRECISION)?; + return Ok(if joined.is_empty() { vec![] } else { vec![joined] }); } let kept = match erase_outline(pd, f64::INFINITY, &|q| axis.side(q) * sign < 0.0) { Some(pieces) => pieces.into_iter().flat_map(|p| p.subpaths).collect(), None => pd.subpaths.clone(), }; let subs: Vec = kept.iter().flat_map(|sp| mirror_open(sp, axis, m)).collect(); - if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] } + Ok(if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] }) } /// An open run and its reflection, joined where its ends touch the axis (closed when both do); @@ -399,4 +411,24 @@ mod tests { let out = mirror_open(&sp, &axis, axis.reflection()); assert_eq!((out.len(), out[0].closed, out[0].anchors.len()), (1, false, 3)); } + + /// A shape the booleans refuse (here: so far from the origin that the sweep tolerance exceeds the precision) is an error, + /// not "no pieces": that would make Mirror & Cut delete it and Rectangle Cut crop it to nothing. + #[test] + fn a_shape_the_booleans_refuse_is_an_error_not_no_pieces() { + let far = polygon(&[ + Point::new(1e13, 1e13), + Point::new(1e13 + 100.0, 1e13), + Point::new(1e13 + 100.0, 1e13 + 100.0), + Point::new(1e13, 1e13 + 100.0), + ]); + let axis = Axis { p: Point::ZERO, d: Vec2::new(0.0, 1.0) }; + assert!(mirror(&far, FillRule::NonZero, &axis, 1.0).is_err()); + assert!(crop(&far, FillRule::NonZero, Rect::new(0.0, 0.0, 100.0, 100.0)).is_err()); + assert!(split_by_line(&far, FillRule::NonZero, &axis).is_err()); + // Near the origin the same cuts work. + let near = polygon(&[Point::new(-50.0, 0.0), Point::new(50.0, 0.0), Point::new(50.0, 100.0), Point::new(-50.0, 100.0)]); + assert_eq!(mirror(&near, FillRule::NonZero, &axis, 1.0).unwrap().len(), 1); + assert_eq!(split_by_line(&near, FillRule::NonZero, &axis).unwrap().map(|p| p.len()), Some(2)); + } } diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 2e7b1b793f..27294956e0 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -143,9 +143,18 @@ pub(crate) fn eps_for<'a>(paths: impl IntoIterator) -> Resul } } } - Ok((m * f64::EPSILON * 64.0).max(1e-6)) + let eps = (m * f64::EPSILON * 64.0).max(1e-6); + // Past this the sweep tolerance is wider than the refit precision: features thinner than it collapse and the call + // would answer `Ok` with part of the art (or all of it) gone. Refuse instead, so callers keep the original. + if eps > MAX_SWEEP_EPS { + return Err(PathOpsError::Degenerate); + } + Ok(eps) } +/// The widest sweep tolerance [`eps_for`] accepts: [`DEFAULT_PRECISION`], reached by coordinates of about 7e11. +const MAX_SWEEP_EPS: f64 = DEFAULT_PRECISION; + fn el_points(el: &kurbo::PathEl) -> impl Iterator { use kurbo::PathEl::*; let v: [Option; 3] = match *el { @@ -329,6 +338,13 @@ impl Arrangement { self.contours_where(|w| pred(&self.mask(w))) } + /// [`Self::contours`] with a panic in the sweep's contour pass turned into an error, as `new` does for the + /// sweep itself. Used by the calls that can return an error; the rest have none to return and let the engine's + /// guard report it. + pub(crate) fn try_contours(&self, pred: impl Fn(&[bool]) -> bool) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.contours(pred))).map_err(|_| PathOpsError::Degenerate) + } + /// All distinct non-empty coverage masks that occur next to some edge, sorted. pub(crate) fn distinct_masks(&self) -> Vec> { let mut set = BTreeSet::new(); @@ -670,7 +686,7 @@ pub fn boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRule, o /// Boolean operation with an explicit refit `precision`; errors on non-finite input. pub fn try_boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRule, op: BoolOp, precision: f64) -> Result { let arr = Arrangement::new(vec![(fill_bezpath(a), a_rule), (fill_bezpath(b), b_rule)])?; - let c = arr.contours(|m| op.apply(m[0], m[1])); + let c = arr.try_contours(|m| op.apply(m[0], m[1]))?; let tidy = Tidy { precision, ..arr.tidy }; Ok(all_contours_to_path(&c, &tidy)) } @@ -680,7 +696,7 @@ pub fn try_boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRul pub fn try_boolean_n(paths: &[(&PathData, FillRule)], pred: impl Fn(&[bool]) -> bool) -> Result { let bps: Vec<(BezPath, FillRule)> = paths.iter().map(|(p, r)| (fill_bezpath(p), *r)).collect(); let arr = Arrangement::new(bps)?; - Ok(all_contours_to_path(&arr.contours(pred), &arr.tidy)) + Ok(all_contours_to_path(&arr.try_contours(pred)?, &arr.tidy)) } /// N-ary boolean: the area where `pred(inside_flags)` holds, `inside_flags[i]` telling whether a @@ -751,7 +767,8 @@ pub fn unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> PathDa /// [`area`] that reports a refused input instead of an area of zero. pub fn try_area(path: &PathData, rule: FillRule) -> Result { let c = normalize_bez(&fill_bezpath(path), rule)?; - Ok(c.contours().map(|ct| ct.path.area()).sum::().abs()) + let area = c.contours().map(|ct| ct.path.area()).sum::().abs(); + if area.is_finite() { Ok(area) } else { Err(PathOpsError::NonFinite) } } /// Unsigned filled area of a path under a fill rule (normalises first, so it is exact for @@ -816,4 +833,67 @@ mod tests { lens.close_path(); assert_eq!(tidy.repair(&lens), lens); } + + fn square(x: f64, y: f64, size: f64) -> PathData { + PathData::single(vectorcraft_geom::SubPath::new( + [(x, y), (x + size, y), (x + size, y + size), (x, y + size)] + .iter() + .map(|&(x, y)| vectorcraft_geom::Anchor::corner(Point::new(x, y))) + .collect(), + true, + )) + } + + #[test] + fn coordinates_wider_than_the_precision_are_refused_not_emptied() { + // At 1e15 the sweep tolerance is far above a 10 unit square: both squares used to vanish and the call said `Ok`. + let near = square(0.0, 0.0, 10.0); + let far = square(1e15, 1e15, 10.0); + for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Difference, BoolOp::Xor] { + assert_eq!( + try_boolean(&near, FillRule::NonZero, &far, FillRule::NonZero, op, DEFAULT_PRECISION), + Err(PathOpsError::Degenerate), + "{op:?}" + ); + } + assert_eq!(try_area(&far, FillRule::NonZero), Err(PathOpsError::Degenerate)); + assert_eq!(try_normalize(&far, FillRule::NonZero), Err(PathOpsError::Degenerate)); + // The infallible entry points keep answering with an empty path. + assert!(boolean(&near, FillRule::NonZero, &far, FillRule::NonZero, BoolOp::Union).is_empty()); + } + + #[test] + fn coordinates_near_the_float_limit_do_not_reach_the_sweep() { + // A 1e308 rectangle made linesweeper panic (a caught panic here, an abort on the web). + let huge = square(0.0, 0.0, 1e308); + let small = square(0.0, 0.0, 10.0); + assert_eq!(try_area(&huge, FillRule::NonZero), Err(PathOpsError::Degenerate)); + assert_eq!(try_boolean(&huge, FillRule::NonZero, &small, FillRule::NonZero, BoolOp::Union, DEFAULT_PRECISION), Err(PathOpsError::Degenerate)); + assert_eq!(try_unite_all(&[(&huge, FillRule::NonZero), (&small, FillRule::NonZero)]), Err(PathOpsError::Degenerate)); + } + + #[test] + fn large_but_sensible_coordinates_still_work() { + // Well inside the limit: far-out but sensible offsets. + for at in [1e5, 1e7] { + let u = try_boolean( + &square(at, at, 10.0), + FillRule::NonZero, + &square(at + 5.0, at, 10.0), + FillRule::NonZero, + BoolOp::Union, + DEFAULT_PRECISION, + ) + .unwrap(); + let a = try_area(&u, FillRule::NonZero).unwrap(); + assert!((a - 150.0).abs() < 1.0, "at {at}: area {a}"); + } + } + + #[test] + fn a_panic_in_the_contour_pass_becomes_an_error() { + let arr = Arrangement::new(vec![(fill_bezpath(&square(0.0, 0.0, 10.0)), FillRule::NonZero)]).unwrap(); + assert!(arr.try_contours(|m| m[0]).is_ok()); + assert_eq!(arr.try_contours(|_| panic!("simulated panic in the sweep")).err(), Some(PathOpsError::Degenerate)); + } } From 0a2935cf8f984ddbfcb1959f4ff44166dd9efcc9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:49:40 +0100 Subject: [PATCH 27/50] Booleans: limit of one unit, crop outside shortcut, tests (#5465) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/cut.rs | 24 ++++++++++++++++-------- crates/pathops/src/boolean.rs | 21 +++++++++++++++------ 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/cut.rs b/crates/engine/src/cmd/cut.rs index 04fa0c7f00..48f2c31e62 100644 --- a/crates/engine/src/cmd/cut.rs +++ b/crates/engine/src/cmd/cut.rs @@ -155,7 +155,7 @@ fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, Fill if pd.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())) { return Err(bad(cmd, "paths contain invalid coordinates")); } - let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("a shape cannot be cut: {e}")))?; + let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("the cut cannot be made on this art: {e}")))?; if let Some(pieces) = pieces { plan.push((id, pieces)); } @@ -251,6 +251,10 @@ fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Cut { return Ok(None); } if pd.is_closed() { + // Wholly outside: nothing is left, whatever the booleans would make of the rectangle's coordinates. + if rect.intersect(b).is_zero_area() { + return Ok(Some(vec![])); + } let r = intersect( pd, rule, @@ -417,15 +421,19 @@ mod tests { #[test] fn a_shape_the_booleans_refuse_is_an_error_not_no_pieces() { let far = polygon(&[ - Point::new(1e13, 1e13), - Point::new(1e13 + 100.0, 1e13), - Point::new(1e13 + 100.0, 1e13 + 100.0), - Point::new(1e13, 1e13 + 100.0), + Point::new(1e15, 1e15), + Point::new(1e15 + 100.0, 1e15), + Point::new(1e15 + 100.0, 1e15 + 100.0), + Point::new(1e15, 1e15 + 100.0), ]); let axis = Axis { p: Point::ZERO, d: Vec2::new(0.0, 1.0) }; - assert!(mirror(&far, FillRule::NonZero, &axis, 1.0).is_err()); - assert!(crop(&far, FillRule::NonZero, Rect::new(0.0, 0.0, 100.0, 100.0)).is_err()); - assert!(split_by_line(&far, FillRule::NonZero, &axis).is_err()); + let refused = Some(po::PathOpsError::Degenerate); + assert_eq!(mirror(&far, FillRule::NonZero, &axis, 1.0).err(), refused); + assert_eq!(split_by_line(&far, FillRule::NonZero, &axis).err(), refused); + // A rectangle that far out, against art near the origin, still crops it to nothing. + let far_rect = Rect::new(1e15, 1e15, 1e15 + 100.0, 1e15 + 100.0); + let near_art = polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]); + assert_eq!(crop(&near_art, FillRule::NonZero, far_rect).unwrap(), Some(vec![])); // Near the origin the same cuts work. let near = polygon(&[Point::new(-50.0, 0.0), Point::new(50.0, 0.0), Point::new(50.0, 100.0), Point::new(-50.0, 100.0)]); assert_eq!(mirror(&near, FillRule::NonZero, &axis, 1.0).unwrap().len(), 1); diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 27294956e0..f61ac5e488 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -144,7 +144,7 @@ pub(crate) fn eps_for<'a>(paths: impl IntoIterator) -> Resul } } let eps = (m * f64::EPSILON * 64.0).max(1e-6); - // Past this the sweep tolerance is wider than the refit precision: features thinner than it collapse and the call + // Past this the sweep tolerance is wider than a document unit: features thinner than it collapse and the call // would answer `Ok` with part of the art (or all of it) gone. Refuse instead, so callers keep the original. if eps > MAX_SWEEP_EPS { return Err(PathOpsError::Degenerate); @@ -152,8 +152,10 @@ pub(crate) fn eps_for<'a>(paths: impl IntoIterator) -> Resul Ok(eps) } -/// The widest sweep tolerance [`eps_for`] accepts: [`DEFAULT_PRECISION`], reached by coordinates of about 7e11. -const MAX_SWEEP_EPS: f64 = DEFAULT_PRECISION; +/// The widest sweep tolerance [`eps_for`] accepts: one document unit, reached by coordinates of about 7e13. (The engine +/// refuses coordinates far below that, so this only guards the library's own callers; it does not follow the `precision` +/// a caller asks for.) +const MAX_SWEEP_EPS: f64 = 1.0; fn el_points(el: &kurbo::PathEl) -> impl Iterator { use kurbo::PathEl::*; @@ -339,7 +341,7 @@ impl Arrangement { } /// [`Self::contours`] with a panic in the sweep's contour pass turned into an error, as `new` does for the - /// sweep itself. Used by the calls that can return an error; the rest have none to return and let the engine's + /// sweep itself (native builds only: on the web a panic aborts, whatever is caught here). Used by the calls that can return an error; the rest have none to return and let the engine's /// guard report it. pub(crate) fn try_contours(&self, pred: impl Fn(&[bool]) -> bool) -> Result { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.contours(pred))).map_err(|_| PathOpsError::Degenerate) @@ -767,8 +769,7 @@ pub fn unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> PathDa /// [`area`] that reports a refused input instead of an area of zero. pub fn try_area(path: &PathData, rule: FillRule) -> Result { let c = normalize_bez(&fill_bezpath(path), rule)?; - let area = c.contours().map(|ct| ct.path.area()).sum::().abs(); - if area.is_finite() { Ok(area) } else { Err(PathOpsError::NonFinite) } + Ok(c.contours().map(|ct| ct.path.area()).sum::().abs()) } /// Unsigned filled area of a path under a fill rule (normalises first, so it is exact for @@ -891,6 +892,14 @@ mod tests { } #[test] + fn the_coordinate_limit_sits_where_the_tolerance_passes_a_unit() { + // 100 unit squares: tolerance 0.7 at 5e13 (kept), 1.4 at 1e14 (refused). + assert!(try_area(&square(5e13, 5e13, 100.0), FillRule::NonZero).is_ok()); + assert_eq!(try_area(&square(1e14, 1e14, 100.0), FillRule::NonZero), Err(PathOpsError::Degenerate)); + } + + #[test] + #[cfg(panic = "unwind")] fn a_panic_in_the_contour_pass_becomes_an_error() { let arr = Arrangement::new(vec![(fill_bezpath(&square(0.0, 0.0, 10.0)), FillRule::NonZero)]).unwrap(); assert!(arr.try_contours(|m| m[0]).is_ok()); From 445e954ec9a59c1e67b64cab908f0fdc69da3e24 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:03:26 +0100 Subject: [PATCH 28/50] Offset Path: skip far segments and stop at the first near one in the spurious-contour check (#5455) For every hole (when growing) or island (when insetting), the check measured the distance to every segment of the input with the nearest-point search and took the minimum, so the cost grew with holes x segments. Segment bounding boxes are now computed once, a segment whose box is farther than the offset distance is skipped, and the search stops at the first segment that is close enough. The decision is the same as before; a test compares it with the old full scan on random segment sets. Co-Authored-By: Claude Sonnet 5.5 --- crates/pathops/src/offset.rs | 102 +++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index a78d8744cf..955a938290 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -119,10 +119,10 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> // winding, leaving faces uncovered that are really within `d` of the path. Every face of the // true offset is bounded by arrangement edges, so a contour is spurious iff a point deep inside // it lies closer than `d`: holes when growing, islands when insetting. - let src = path.to_bezpath(); + let src = std::cell::LazyCell::new(|| boxed_segments(&path.to_bezpath())); let drop_outer = delta < 0.0; let spurious: Vec = - c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| dist_to(&src, p) < d * (1.0 - 1e-4) - 1e-6)).collect(); + c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| any_within(&src, p, d * (1.0 - 1e-4) - 1e-6))).collect(); if !spurious.contains(&true) { return all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION)); } @@ -208,9 +208,22 @@ fn deep_point(bp: &BezPath) -> Option { best.map(|(_, p)| p) } -fn dist_to(bp: &BezPath, p: kurbo::Point) -> f64 { +/// Each segment of `bp` with its bounding box. +fn boxed_segments(bp: &BezPath) -> Vec<(kurbo::Rect, kurbo::PathSeg)> { + use kurbo::ParamCurveExtrema; + bp.segments().map(|s| (s.bounding_box(), s)).collect() +} + +/// Whether some segment lies closer than `r` to `p`. A segment whose box is more than `r` away +/// (with a little slack for rounding) can't, so it is skipped without the costly nearest-point +/// search, and the search stops at the first segment that does. +fn any_within(segs: &[(kurbo::Rect, kurbo::PathSeg)], p: kurbo::Point, r: f64) -> bool { use kurbo::ParamCurveNearest; - bp.segments().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + let reach = r + 1e-6; + r > 0.0 + && segs.iter().any(|(b, s)| { + p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach && s.nearest(p, 1e-6).distance_sq.sqrt() < r + }) } #[cfg(test)] @@ -219,6 +232,87 @@ mod tests { use super::*; + /// The check as it was: the nearest distance over every segment, then compared. + fn dist_to(bp: &BezPath, p: kurbo::Point) -> f64 { + use kurbo::ParamCurveNearest; + bp.segments().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + } + + struct Lcg(u64); + impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + /// A coordinate on a coarse grid, so segments touch, coincide and nest often. + fn grid(&mut self, n: f64) -> f64 { + (self.next() * n).floor() + } + } + + #[test] + fn nearby_segment_check_agrees_with_the_full_scan() { + let mut rng = Lcg(7); + let mut hits = 0; + for case in 0..400 { + let n = [3.0, 6.0, 20.0][case % 3]; + let mut bp = BezPath::new(); + for _ in 0..1 + (rng.next() * 12.0) as usize { + let pt = |rng: &mut Lcg| kurbo::Point::new(rng.grid(n), rng.grid(n)); + let a = pt(&mut rng); + bp.move_to(a); + match (rng.next() * 5.0) as u32 { + 0 => bp.line_to(a), // zero length + 1 => bp.line_to(pt(&mut rng)), + 2 => bp.quad_to(pt(&mut rng), pt(&mut rng)), + 3 => bp.curve_to(pt(&mut rng), pt(&mut rng), pt(&mut rng)), + _ => { + // A circle, touching or nested in others. + let r = 1.0 + rng.grid(n / 2.0); + bp.extend(kurbo::Circle::new(a, r).to_path(0.01)); + } + } + if rng.next() < 0.3 { + bp.close_path(); + } + } + let segs = boxed_segments(&bp); + for _ in 0..40 { + // On the grid (on segments and their ends) and off it. + let p = if rng.next() < 0.5 { + kurbo::Point::new(rng.grid(n), rng.grid(n)) + } else { + kurbo::Point::new(rng.next() * (n + 2.0) - 1.0, rng.next() * (n + 2.0) - 1.0) + }; + let nearest = dist_to(&bp, p); + // Radii around the true distance (where a wrong skip would show), and the usual kind. + for r in [nearest, nearest * (1.0 - 1e-9), nearest * (1.0 + 1e-9), nearest + 1e-6, 0.0, -1.0, 1e-7, rng.next() * 3.0, 1e6] { + assert_eq!(any_within(&segs, p, r), nearest < r, "case {case} p {p:?} r {r} nearest {nearest}"); + hits += usize::from(nearest < r); + } + } + } + assert!(hits > 1000, "{hits}"); + assert!(!any_within(&[], kurbo::Point::ZERO, 1.0)); + } + + #[test] + fn growing_a_plate_with_many_holes_keeps_the_holes_that_stay() { + // A plate with a grid of round holes: growing by 1 closes the narrow ones (radius <= 1) + // and keeps the wide ones. + let mut plate = BezPath::new(); + plate.extend(kurbo::Rect::new(0.0, 0.0, 200.0, 200.0).to_path(0.1)); + for i in 0..10 { + for j in 0..10 { + let r = if (i + j) % 2 == 0 { 0.8 } else { 4.0 }; + plate.extend(kurbo::Circle::new((10.0 + 20.0 * f64::from(i), 10.0 + 20.0 * f64::from(j)), r).to_path(0.01).reverse_subpaths()); + } + } + let out = offset_path(&PathData::from_bezpath(&plate), 1.0, Join::Round, 4.0); + // The outer contour and the 50 wide holes; the 50 narrow ones are gone. + assert_eq!(out.subpaths.len(), 1 + 50); + } + #[test] fn stroke_region_unites_outlines_whatever_their_winding() { // A bar, and a square ring wound the other way that the bar runs into. From 63aeefbd6ce369b3f52817fa7e0f900a8532bc34 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:05:37 +0100 Subject: [PATCH 29/50] Offset Path: scale the box slack with the coordinates and tighten the tests (#5455) Co-Authored-By: Claude Sonnet 5.5 --- crates/pathops/src/offset.rs | 65 +++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 12 deletions(-) diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index 955a938290..ec6b517f7a 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -214,16 +214,19 @@ fn boxed_segments(bp: &BezPath) -> Vec<(kurbo::Rect, kurbo::PathSeg)> { bp.segments().map(|s| (s.bounding_box(), s)).collect() } -/// Whether some segment lies closer than `r` to `p`. A segment whose box is more than `r` away -/// (with a little slack for rounding) can't, so it is skipped without the costly nearest-point -/// search, and the search stops at the first segment that does. +/// Whether a segment with bounding box `b` could lie within `r` of `p`: the box is inflated by `r` +/// and by slack for rounding in the box and in the curve evaluation, which grows with the coordinates. +fn box_may_reach(b: &kurbo::Rect, p: kurbo::Point, r: f64) -> bool { + let reach = r + 1e-6 + 1e-9 * p.x.abs().max(p.y.abs()); + p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach +} + +/// Whether some segment lies closer than `r` to `p`. A segment whose box is too far away can't, so +/// it is skipped without the costly nearest-point search, and the search stops at the first +/// segment that does. fn any_within(segs: &[(kurbo::Rect, kurbo::PathSeg)], p: kurbo::Point, r: f64) -> bool { use kurbo::ParamCurveNearest; - let reach = r + 1e-6; - r > 0.0 - && segs.iter().any(|(b, s)| { - p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach && s.nearest(p, 1e-6).distance_sq.sqrt() < r - }) + r > 0.0 && segs.iter().any(|(b, s)| box_may_reach(b, p, r) && s.nearest(p, 1e-6).distance_sq.sqrt() < r) } #[cfg(test)] @@ -253,7 +256,7 @@ mod tests { #[test] fn nearby_segment_check_agrees_with_the_full_scan() { let mut rng = Lcg(7); - let mut hits = 0; + let (mut hits, mut skipped) = (0, 0); for case in 0..400 { let n = [3.0, 6.0, 20.0][case % 3]; let mut bp = BezPath::new(); @@ -276,6 +279,9 @@ mod tests { bp.close_path(); } } + // The same geometry far from the origin too, where the rounding slack matters. + let shift = [0.0, 1e6, 1e9][case % 3]; + let bp = kurbo::Affine::translate((shift, -shift)) * bp; let segs = boxed_segments(&bp); for _ in 0..40 { // On the grid (on segments and their ends) and off it. @@ -284,15 +290,39 @@ mod tests { } else { kurbo::Point::new(rng.next() * (n + 2.0) - 1.0, rng.next() * (n + 2.0) - 1.0) }; + let p = kurbo::Point::new(p.x + shift, p.y - shift); let nearest = dist_to(&bp, p); - // Radii around the true distance (where a wrong skip would show), and the usual kind. - for r in [nearest, nearest * (1.0 - 1e-9), nearest * (1.0 + 1e-9), nearest + 1e-6, 0.0, -1.0, 1e-7, rng.next() * 3.0, 1e6] { + // Radii around the true distance (where a wrong skip would show), just outside a + // segment's box, and the usual kind. + let box_gap = + segs.iter().map(|(b, _)| (b.x0 - p.x).max(p.x - b.x1).max(b.y0 - p.y).max(p.y - b.y1).max(0.0)).fold(f64::INFINITY, f64::min); + for r in [ + nearest, + nearest * (1.0 - 1e-9), + nearest * (1.0 + 1e-9), + nearest + 1e-6, + box_gap + 5e-7, + box_gap + 2e-6, + 0.0, + -1.0, + 1e-7, + rng.next() * 3.0, + 1e6, + ] { assert_eq!(any_within(&segs, p, r), nearest < r, "case {case} p {p:?} r {r} nearest {nearest}"); hits += usize::from(nearest < r); + // Every segment the box test skips is really out of reach. + for (b, s) in &segs { + if r > 0.0 && !box_may_reach(b, p, r) { + skipped += 1; + use kurbo::ParamCurveNearest; + assert!(s.nearest(p, 1e-6).distance_sq.sqrt() >= r, "case {case} skipped a segment within {r} of {p:?}"); + } + } } } } - assert!(hits > 1000, "{hits}"); + assert!(hits > 1000 && skipped > 10_000, "{hits} {skipped}"); assert!(!any_within(&[], kurbo::Point::ZERO, 1.0)); } @@ -311,6 +341,17 @@ mod tests { let out = offset_path(&PathData::from_bezpath(&plate), 1.0, Join::Round, 4.0); // The outer contour and the 50 wide holes; the 50 narrow ones are gone. assert_eq!(out.subpaths.len(), 1 + 50); + // The holes left are the wide ones, shrunk to radius 3 and still centred on their grid point. + let mut holes = 0; + for sp in out.subpaths.iter().skip(1) { + let b = PathData::single(sp.clone()).to_bezpath().bounding_box(); + let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert!((b.width() - 6.0).abs() < 0.05 && (b.height() - 6.0).abs() < 0.05, "{b:?}"); + let (i, j) = (((cx - 10.0) / 20.0).round(), ((cy - 10.0) / 20.0).round()); + assert!((cx - 10.0 - 20.0 * i).abs() < 0.05 && (cy - 10.0 - 20.0 * j).abs() < 0.05 && (i + j) % 2.0 != 0.0, "{b:?}"); + holes += 1; + } + assert_eq!(holes, 50); } #[test] From 13b0bbe63933eb15815c50d9a5c962febba3c242 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:39:07 +0000 Subject: [PATCH 30/50] Linear-time scans: Add Anchor Points, swatch library adds, placed-document export, width profiles, symbolism previews Add Anchor Points builds the new anchor list in one pass, Swatch Library add looks names up in sets, full_documents dedups placed keys with a set, width profile lookups and mark insertion use binary search, and the symbolism tools cap and thin the previews of a long drag as Liquify does. --- crates/doc/src/appearance/profile.rs | 37 +++++++++++++++---- crates/effects/src/stroke/width.rs | 7 +++- crates/engine/src/cmd/place/document.rs | 3 +- crates/engine/src/cmd/swatchlib.rs | 39 ++++++++++++++++++-- crates/pathops/src/edit.rs | 29 +++++++++++++-- crates/pathops/tests/it/ops.rs | 15 ++++++++ crates/tools/src/lib.rs | 2 +- crates/tools/src/symbolism.rs | 49 +++++++++++++++++++++++-- 8 files changed, 158 insertions(+), 23 deletions(-) diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 1c3334f0dc..fabe408e1f 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -34,11 +34,11 @@ impl WidthProfile { if t <= p[0].0 { return (p[0].1, p[0].2); } - for w in p.windows(2) { - if t <= w[1].0 { - let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9); - return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u); - } + // (Positions go forward; found in log time, so a long profile read from a file is cheap to ask.) + let i = p.partition_point(|q| q.0 < t); + if let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) { + let u = (t - a.0) / (b.0 - a.0).max(1e-9); + return (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u); } p.last().map_or((1.0, 1.0), |l| (l.1, l.2)) } @@ -90,10 +90,11 @@ impl WidthProfile { /// discontinuous point (two points at `t`, within `1e-7`). pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) { let p = &self.points; - if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) { - let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1; + let i = p.partition_point(|q| q.0 < t - 1e-7); + if let Some(first) = p.get(i).filter(|q| (q.0 - t).abs() <= 1e-7) { + let j = i + p[i..].partition_point(|q| q.0 - first.0 <= 1e-9) - 1; if j > i { - return ((p[i].1, p[i].2), (p[j].1, p[j].2)); + return ((first.1, first.2), (p[j].1, p[j].2)); } } let v = self.at(t); @@ -334,3 +335,23 @@ pub struct SavedProfile { pub name: String, pub profile: WidthProfile, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn width_profile_lookups_by_search() { + let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25), (1.0, 0.0, 0.0)] }; + assert_eq!(p.at(-1.0), (0.0, 0.0)); + assert_eq!(p.at(0.25), (0.5, 0.5)); + assert_eq!(p.at(0.75), (0.25, 0.125)); + assert_eq!(p.at(2.0), (0.0, 0.0)); + // A step: the widths just before and just after it. + assert_eq!(p.around(0.5), ((1.0, 1.0), (0.5, 0.25))); + assert_eq!(p.around(0.25), ((0.5, 0.5), (0.5, 0.5))); + // Many points at one position are one step, found without a pass over them all. + let many = WidthProfile { points: (0..1000).map(|i| (0.5, i as f64, i as f64)).collect() }; + assert_eq!(many.around(0.5), ((0.0, 0.0), (999.0, 999.0))); + } +} diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 87eca97d78..324fddfac9 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -114,13 +114,16 @@ pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f6 let seg_count = if closed { n } else { n.saturating_sub(1) }; let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); let mut acc = 0.0; + // Sorted once, so each segment finds its marks by search, not by a pass over all of them. + let mut marks = marks.to_vec(); + marks.sort_by(f64::total_cmp); for i in 0..seg_count { let (a, b) = (pts[i], pts[(i + 1) % n]); let len = a.distance(b); out.0.push(a); out.1.push(corner[i]); - let mut inner: Vec = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect(); - inner.sort_by(f64::total_cmp); + let from = marks.partition_point(|d| *d <= acc + 1e-9); + let mut inner: Vec = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect(); inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); for d in inner { out.0.push(a.lerp(b, (d - acc) / len)); diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 76f8b82ffd..9bc52c89b1 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -338,8 +338,9 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { Cow::Owned(doc) => doc, }; let mut need: Vec = vec![]; + let mut seen = std::collections::HashSet::new(); doc.visit_placed(|_, p| { - if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && !need.iter().any(|n| n.key == p.key) { + if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) { need.push(p.clone()); } }); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index ed2671eafd..8e929f14d2 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LIBRARIES, builtin_library}; use vectorcraft_color::palette_io::{self, PaletteFormat}; use vectorcraft_color::recolor::Palette; +use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; @@ -587,8 +588,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result { /// ungrouped): a group's name brings the group, a swatch's name the swatch alone; no names, all. fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result, &'a Swatch)>> { let mut out: Vec<(Option<&str>, &Swatch)> = vec![]; + let mut seen: HashSet<&str> = HashSet::new(); let mut push = |g: Option<&'a str>, w: &'a Swatch| { - if !out.iter().any(|(_, x)| x.name == w.name) { + if seen.insert(w.name.as_str()) { out.push((g, w)); } }; @@ -606,6 +608,23 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result HashSet { + let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name)); + names.cloned().chain([REGISTRATION.to_string()]).collect() +} + +/// [`vectorcraft_doc::Document::free_swatch_name`] against `taken`, which takes the name returned. +fn free_in(taken: &mut HashSet, base: &str) -> String { + let name = if taken.contains(base) { + (2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string()) + } else { + base.to_string() + }; + taken.insert(name.clone()); + name +} + fn add(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.add"; let (info, lib) = library_param(s, p, C)?; @@ -621,11 +640,21 @@ fn add(s: &mut Session, p: &Value) -> Result { // same pattern) are reused, not added again. let patterns = patternlib::library_doc(&info.id); let d = &s.doc()?.doc; + // The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked + // up once so that a large palette takes linear time. + let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + for w in d.swatches_iter() { + by_name.entry(w.name.as_str()).or_insert(w); + } let there = |w: &Swatch| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target)) } - _ => d.swatch(&w.name).is_some_and(|x| x.paint == w.paint).then(|| w.name.clone()), + _ => match by_name.get(w.name.as_str()) { + Some(x) => x.paint == w.paint, + None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint), + } + .then(|| w.name.clone()), }; // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; @@ -647,6 +676,7 @@ fn add(s: &mut Session, p: &Value) -> Result { // already had, or one made here. let before = d.swatch_groups.len(); let mut placed: Vec<(&str, usize)> = vec![]; + let mut taken = taken_names(d); for (group, w) in fresh { if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one @@ -661,9 +691,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } }; out.push((w.name.clone(), name)); + taken = taken_names(d); continue; } - let name = d.free_swatch_name(&w.name); + let name = free_in(&mut taken, &w.name); let sw = Swatch { name: name.clone(), ..(*w).clone() }; match group { Some(g) => { @@ -671,7 +702,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) { Some(i) => i, None => { - let name = d.free_swatch_name(g); + let name = free_in(&mut taken, g); d.swatch_groups.push(SwatchGroup { name, swatches: vec![] }); d.swatch_groups.len() - 1 } diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 2a39cccfa6..7d289e135b 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use kurbo::{CubicBez, PathSeg, Point, Rect, Vec2}; +use kurbo::{CubicBez, ParamCurve, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; @@ -628,9 +628,32 @@ fn golden_min(f: impl Fn(f64) -> (CubicBez, f64, usize), mut a: f64, mut b: f64) pub fn add_anchor_points(path: &PathData) -> PathData { let mut out = path.clone(); for sp in &mut out.subpaths { - for seg in (0..sp.segment_count()).rev() { - sp.insert_anchor(seg, 0.5); + let n = sp.segment_count(); + if n == 0 { + continue; } + // Built in one pass (inserting into the middle of the vector shifts the rest each time): + // anchor k lands at 2k and the new anchor of segment k at 2k + 1. + let mut v = Vec::with_capacity(sp.anchors.len() * 2); + for (k, a) in sp.anchors.iter().enumerate() { + v.push(*a); + if k < n { + v.push(*a); + } + } + for seg in 0..n { + let c = sp.segment(seg); + let (l, r) = (c.subsegment(0.0..0.5), c.subsegment(0.5..1.0)); + if sp.segment_is_line(seg) { + v[2 * seg + 1] = Anchor::corner(l.p3); + } else { + let at = (2 * seg + 2) % v.len(); + v[2 * seg].h_out = l.p1; + v[at].h_in = r.p2; + v[2 * seg + 1] = Anchor { p: l.p3, h_in: l.p2, h_out: r.p1, kind: AnchorKind::Smooth }; + } + } + sp.anchors = v; } out } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index c3184a9fc6..587da33448 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -515,6 +515,21 @@ fn add_anchor_points_doubles() { assert!(r.anchors().any(|(_, _, a)| a.p == Point::new(5.0, 0.0))); } +/// The one-pass build gives what inserting a midpoint into each segment (last first) gives, open or closed. +#[test] +fn add_anchor_points_matches_inserting() { + let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.clone(), false)); + for src in [circle(0.0, 0.0, 10.0), rect(0.0, 0.0, 10.0, 10.0), open] { + let mut want = src.clone(); + for sp in &mut want.subpaths { + for seg in (0..sp.segment_count()).rev() { + sp.insert_anchor(seg, 0.5); + } + } + assert_eq!(add_anchor_points(&src), want); + } +} + #[test] fn average_axes() { let p = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 4.0), Point::new(5.0, 8.0)], false)); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index bf2edac343..ee00fdbe97 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -323,7 +323,7 @@ pub(crate) const MAX_STROKE_SAMPLES: usize = 100_000; /// `n / PREVIEW_ALL_UNTIL` samples. Each preview carries every sample so far, so previewing at /// every sample cost the square of the stroke's length (a gesture of many drags sent at once /// spent seconds); this way it is about `PREVIEW_ALL_UNTIL` per sample. -const PREVIEW_ALL_UNTIL: usize = 1000; +pub(crate) const PREVIEW_ALL_UNTIL: usize = 1000; /// Whether a drag that made the stroke `n` samples long previews it ([`PREVIEW_ALL_UNTIL`]). pub(crate) fn previews_at(n: usize) -> bool { diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index bb04f7ab33..eed36da853 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -11,7 +11,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Shape}; use crate::draw2::{FEEDBACK, GestureTool, points_json}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, MAX_STROKE_SAMPLES, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, previews_at}; /// Create a symbolism tool or the brush-aware Paintbrush (None = not one of ours). pub fn create(id: &str) -> Option> { @@ -26,6 +26,8 @@ pub fn create(id: &str) -> Option> { pub struct SymbolismTool { id: &'static str, points: Vec, + /// How many points the last preview had ([`previews_at`] thins previews of a long drag). + previewed: usize, active: bool, hover: Option, alt: bool, @@ -53,7 +55,19 @@ impl SymbolismTool { "symbolStyler" => "symbolStyler", _ => "symbolSprayer", }; - Self { id, points: vec![], active: false, hover: None, alt: false, diameter: 80.0, intensity: 5.0, density: 5.0, symbol: None, style: None } + Self { + id, + points: vec![], + previewed: 0, + active: false, + hover: None, + alt: false, + diameter: 80.0, + intensity: 5.0, + density: 5.0, + symbol: None, + style: None, + } } fn label(&self) -> &'static str { @@ -116,6 +130,7 @@ impl Tool for SymbolismTool { match ev.kind { PointerKind::Down => { self.points = vec![p]; + self.previewed = 1; self.active = true; self.alt = ev.mods.alt; let (c, v) = self.command(cx); @@ -124,17 +139,27 @@ impl Tool for SymbolismTool { PointerKind::Drag if self.active => { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; - if self.points.last().is_some_and(|l| l.distance(p) < step) { + // Each preview carries every point so far: a long drag stops growing and previews less often. + if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|l| l.distance(p) < step) { return vec![]; } self.points.push(p); + if !previews_at(self.points.len()) { + return vec![]; + } + self.previewed = self.points.len(); let (c, v) = self.command(cx); vec![Action::Preview(c, v)] } PointerKind::Up if self.active => { self.active = false; + // What is committed is the last preview: show the whole drag first. + let stale = (self.previewed != self.points.len()).then(|| { + let (c, v) = self.command(cx); + Action::Preview(c, v) + }); self.points.clear(); - vec![Action::Commit] + stale.into_iter().chain([Action::Commit]).collect() } _ => vec![], } @@ -294,6 +319,22 @@ mod tests { assert!(!t.busy()); } + #[test] + fn a_long_drag_previews_less_often_and_commits_all_of_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolShifter"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + let n = 7 * crate::PREVIEW_ALL_UNTIL + 1; // not a point that previews + let previews = (1..n).filter(|&i| !t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 50.0 * i as f64, 0.0)).is_empty()).count(); + assert!(previews < n * 3 / 4, "{previews} previews of {n} points"); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 0.0, 0.0)); + let last = up.iter().rev().nth(1); + assert!(matches!(last, Some(Action::Preview(_, v)) if v["points"].as_array().unwrap().len() == n), "{up:?}"); + assert_eq!(up.last(), Some(&Action::Commit)); + } + #[test] fn adjust_tools_map_to_symbol_adjust() { let (d, _) = doc_with_rect(); From fc83e5c5b97927efc79ca6952bb5e0cebf6f1681 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 23:11:59 +0000 Subject: [PATCH 31/50] address review: same distance test in width profile lower bound; preview the whole drag when a symbolism tool deactivates --- crates/doc/src/appearance/profile.rs | 6 +++- crates/tools/src/symbolism.rs | 47 +++++++++++++++++++--------- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index fabe408e1f..01b9c9fc59 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -90,7 +90,8 @@ impl WidthProfile { /// discontinuous point (two points at `t`, within `1e-7`). pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) { let p = &self.points; - let i = p.partition_point(|q| q.0 < t - 1e-7); + // The same distance test below, so a point exactly 1e-7 before `t` is never skipped by rounding. + let i = p.partition_point(|q| q.0 < t && (q.0 - t).abs() > 1e-7); if let Some(first) = p.get(i).filter(|q| (q.0 - t).abs() <= 1e-7) { let j = i + p[i..].partition_point(|q| q.0 - first.0 <= 1e-9) - 1; if j > i { @@ -353,5 +354,8 @@ mod tests { // Many points at one position are one step, found without a pass over them all. let many = WidthProfile { points: (0..1000).map(|i| (0.5, i as f64, i as f64)).collect() }; assert_eq!(many.around(0.5), ((0.0, 0.0), (999.0, 999.0))); + // 0.4999999 == 0.5 - 1e-7, yet its distance from 0.5 rounds above 1e-7: it is not part of the step. + let near = WidthProfile { points: vec![(0.4999999, 2.0, 2.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25)] }; + assert_eq!(near.around(0.5), ((1.0, 1.0), (0.5, 0.25))); } } diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index eed36da853..1618d6e7d6 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -117,6 +117,19 @@ impl SymbolismTool { } } +impl SymbolismTool { + /// Ends the drag: what is committed is the last preview, so the whole drag is shown first. + fn finish(&mut self, cx: &ToolContext) -> Vec { + self.active = false; + let stale = (self.previewed != self.points.len()).then(|| { + let (c, v) = self.command(cx); + Action::Preview(c, v) + }); + self.points.clear(); + stale.into_iter().chain([Action::Commit]).collect() + } +} + impl Tool for SymbolismTool { fn id(&self) -> &'static str { self.id @@ -151,16 +164,7 @@ impl Tool for SymbolismTool { let (c, v) = self.command(cx); vec![Action::Preview(c, v)] } - PointerKind::Up if self.active => { - self.active = false; - // What is committed is the last preview: show the whole drag first. - let stale = (self.previewed != self.points.len()).then(|| { - let (c, v) = self.command(cx); - Action::Preview(c, v) - }); - self.points.clear(); - stale.into_iter().chain([Action::Commit]).collect() - } + PointerKind::Up if self.active => self.finish(cx), _ => vec![], } } @@ -182,11 +186,9 @@ impl Tool for SymbolismTool { } vec![] } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { if self.active { - self.active = false; - self.points.clear(); - return vec![Action::Commit]; + return self.finish(cx); } vec![] } @@ -335,6 +337,23 @@ mod tests { assert_eq!(up.last(), Some(&Action::Commit)); } + #[test] + fn switching_tools_mid_drag_previews_the_whole_drag_before_committing() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolShifter"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + let n = 7 * crate::PREVIEW_ALL_UNTIL + 1; // not a point that previews + for i in 1..n { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 50.0 * i as f64, 0.0)); + } + let a = t.deactivate(&cx); + assert!(matches!(a.first(), Some(Action::Preview(_, v)) if v["points"].as_array().unwrap().len() == n), "{a:?}"); + assert_eq!(a.last(), Some(&Action::Commit)); + assert!(!t.busy()); + } + #[test] fn adjust_tools_map_to_symbol_adjust() { let (d, _) = doc_with_rect(); From 5bc34676cea6e3a8ec92ce348ea7ad94a6ffb61d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:43:25 +0100 Subject: [PATCH 32/50] Trace: look up the smoothing weights instead of computing them per pixel (#5454) The bilateral smoothing pass worked out a squared colour distance, a powi, a division and a weight for every pixel and neighbour, and called round() per channel. The distance is a whole number up to 195,075, so the weights come from a table built once per trace, and the rounding is a truncation plus a compare that gives the same level as round() for 0..=255. Rows are read through slices. The output is byte for byte what it was; tests compare the pass with the old formula on several images and on every pair of grey levels. Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/smooth.rs | 153 ++++++++++++++++++++++++++++++++++--- 1 file changed, 141 insertions(+), 12 deletions(-) diff --git a/crates/trace/src/smooth.rs b/crates/trace/src/smooth.rs index 7cd8d18568..070bd82e1d 100644 --- a/crates/trace/src/smooth.rs +++ b/crates/trace/src/smooth.rs @@ -13,33 +13,54 @@ use crate::{Raster, parallel_map}; /// Colours this far apart (levels, all channels together) count half as much as equal ones. const ALIKE: f64 = 20.0; -/// One pass along rows (`dx = 1`) or columns (`dx = 0`). -fn pass(src: &[u8], w: usize, h: usize, along_rows: bool) -> Vec { +/// How much a neighbour counts, by the squared distance between the two colours (all channels +/// together): `1 / (1 + d2 / ALIKE²)²`. Distances are whole numbers, so every value a pass can ask +/// for is worked out once here instead of once per pixel and neighbour. +fn weight_table() -> Vec { + (0..=3 * 255 * 255usize).map(|d2| 1.0 / (1.0 + d2 as f64 / (ALIKE * ALIKE)).powi(2)).collect() +} + +/// `v` rounded to the nearest level, halves up. The same as `v.round() as u8` for `0 <= v <= 255`, +/// without the library call that `round` is on targets that lack a rounding instruction. +fn level(v: f64) -> u8 { + let whole = v as u8; + whole.saturating_add(u8::from(v - f64::from(whole) >= 0.5)) +} + +/// The pixel at column `x` of `row`. +fn at(row: &[u8], x: usize) -> Option<&[u8]> { + row.get(x * 4..x * 4 + 4) +} + +/// One pass along rows (`dx = 1`) or columns (`dx = 0`), weighting by `weights` (see `weight_table`). +fn pass(src: &[u8], w: usize, h: usize, along_rows: bool, weights: &[f64]) -> Vec { let rows: Vec = (0..h).collect(); - let px = |x: usize, y: usize| src.get((y * w + x) * 4..(y * w + x) * 4 + 4); + let row = |y: usize| src.get(y * w * 4..(y + 1) * w * 4).unwrap_or_default(); let done = parallel_map(&rows, |&y| { + let cur = row(y); + let (above, below) = (y.checked_sub(1).map(row), (y + 1 < h).then(|| row(y + 1))); let mut out = Vec::with_capacity(w * 4); - for x in 0..w { - let Some(p) = px(x, y) else { continue }; + for (x, p) in cur.as_chunks::<4>().0.iter().enumerate() { if p[3] < 128 { out.extend_from_slice(p); continue; } let near = if along_rows { - [(x > 0).then(|| (x - 1, y)), (x + 1 < w).then(|| (x + 1, y))] + [x.checked_sub(1).and_then(|x| at(cur, x)), at(cur, x + 1)] } else { - [(y > 0).then(|| (x, y - 1)), (y + 1 < h).then(|| (x, y + 1))] + [above.and_then(|r| at(r, x)), below.and_then(|r| at(r, x))] }; let (mut sum, mut weight) = ([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], 1.0); - for q in near.into_iter().flatten().filter_map(|(x, y)| px(x, y)).filter(|q| q[3] >= 128) { - let d2: f64 = (0..3).map(|k| (f64::from(q[k]) - f64::from(p[k])).powi(2)).sum(); - let wt = 1.0 / (1.0 + d2 / (ALIKE * ALIKE)).powi(2); + for q in near.into_iter().flatten().filter(|q| q[3] >= 128) { + let d = |k: usize| i32::from(q[k]) - i32::from(p[k]); + let d2 = (d(0) * d(0) + d(1) * d(1) + d(2) * d(2)) as usize; + let wt = weights.get(d2).copied().unwrap_or(0.0); for k in 0..3 { sum[k] += wt * f64::from(q[k]); } weight += wt; } - out.extend(sum.map(|v| (v / weight).round() as u8)); + out.extend(sum.map(|v| level(v / weight))); out.push(p[3]); } out @@ -52,8 +73,9 @@ pub(crate) fn smoothed(img: &Raster) -> Raster { let (w, h) = (img.width as usize, img.height as usize); let mut rgba = img.rgba.clone(); if rgba.len() == w * h * 4 { + let weights = weight_table(); for _ in 0..3 { - rgba = pass(&pass(&rgba, w, h, true), w, h, false); + rgba = pass(&pass(&rgba, w, h, true, &weights), w, h, false, &weights); } } Raster { width: img.width, height: img.height, rgba } @@ -85,6 +107,113 @@ mod tests { assert!(out.pixel(19, 10)[0] < 70 && out.pixel(20, 10)[0] > 150); } + /// The filter as it was before the weight table: the reference the fast pass must match byte for byte. + fn reference(src: &[u8], w: usize, h: usize, along_rows: bool) -> Vec { + let px = |x: usize, y: usize| src.get((y * w + x) * 4..(y * w + x) * 4 + 4); + let mut out = Vec::with_capacity(w * h * 4); + for y in 0..h { + for x in 0..w { + let Some(p) = px(x, y) else { continue }; + if p[3] < 128 { + out.extend_from_slice(p); + continue; + } + let near = if along_rows { + [(x > 0).then(|| (x - 1, y)), (x + 1 < w).then(|| (x + 1, y))] + } else { + [(y > 0).then(|| (x, y - 1)), (y + 1 < h).then(|| (x, y + 1))] + }; + let (mut sum, mut weight) = ([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], 1.0); + for q in near.into_iter().flatten().filter_map(|(x, y)| px(x, y)).filter(|q| q[3] >= 128) { + let d2: f64 = (0..3).map(|k| (f64::from(q[k]) - f64::from(p[k])).powi(2)).sum(); + let wt = 1.0 / (1.0 + d2 / (ALIKE * ALIKE)).powi(2); + for k in 0..3 { + sum[k] += wt * f64::from(q[k]); + } + weight += wt; + } + out.extend(sum.map(|v| (v / weight).round() as u8)); + out.push(p[3]); + } + } + out + } + + fn reference_smoothed(img: &Raster) -> Vec { + let (w, h) = (img.width as usize, img.height as usize); + let mut rgba = img.rgba.clone(); + for _ in 0..3 { + rgba = reference(&reference(&rgba, w, h, true), w, h, false); + } + rgba + } + + fn hash(x: u32, y: u32, salt: u32) -> u32 { + let mut n = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77) ^ salt.wrapping_mul(0xC2B2_AE3D); + n ^= n >> 15; + n = n.wrapping_mul(0x2C1B_3C6D); + n ^= n >> 13; + n.wrapping_mul(0x297A_2D39) ^ (n >> 16) + } + + #[test] + fn same_bytes_as_the_unoptimised_filter() { + let inputs: Vec<(&str, Raster)> = vec![ + ("random colours", Raster::from_fn(61, 47, |x, y| [hash(x, y, 1) as u8, (hash(x, y, 2) >> 3) as u8, (hash(x, y, 3) >> 5) as u8, 255])), + ( + "photo-like", + Raster::from_fn(90, 70, |x, y| { + let base = ((x as f64 / 9.0).sin() * 60.0 + (y as f64 / 13.0).cos() * 60.0 + 128.0) as i32; + let v = (base + (hash(x, y, 4) % 9) as i32 - 4).clamp(0, 255) as u8; + [v, (i32::from(v) / 2 + 60) as u8, 255 - v, 255] + }), + ), + ("gradient", Raster::from_fn(80, 33, |x, y| [(x * 3) as u8, (y * 7) as u8, (x + y) as u8, 255])), + ("flat", Raster::from_fn(20, 20, |_, _| [40, 90, 200, 255])), + ("extremes", Raster::from_fn(32, 32, |x, y| if hash(x, y, 5).is_multiple_of(2) { [0, 0, 0, 255] } else { [255, 255, 255, 255] })), + ( + "holes and half alpha", + Raster::from_fn(50, 40, |x, y| { + [hash(x, y, 6) as u8, (hash(x, y, 7) >> 8) as u8, 77, [0, 127, 128, 255, 255][(hash(x, y, 8) % 5) as usize]] + }), + ), + ("one column", Raster::from_fn(1, 30, |_, y| [(y * 8) as u8, 5, 9, 255])), + ("one row", Raster::from_fn(30, 1, |x, _| [(x * 8) as u8, 5, 9, 255])), + ("one pixel", Raster::from_fn(1, 1, |_, _| [1, 2, 3, 255])), + ("two by two", Raster::from_fn(2, 2, |x, y| [(x * 100) as u8, (y * 100) as u8, 3, 255])), + ("wide", Raster::from_fn(257, 3, |x, y| [x as u8, (x / 2) as u8, y as u8, 255])), + ]; + for (name, img) in &inputs { + assert_eq!(smoothed(img).rgba, reference_smoothed(img), "{name}"); + } + } + + #[test] + fn same_bytes_for_every_pair_of_grey_levels() { + // Every pixel next to every possible neighbour, one table for all of them (the picture + // tests above run the three rounds). + let weights = weight_table(); + for p in 0..=255u8 { + for q in 0..=255u8 { + let src = [p, p, p, 255, q, q, q, 255]; + assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}"); + } + } + } + + #[test] + fn level_is_round_for_every_value_that_can_occur() { + for v in + [0.0, 0.499_999_999_999_999_94, 0.5, 0.500_000_000_000_000_1, 1.499_999_999_999_999_8, 1.5, 127.5, 254.5, 254.999_999_999_999_97, 255.0] + { + assert_eq!(level(v), v.round() as u8, "{v}"); + } + for i in 0..=255 * 4096u32 { + let v = f64::from(i) / 4096.0; + assert_eq!(level(v), v.round() as u8, "{v}"); + } + } + #[test] fn transparent_pixels_and_odd_sizes_pass_through() { let img = Raster::from_fn(3, 1, |x, _| [10 * x as u8, 0, 0, if x == 1 { 0 } else { 255 }]); From df3f18329e9ab44b19248e6a2fc85708140b2263 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:44:55 +0100 Subject: [PATCH 33/50] Trace: cover the column pass and mixed pairs in the smoothing tests (#5454) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/smooth.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/trace/src/smooth.rs b/crates/trace/src/smooth.rs index 070bd82e1d..c449f4f9ae 100644 --- a/crates/trace/src/smooth.rs +++ b/crates/trace/src/smooth.rs @@ -195,8 +195,11 @@ mod tests { let weights = weight_table(); for p in 0..=255u8 { for q in 0..=255u8 { - let src = [p, p, p, 255, q, q, q, 255]; - assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}"); + // Grey, and a mixed pair, along a row (2x1) and along a column (1x2). + for src in [[p, p, p, 255, q, q, q, 255], [p, q, p ^ q, 255, q, p, q ^ 0x5a, 255]] { + assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}"); + assert_eq!(pass(&src, 1, 2, false, &weights), reference(&src, 1, 2, false), "{p} {q}"); + } } } } @@ -208,6 +211,13 @@ mod tests { { assert_eq!(level(v), v.round() as u8, "{v}"); } + // Values a hair either side of every half, where a wrong rounding would show. + for k in 0..255 { + let half = f64::from(k) + 0.5; + for v in [half, f64::from_bits(half.to_bits() - 1), f64::from_bits(half.to_bits() + 1)] { + assert_eq!(level(v), v.round() as u8, "{v}"); + } + } for i in 0..=255 * 4096u32 { let v = f64::from(i) / 4096.0; assert_eq!(level(v), v.round() as u8, "{v}"); From a84ab2f14a26a2d2edceaafc2272e9ebb0a7e993 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:19:44 +0100 Subject: [PATCH 34/50] contributors: credit vangel76 as Valentin Klein Co-Authored-By: Claude Sonnet 5.5 --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index db94e2a890..9014073aa7 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -193,3 +193,6 @@ sync_github_name = true [people.JonRC] real_name = "Jonathan Cardoso" display_name = "Jonathan Cardoso" + +[people.vangel76] +real_name = "Valentin Klein" From f75616af549f1731369853c37efc05cd0224dfba Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:27:03 +0100 Subject: [PATCH 35/50] contributors: set display name for vangel76 Co-Authored-By: Claude Sonnet 5.5 --- contributors/people.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 9014073aa7..0e8dae9371 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -196,3 +196,5 @@ display_name = "Jonathan Cardoso" [people.vangel76] real_name = "Valentin Klein" +display_name = "vangel76" +sync_github_name = false From 63b8c88168973e50325df48a063e12fcc3e3a95c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:35:44 +0100 Subject: [PATCH 36/50] Image Trace: noise removal keeps its regions in u32 arrays (#5462) Regions are a linked list of pixels with a union-find over region ids instead of a Vec per region and BTreeMaps per merge. Same merge order and output; about 2.7x less peak memory and up to 1.9x faster on 25 MP noisy labels. Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/quantize/denoise.rs | 304 ++++++++++++++++++++++----- 1 file changed, 250 insertions(+), 54 deletions(-) diff --git a/crates/trace/src/quantize/denoise.rs b/crates/trace/src/quantize/denoise.rs index cb40ffa4fa..971d274fcf 100644 --- a/crates/trace/src/quantize/denoise.rs +++ b/crates/trace/src/quantize/denoise.rs @@ -13,94 +13,290 @@ pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) { /// clears specks, not a colour's only regions. Smaller regions of it go as any other. pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) { use std::cmp::Reverse; - use std::collections::{BTreeMap, BinaryHeap}; + use std::collections::BinaryHeap; - if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) { + // Every index below is a `u32`: 4 bytes per pixel and per region instead of a `Vec` of pixels per region. + const NONE: u32 = u32::MAX; + if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize { return; } - struct Region { - label: u16, - pixels: Vec, - } - // Region membership is kept current after every merge. In particular, no stale `seen` - // flags can exclude previously recoloured pixels from a subsequent connected component. - let mut at = vec![usize::MAX; labels.len()]; - let mut regions: Vec = Vec::new(); + // Region of each pixel as first found (`NONE` for transparent). A merge does not touch it: the region a pixel + // belongs to now is `find(at[i])`. + let mut at = vec![NONE; labels.len()]; + // Pixels of a region form a singly linked list through `next`, so absorbing a region is one pointer write. + let mut next = vec![NONE; labels.len()]; + let mut head: Vec = Vec::new(); + let mut tail: Vec = Vec::new(); + let mut size: Vec = Vec::new(); + let mut colour: Vec = Vec::new(); + // Union-find over region ids: a region absorbed into another points at it. + let mut parent: Vec = Vec::new(); let neighbours = |i: usize| { let (x, y) = (i % w, i / w); [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)] }; for start in 0..labels.len() { - if at[start] != usize::MAX || labels[start] == TRANSPARENT { + if at[start] != NONE || labels[start] == TRANSPARENT { continue; } - let id = regions.len(); + let id = head.len() as u32; let label = labels[start]; - let mut pixels = vec![start]; at[start] = id; - let mut cursor = 0; - while let Some(&i) = pixels.get(cursor) { - for j in neighbours(i).into_iter().flatten() { - if at[j] == usize::MAX && labels[j] == label { + let mut last = start; + let mut count = 1u32; + let mut cursor = start; + loop { + for j in neighbours(cursor).into_iter().flatten() { + if at[j] == NONE && labels[j] == label { at[j] = id; - pixels.push(j); + next[last] = j as u32; + last = j; + count += 1; } } - cursor += 1; + match next[cursor] { + NONE => break, + n => cursor = n as usize, + } } - regions.push(Region { label, pixels }); + head.push(start as u32); + tail.push(last as u32); + size.push(count); + colour.push(label); + parent.push(id); } - let mut pending: BinaryHeap<_> = regions.iter().enumerate().map(|(id, r)| Reverse((r.pixels.len(), id))).collect(); - while let Some(Reverse((area, id))) = pending.pop() { - if area >= min_area { - break; + fn find(parent: &mut [u32], mut a: u32) -> u32 { + while parent[a as usize] != a { + let up = parent[parent[a as usize] as usize]; + parent[a as usize] = up; + a = up; } - if regions[id].pixels.len() != area { + a + } + // Only regions below `min_area` are ever taken from the queue; a larger one ends the loop. + let mut pending: BinaryHeap<_> = + (0..size.len() as u32).filter(|&id| (size[id as usize] as usize) < min_area).map(|id| Reverse((size[id as usize], id))).collect(); + // Scratch for one merge: `(other region, shared pixel edges)` and `(colour, shared pixel edges)`. + let mut borders: Vec<(u32, usize)> = Vec::new(); + let mut by_colour: Vec<(u16, usize)> = Vec::new(); + while let Some(Reverse((area, id))) = pending.pop() { + if size[id as usize] != area { continue; // absorbed region or an old heap entry for a region that grew } - if area >= RARE_ISLAND && keep.get(regions[id].label as usize).copied().unwrap_or(false) { + if area as usize >= RARE_ISLAND && keep.get(colour[id as usize] as usize).copied().unwrap_or(false) { continue; } - let mut borders: BTreeMap = BTreeMap::new(); - for &i in ®ions[id].pixels { - for j in neighbours(i).into_iter().flatten() { - let other = at[j]; - if other != id && other != usize::MAX { - *borders.entry(other).or_default() += 1; + borders.clear(); + // Pairs are folded together whenever the list doubles, so a big region keeps it short. + let mut limit = 4096; + let mut pixel = head[id as usize]; + while pixel != NONE { + for j in neighbours(pixel as usize).into_iter().flatten() { + if at[j] != NONE { + let other = find(&mut parent, at[j]); + if other != id { + borders.push((other, 1)); + } } } + pixel = next[pixel as usize]; + if borders.len() >= limit { + merge_counts(&mut borders); + limit = limit.max(2 * borders.len()); + } } - let mut colours: BTreeMap = BTreeMap::new(); - for (&other, &border) in &borders { - *colours.entry(regions[other].label).or_default() += border; - } - let Some((&colour, _)) = colours.iter().max_by_key(|(label, border)| (**border, Reverse(**label))) else { + merge_counts(&mut borders); + by_colour.clear(); + by_colour.extend(borders.iter().map(|&(other, border)| (colour[other as usize], border))); + merge_counts(&mut by_colour); + let Some(&(chosen, _)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else { continue; // an opaque island surrounded only by transparency stays intact }; // All adjacent regions of the chosen colour become connected by this merge. Absorb - // them together, keeping the largest one's storage to avoid repeatedly moving it. + // them together, keeping the largest one as the survivor. let Some(target) = borders - .keys() - .copied() - .filter(|&other| regions[other].label == colour) - .max_by_key(|&other| (regions[other].pixels.len(), Reverse(other))) + .iter() + .map(|&(other, _)| other) + .filter(|&other| colour[other as usize] == chosen) + .max_by_key(|&other| (size[other as usize], Reverse(other))) else { continue; }; - let sources: Vec<_> = - std::iter::once(id).chain(borders.keys().copied().filter(|&other| other != target && regions[other].label == colour)).collect(); - for source in sources { - let pixels = std::mem::take(&mut regions[source].pixels); - for &i in &pixels { - at[i] = target; - } - regions[target].pixels.extend(pixels); + for source in + std::iter::once(id).chain(borders.iter().map(|&(other, _)| other).filter(|&other| other != target && colour[other as usize] == chosen)) + { + next[tail[target as usize] as usize] = head[source as usize]; + tail[target as usize] = tail[source as usize]; + size[target as usize] += size[source as usize]; + size[source as usize] = 0; + parent[source as usize] = target; + } + if (size[target as usize] as usize) < min_area { + pending.push(Reverse((size[target as usize], target))); } - pending.push(Reverse((regions[target].pixels.len(), target))); } - for region in regions { - for i in region.pixels { - labels[i] = region.label; + for (i, ®ion) in at.iter().enumerate() { + if region != NONE { + labels[i] = colour[find(&mut parent, region) as usize]; } } } + +/// Sort `(key, count)` pairs and add up the counts of equal keys. +fn merge_counts(pairs: &mut Vec<(K, usize)>) { + pairs.sort_unstable_by_key(|p| p.0); + pairs.dedup_by(|b, a| { + let same = a.0 == b.0; + if same { + a.1 += b.1; + } + same + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The first implementation (a pixel `Vec` per region, `BTreeMap` borders), kept to check that the compact one merges + /// in exactly the same order. + fn denoise_reference(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) { + use std::cmp::Reverse; + use std::collections::{BTreeMap, BinaryHeap}; + + if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) { + return; + } + struct Region { + label: u16, + pixels: Vec, + } + // Region membership is kept current after every merge. In particular, no stale `seen` + // flags can exclude previously recoloured pixels from a subsequent connected component. + let mut at = vec![usize::MAX; labels.len()]; + let mut regions: Vec = Vec::new(); + let neighbours = |i: usize| { + let (x, y) = (i % w, i / w); + [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)] + }; + for start in 0..labels.len() { + if at[start] != usize::MAX || labels[start] == TRANSPARENT { + continue; + } + let id = regions.len(); + let label = labels[start]; + let mut pixels = vec![start]; + at[start] = id; + let mut cursor = 0; + while let Some(&i) = pixels.get(cursor) { + for j in neighbours(i).into_iter().flatten() { + if at[j] == usize::MAX && labels[j] == label { + at[j] = id; + pixels.push(j); + } + } + cursor += 1; + } + regions.push(Region { label, pixels }); + } + let mut pending: BinaryHeap<_> = regions.iter().enumerate().map(|(id, r)| Reverse((r.pixels.len(), id))).collect(); + while let Some(Reverse((area, id))) = pending.pop() { + if area >= min_area { + break; + } + if regions[id].pixels.len() != area { + continue; // absorbed region or an old heap entry for a region that grew + } + if area >= RARE_ISLAND && keep.get(regions[id].label as usize).copied().unwrap_or(false) { + continue; + } + let mut borders: BTreeMap = BTreeMap::new(); + for &i in ®ions[id].pixels { + for j in neighbours(i).into_iter().flatten() { + let other = at[j]; + if other != id && other != usize::MAX { + *borders.entry(other).or_default() += 1; + } + } + } + let mut colours: BTreeMap = BTreeMap::new(); + for (&other, &border) in &borders { + *colours.entry(regions[other].label).or_default() += border; + } + let Some((&colour, _)) = colours.iter().max_by_key(|(label, border)| (**border, Reverse(**label))) else { + continue; // an opaque island surrounded only by transparency stays intact + }; + // All adjacent regions of the chosen colour become connected by this merge. Absorb + // them together, keeping the largest one's storage to avoid repeatedly moving it. + let Some(target) = borders + .keys() + .copied() + .filter(|&other| regions[other].label == colour) + .max_by_key(|&other| (regions[other].pixels.len(), Reverse(other))) + else { + continue; + }; + let sources: Vec<_> = + std::iter::once(id).chain(borders.keys().copied().filter(|&other| other != target && regions[other].label == colour)).collect(); + for source in sources { + let pixels = std::mem::take(&mut regions[source].pixels); + for &i in &pixels { + at[i] = target; + } + regions[target].pixels.extend(pixels); + } + pending.push(Reverse((regions[target].pixels.len(), target))); + } + for region in regions { + for i in region.pixels { + labels[i] = region.label; + } + } + } + + fn noisy(w: usize, h: usize, colours: u64, transparent_one_in: u64, seed: u64) -> Vec { + let mut state = seed; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + (0..w * h) + .map(|_| { + // Runs of equal labels as well as single pixels, so regions of every size touch. + if transparent_one_in > 0 && next() % transparent_one_in == 0 { TRANSPARENT } else { (next() % colours) as u16 } + }) + .collect() + } + + #[test] + fn compact_denoise_matches_the_reference_merge_order() { + for (seed, (w, h, colours, transparent)) in + [(31, 17, 3, 0), (64, 64, 2, 0), (50, 70, 5, 9), (97, 41, 8, 0), (120, 90, 4, 5), (7, 300, 3, 0), (1, 40, 3, 0), (40, 1, 3, 0)] + .into_iter() + .enumerate() + { + let base = noisy(w, h, colours, transparent, seed as u64 + 1); + for min_area in [2, 3, 5, 9, 25, 80, 400, 100_000] { + for keep in [&[][..], &[false, true, false, true][..]] { + let (mut a, mut b) = (base.clone(), base.clone()); + denoise_reference(&mut a, w, h, min_area, keep); + denoise_keeping(&mut b, w, h, min_area, keep); + assert_eq!(a, b, "{w}x{h}, {colours} colours, min_area {min_area}, keep {keep:?}"); + } + } + } + } + + /// A minimum so large that regions keep merging into big ones. + #[test] + fn compact_denoise_matches_the_reference_with_a_large_min_area() { + let (w, h) = (320, 320); + let base = noisy(w, h, 6, 0, 99); + let (mut a, mut b) = (base.clone(), base); + denoise_reference(&mut a, w, h, 50_000, &[]); + denoise_keeping(&mut b, w, h, 50_000, &[]); + assert_eq!(a, b); + } +} From c0465969c82b6ec630dd6180691ec0b06a75da1c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:36:44 +0100 Subject: [PATCH 37/50] Denoise: comment fixes from review (#5462) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/quantize/denoise.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/trace/src/quantize/denoise.rs b/crates/trace/src/quantize/denoise.rs index 971d274fcf..a929691466 100644 --- a/crates/trace/src/quantize/denoise.rs +++ b/crates/trace/src/quantize/denoise.rs @@ -15,7 +15,8 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: use std::cmp::Reverse; use std::collections::BinaryHeap; - // Every index below is a `u32`: 4 bytes per pixel and per region instead of a `Vec` of pixels per region. + // Every index below is a `u32`, so a pixel costs 8 bytes and a region 18 instead of a `Vec` per region. An image + // of `u32::MAX` pixels or more (far above the decoder's cap) is left as it is. const NONE: u32 = u32::MAX; if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize { return; @@ -262,12 +263,7 @@ mod tests { state ^= state << 17; state }; - (0..w * h) - .map(|_| { - // Runs of equal labels as well as single pixels, so regions of every size touch. - if transparent_one_in > 0 && next() % transparent_one_in == 0 { TRANSPARENT } else { (next() % colours) as u16 } - }) - .collect() + (0..w * h).map(|_| if transparent_one_in > 0 && next() % transparent_one_in == 0 { TRANSPARENT } else { (next() % colours) as u16 }).collect() } #[test] From f4ba106e395d2022a49a11a18390d6b29a00a4c2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:16:05 +0100 Subject: [PATCH 38/50] Image Trace: all_within hashes its grid cells with a small hasher (#5463) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/logo/geom.rs | 54 ++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/crates/trace/src/logo/geom.rs b/crates/trace/src/logo/geom.rs index ca77f27612..b10e1231f0 100644 --- a/crates/trace/src/logo/geom.rs +++ b/crates/trace/src/logo/geom.rs @@ -2,6 +2,7 @@ use kurbo::Vec2; use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; use vectorcraft_geom::Point; /// One cubic Bézier segment: start, two handles, end. @@ -315,13 +316,38 @@ pub(crate) fn sample_cubics(cs: &[Cubic], spacing: f64) -> Vec { out } +/// Multiply-and-rotate hasher for the small integer cell keys of [`all_within`]. The grid is only ever looked up, never +/// iterated, so the hash cannot change a result; std's SipHash took about a quarter of the time of a noisy trace. +#[derive(Default)] +struct CellHasher(u64); + +impl CellHasher { + fn add(&mut self, word: u64) { + self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95); + } +} + +impl Hasher for CellHasher { + fn write(&mut self, bytes: &[u8]) { + bytes.iter().for_each(|&b| self.add(u64::from(b))); + } + + fn write_i64(&mut self, word: i64) { + self.add(word as u64); + } + + fn finish(&self) -> u64 { + self.0 + } +} + /// True when every point of `a` has a point of `b` within `lim`. pub(crate) fn all_within(a: &[Point], b: &[Point], lim: f64) -> bool { if lim.is_nan() || lim <= 0.0 { return false; } let key = |p: Point| ((p.x / lim).floor() as i64, (p.y / lim).floor() as i64); - let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let mut grid: HashMap<(i64, i64), Vec, BuildHasherDefault> = HashMap::default(); for &q in b { grid.entry(key(q)).or_default().push(q); } @@ -426,4 +452,30 @@ mod tests { assert!(!all_within(&a, &b, 0.1)); assert!(!all_within(&a, &b, 0.0)); } + + #[test] + fn within_agrees_with_a_brute_force_search() { + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut rand = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 + }; + for round in 0..60 { + // Negative and large coordinates, clustered and sparse clouds. + let spread = [3.0, 40.0, 1.0e5][round % 3]; + let cloud = |n: usize, rand: &mut dyn FnMut() -> f64| -> Vec { + (0..n).map(|_| Point::new((rand() - 0.5) * spread, (rand() - 0.5) * spread)).collect() + }; + let a = cloud(1 + round % 7, &mut rand); + let mut b = cloud(200, &mut rand); + b.extend(a.iter().map(|p| Point::new(p.x + (rand() - 0.5) * 0.3, p.y + (rand() - 0.5) * 0.3))); + for lim in [0.05, 0.2, 1.5, 30.0] { + let brute = a.iter().all(|&p| b.iter().any(|q| q.distance(p) <= lim)); + assert_eq!(all_within(&a, &b, lim), brute, "round {round}, lim {lim}"); + assert_eq!(all_within(&b, &a, lim), b.iter().all(|&p| a.iter().any(|q| q.distance(p) <= lim)), "round {round}, lim {lim}"); + } + } + } } From 6ede10de4de40084d7a779478429f6ce9af0cedd Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:18:19 +0100 Subject: [PATCH 39/50] all_within hasher: mix the high bits into the low ones (#5463) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/logo/geom.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/trace/src/logo/geom.rs b/crates/trace/src/logo/geom.rs index b10e1231f0..b33b358856 100644 --- a/crates/trace/src/logo/geom.rs +++ b/crates/trace/src/logo/geom.rs @@ -337,7 +337,8 @@ impl Hasher for CellHasher { } fn finish(&self) -> u64 { - self.0 + // The table picks its bucket from the low bits, which a product leaves weak: bring the strong high bits down. + self.0.rotate_left(26) } } @@ -478,4 +479,14 @@ mod tests { } } } + + #[test] + fn cell_hasher_spreads_keys_whose_low_bits_are_zero() { + use std::hash::BuildHasher; + // Cell indices that are all multiples of 1024 (pixel-exact points with a power-of-two limit). + let build = BuildHasherDefault::::default(); + let buckets: std::collections::HashSet = + (0..64i64).flat_map(|i| (0..64i64).map(move |j| (i << 10, j << 10))).map(|k| build.hash_one(k) & 1023).collect(); + assert!(buckets.len() > 600, "{} of 1024 buckets used", buckets.len()); + } } From 007e15ad8b8b5f10d06813b9b0e9c90fc5dc300f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:25:31 +0100 Subject: [PATCH 40/50] Image Trace: fit the components of a layer in parallel, in chunks (#5464) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/layers.rs | 84 +++++++++++++++++++++++++++++++++++--- crates/trace/src/tests.rs | 24 +++++++++++ 2 files changed, 103 insertions(+), 5 deletions(-) diff --git a/crates/trace/src/layers.rs b/crates/trace/src/layers.rs index 3c9467d766..a0f63613b1 100644 --- a/crates/trace/src/layers.rs +++ b/crates/trace/src/layers.rs @@ -331,7 +331,9 @@ impl Layers<'_> { } } } - for comp in comps { + // One component's paths: a pure function of its loops and the shared read-only state, so components are fitted in + // parallel and then added in order. + let fit_comp = |comp: &contour::Component| -> Option<(PathData, Option)> { // (`hard`: some of the outline has no anti-aliasing, and is known less exactly.) let hard = std::cell::Cell::new(false); // (Each loop fitted, and whether its own outline is hard.) @@ -355,7 +357,7 @@ impl Layers<'_> { hard.set(hard.get() || is_hard); Some((sp, is_hard)) }; - let Some((outer, _)) = fit(&comp.outer) else { continue }; + let (outer, _) = fit(&comp.outer)?; let mut subs = vec![outer]; for hole in &comp.holes { if hole.area2.abs() / 2 < min_hole && params.noise > 0 { @@ -398,9 +400,16 @@ impl Layers<'_> { _ => None, }; let path = shape.map_or_else(|| PathData::new(subs), |s| s.path()); - if !add(path, comp.pixels, area_stroke, shape, false) { - return None; - } + Some((path, shape)) + }; + // In chunks, so that the anchor budget still stops the work early: a hostile image is refused after at most one + // chunk beyond the limit, not after every component is fitted. + let accepted = fit_in_chunks(&comps, FIT_CHUNK, fit_comp, |comp, fitted| { + let Some((path, shape)) = fitted else { return true }; + add(path, comp.pixels, area_stroke, shape, false) + }); + if !accepted { + return None; } for line in lines { if !add(line.path, line.pixels, Some(line.width), None, line.square) { @@ -452,6 +461,24 @@ pub(crate) fn shift_probe(img: &Raster, params: &TraceParams) -> Vec<[f64; 4]> { out } +/// How many components of a layer are fitted at a time (see `fit_in_chunks`). +const FIT_CHUNK: usize = 256; + +/// `fit` of each of `items` over the available cores, `chunk` items at a time, each result handed to `accept` in item +/// order. Stops after the chunk in which `accept` returns false, and says whether it never did. +fn fit_in_chunks(items: &[T], chunk: usize, fit: impl Fn(&T) -> R + Sync, mut accept: impl FnMut(&T, R) -> bool) -> bool { + for part in items.chunks(chunk.max(1)) { + // (A few components are not worth starting threads for.) + let fitted = if part.len() < 4 { part.iter().map(&fit).collect() } else { parallel_map(part, &fit) }; + for (item, result) in part.iter().zip(fitted) { + if !accept(item, result) { + return false; + } + } + } + true +} + /// `f` of each of `items`, in order, spread over the available cores. pub(crate) fn parallel_map(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec { parallel_map_at_most(usize::MAX, items, f) @@ -492,3 +519,50 @@ pub(crate) fn parallel_map_at_most(at_a_time: usize, items: &[ pub(crate) fn parallel_map_at_most(_: usize, items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec { items.iter().map(f).collect() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_in_chunks_keeps_the_order_and_stops_at_the_first_refusal() { + let items: Vec = (0..1000).collect(); + let fitted = AtomicUsize::new(0); + let mut seen = vec![]; + let all = fit_in_chunks( + &items, + 16, + |&i| { + fitted.fetch_add(1, Ordering::Relaxed); + i * 2 + }, + |&i, r| { + assert_eq!(r, i * 2); + seen.push(i); + seen.len() <= 10 + }, + ); + assert!(!all); + // Items come in order, up to and including the one refused. + assert_eq!(seen, (0..=10).collect::>()); + // The early stop is kept: only the chunk holding the refusal was fitted, not the other 984 items. + assert_eq!(fitted.load(Ordering::Relaxed), 16); + } + + #[test] + fn fit_in_chunks_accepts_everything_in_order() { + let items: Vec = (0..1000).collect(); + let mut out = vec![]; + assert!(fit_in_chunks( + &items, + 7, + |&i| i + 1, + |_, r| { + out.push(r); + true + } + )); + assert_eq!(out, (1..=1000).collect::>()); + assert!(fit_in_chunks(&[] as &[usize], 7, |&i| i, |_, _| false)); + } +} diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index bcc2242b32..c31d3841c8 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -609,6 +609,30 @@ fn a_trace_past_its_anchor_budget_is_refused() { assert_eq!(trace_within(&img, &p, anchors).unwrap(), full); } +/// Components of a layer are fitted in parallel, a chunk at a time, and added in the order they were found (top to +/// bottom, left to right), also across the chunks. The anchor budget still refuses a trace with many components. +#[test] +fn many_components_come_out_in_scan_order_and_still_meet_the_budget() { + // 20 x 20 black dots, more than one chunk of components. + let img = Raster::from_fn(120, 120, |x, y| if x % 6 < 3 && y % 6 < 3 { BLACK } else { WHITE }); + let p = TraceParams { noise: 1, ..bw() }; + let full = trace(&img, &p); + assert_eq!(full.paths.len(), 400); + let tops: Vec<(i64, i64)> = full + .paths + .iter() + .map(|t| { + let b = t.path.bounds().unwrap(); + (b.y0.round() as i64, b.x0.round() as i64) + }) + .collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "not in scan order: {tops:?}"); + assert_eq!(trace(&img, &p), full, "tracing twice differs"); + let anchors = full.anchor_count(); + assert!(matches!(trace_within(&img, &p, anchors / 2), Err(TraceError::TooComplex { max }) if max == anchors / 2)); + assert_eq!(trace_within(&img, &p, anchors).unwrap(), full); +} + /// #3098: a watched trace says how far it has got, layer by layer, and stops when told to. #[test] fn a_watched_trace_counts_its_layers_and_stops_when_told() { From f25812408697e54fb93e810bb157752f1a8a20a9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:27:14 +0100 Subject: [PATCH 41/50] Component fit chunking: review fixes (#5464) Co-Authored-By: Claude Sonnet 5.5 --- crates/trace/src/layers.rs | 6 +++--- crates/trace/src/tests.rs | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/trace/src/layers.rs b/crates/trace/src/layers.rs index a0f63613b1..d9b34cc549 100644 --- a/crates/trace/src/layers.rs +++ b/crates/trace/src/layers.rs @@ -402,8 +402,8 @@ impl Layers<'_> { let path = shape.map_or_else(|| PathData::new(subs), |s| s.path()); Some((path, shape)) }; - // In chunks, so that the anchor budget still stops the work early: a hostile image is refused after at most one - // chunk beyond the limit, not after every component is fitted. + // In chunks, so that the anchor budget still stops the work early: a hostile image is refused after fitting at most + // the rest of one chunk, not after every component is fitted. let accepted = fit_in_chunks(&comps, FIT_CHUNK, fit_comp, |comp, fitted| { let Some((path, shape)) = fitted else { return true }; add(path, comp.pixels, area_stroke, shape, false) @@ -469,7 +469,7 @@ const FIT_CHUNK: usize = 256; fn fit_in_chunks(items: &[T], chunk: usize, fit: impl Fn(&T) -> R + Sync, mut accept: impl FnMut(&T, R) -> bool) -> bool { for part in items.chunks(chunk.max(1)) { // (A few components are not worth starting threads for.) - let fitted = if part.len() < 4 { part.iter().map(&fit).collect() } else { parallel_map(part, &fit) }; + let fitted = if part.len() < 16 { part.iter().map(&fit).collect() } else { parallel_map(part, &fit) }; for (item, result) in part.iter().zip(fitted) { if !accept(item, result) { return false; diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index c31d3841c8..6b3298a7b4 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -630,6 +630,8 @@ fn many_components_come_out_in_scan_order_and_still_meet_the_budget() { assert_eq!(trace(&img, &p), full, "tracing twice differs"); let anchors = full.anchor_count(); assert!(matches!(trace_within(&img, &p, anchors / 2), Err(TraceError::TooComplex { max }) if max == anchors / 2)); + // The last component alone is over the budget: a refusal in a later chunk. + assert!(matches!(trace_within(&img, &p, anchors - 1), Err(TraceError::TooComplex { .. }))); assert_eq!(trace_within(&img, &p, anchors).unwrap(), full); } From c16c833c58cf36fb6d31ac69d364aafebd22d02c Mon Sep 17 00:00:00 2001 From: Franco Jacquet <54250139+FrancoJacquet@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:13:52 +0700 Subject: [PATCH 42/50] Check stroke.set params: a misnamed key is refused (#1442) Squashed from #5453 onto main. --- contributors/people.toml | 3 +++ crates/engine/src/cmd/params.rs | 1 - crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/tests/params.rs | 21 +++++++++++++++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 0e8dae9371..f4e508fdf5 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -198,3 +198,6 @@ display_name = "Jonathan Cardoso" real_name = "Valentin Klein" display_name = "vangel76" sync_github_name = false + +[people.FrancoJacquet] +real_name = "Franco Jacquet" diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 875721b923..0c0a81ed90 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -439,7 +439,6 @@ pub const UNCHECKED: &[&str] = &[ "shape.flare", "shape.polarGrid", "shape.rectangularGrid", - "stroke.set", "stroke.setAdvanced", "swatch.edit", "swatch.library.load", diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 03b927cd39..3b1289a862 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\"} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index a1f8e00cc4..e989597ae5 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -74,6 +74,27 @@ fn an_unknown_key_is_named_with_the_nearest_accepted_one() { assert!(check_keys("x", "{a, …as file.new}", &json!({"b": 1})).is_err()); } +/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a +/// misnamed one is refused instead of answering `objects: 1` with nothing changed. +#[test] +fn stroke_set_refuses_an_unknown_key() { + assert!(!UNCHECKED.contains(&"stroke.set")); + let e = refusal("stroke.set", json!({"ids": [7], "width": 0.5})); + assert!(e.starts_with("unknown parameter `width`") && e.contains("weight"), "{e}"); + for ok in [ + json!({"ids": [7], "weight": 0.5}), + json!({"id": 7, "weight": 1, "cap": "round", "join": "bevel", "miterLimit": 4, "align": "inside"}), + json!({"dash": [6, 3], "dashOffset": 1, "alignDashes": true, "startArrow": "Arrow", "endArrow": null, "arrowAlign": "tip"}), + json!({"profile": "lens", "item": null, "target": "contents"}), + // `item_target` reads `aligned` for an explicit item. + json!({"item": 1, "aligned": true, "weight": 2}), + // What document.inspect reports in strokeOptions reads back unchanged. + json!({"widthPoints": null, "gradientMode": "within"}), + ] { + assert!(check_params("stroke.set", &ok).is_ok(), "{ok}"); + } +} + /// A command that takes the keys of one that isn't checked yet isn't checked either. #[test] fn a_reference_to_an_unchecked_command_is_unchecked() { From b91f527c9124b5e8eb4a4b056be5363c9ff3c0b9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:41:50 +0100 Subject: [PATCH 43/50] About: credits tables fit without side-scrolling and their columns resize The Contributors table and the Models table were egui Grids inside a two-way scroll area: they opened wider than the dialog, so they scrolled sideways, and Company and Model sat almost touching. Both are now egui_extras tables. Each column opens at the width of its header and widest cell, the spare width goes to the text columns (Name; Company and Model), and every column edge can be dragged. Widening a column grows the table like a spreadsheet, and only then does it scroll sideways; the header stays put while the rows scroll. Counts and dates are right-aligned and every cell is vertically centred. The sorted column stays highlighted and its direction shows on the toolbar's sort-order button, so headers no longer reserve room for an arrow. The opening widths come from fit_widths, a pure function with unit tests that a fitted table fills its room exactly and that only the text columns give way when room is short. The About dialog opens 820 points wide, so every column fits at its natural width. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/credits.rs | 225 ++++++++++++++++++++++------ crates/ui-egui/src/dialogs/about.rs | 4 +- 2 files changed, 183 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index 440f94c6e5..d344f59e7d 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -264,10 +264,14 @@ pub fn contributors_ui(app: &mut VectorcraftApp, ui: &mut egui::Ui) { ui.label(RichText::new(counts).small().weak()); ui.separator(); if v.table && !list.is_empty() { - // The table scrolls its rows under its header itself, and sideways as a whole. - egui::ScrollArea::horizontal().auto_shrink([false, true]).show(ui, |ui| table(app, ui, &list, &mut v)); + // The table scrolls its rows under its header itself; it only scrolls sideways once its + // columns are dragged wider than the dialog. + ui.allocate_ui(egui::vec2(ui.available_width(), SCROLL_HEIGHT), |ui| { + ui.set_max_height(SCROLL_HEIGHT); + egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(app, ui, &list, &mut v)); + }); } else { - egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + egui::ScrollArea::vertical().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { if list.is_empty() { ui.label(tl!("No contributor data was built into this copy.")); } else { @@ -294,20 +298,120 @@ fn link(app: &mut VectorcraftApp, ui: &mut egui::Ui, c: &Contributor, names: Nam r } +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, down to [`MIN_COLUMN`]. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { + let spare = room - natural.iter().sum::(); + let weight = grow.iter().sum::(); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| *w).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if spare >= 0.0 && weight > 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + (w + spare * w / flexible).max(MIN_COLUMN) + } else { + *w + } + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Each column can be dragged wider or narrower at its edge. The last column fills +/// whatever width is left but never shrinks below its opening width, so widening a column grows +/// the table, as in a spreadsheet, instead of crushing the last one: only a table dragged wider +/// than the window scrolls sideways. Text too long for its column is clipped. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + let last = widths.len().saturating_sub(1); + for (i, w) in widths.into_iter().enumerate() { + let c = if i == last { + egui_extras::Column::remainder().at_least(w.max(MIN_COLUMN)) + } else { + egui_extras::Column::initial(w).at_least(MIN_COLUMN) + }; + t = t.column(c.clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(k.label().1).strong() +} + /// The contributors as a table whose header row, the sort buttons, stays above the rows as they /// scroll (#4944). fn table(app: &mut VectorcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - let (row, names) = (ui.spacing().interact_size.y, v.names); - egui_extras::TableBuilder::new(ui) - .id_salt("credits_table") - .striped(true) - .columns(egui_extras::Column::auto(), SortKey::ALL.len()) - .max_scroll_height(SCROLL_HEIGHT - row) - .header(row, |mut header| { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { for k in SortKey::ALL { header.col(|ui| { - let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; - if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0); + + if r.clicked() { if v.key == k { v.ascending = !v.ascending; } else { @@ -319,25 +423,14 @@ fn table(app: &mut VectorcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: } }) .body(|mut body| { - for c in list { - body.row(row, |mut r| { - r.col(|ui| { - link(app, ui, c, names); + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| link(app, ui, c, v.names)); }); - let cells = [ - group(c.prs), - group(c.commits), - group(c.lines_added), - group(c.lines_deleted), - signed(c.lines_delta()), - group(c.binary_added), - group(c.binary_deleted), - day(c.first_commit).to_string(), - day(c.last_commit).to_string(), - ]; for text in cells { - r.col(|ui| { - ui.label(text); + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); }); } }); @@ -352,21 +445,50 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); - egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")] { - ui.label(RichText::new(h).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } + let h = row_height(ui); + let titles = [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + ui.allocate_ui(egui::vec2(ui.available_width(), SCROLL_HEIGHT), |ui| { + ui.set_max_height(SCROLL_HEIGHT); + egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(title).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); }); } @@ -494,4 +616,19 @@ mod tests { assert_eq!(after[0], Some(header), "the header stays where it was"); assert!(after[1].is_none_or(|p| p.y < row.y), "the rows scrolled: {:?} from {row:?}", after[1]); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } } diff --git a/crates/ui-egui/src/dialogs/about.rs b/crates/ui-egui/src/dialogs/about.rs index e24587eae6..58ad3cc9da 100644 --- a/crates/ui-egui/src/dialogs/about.rs +++ b/crates/ui-egui/src/dialogs/about.rs @@ -32,11 +32,11 @@ pub(super) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.separator(); match tab { 1 => { - ui.set_width(660.0); + ui.set_width(820.0); crate::credits::contributors_ui(app, ui); } 2 => { - ui.set_width(660.0); + ui.set_width(820.0); crate::credits::models_ui(ui); } _ => about_tab(app, ui), From e03665a2152d56828b475fe555f1e0d16a82c896 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 12:06:09 -0800 Subject: [PATCH 44/50] Window: New Window opens a second view of the current document Window > New Window was grayed out. It now opens another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own. While a document has more than one view, each tab shows the view's number after the name ("Untitled-1:2"). An edit in one view shows in every view of the document. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Tile and Cascade are enabled with two views of one document. A new view of a view in a floating window opens in a floating window too. File > Close and a tab's close button close the view; the document's last view closes the document, asking to save it first. Next Document and Previous Document step through the views in tab order. Each Tile pane and floating window draws its view in its own Outline or Preview, and switching views with the Artboard tool targets the artboard the view shows. A switch to another view of the current document resets the tool, as a switch to another document does (Session::reset_tool). Artwork held over another view's tab during a drag switches to that view, and a drop there moves it. Fixes #4116 --- crates/engine/src/session/documents.rs | 6 + crates/ui-egui/src/app.rs | 6 +- crates/ui-egui/src/app/view.rs | 4 +- crates/ui-egui/src/canvas.rs | 20 +- crates/ui-egui/src/canvas/panes.rs | 218 +++++++------- crates/ui-egui/src/canvas/panes/tests.rs | 8 +- crates/ui-egui/src/chrome/tabs.rs | 122 ++++---- crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/control.rs | 22 +- crates/ui-egui/src/doc_windows.rs | 338 ++++++++++++---------- crates/ui-egui/src/doc_windows/tests.rs | 171 ++++++++++- crates/ui-egui/src/doc_windows/views.rs | 247 ++++++++++++++++ crates/ui-egui/src/document_drag.rs | 14 +- crates/ui-egui/src/menus/run.rs | 15 +- crates/ui-egui/src/menus/state.rs | 19 +- crates/ui-egui/src/menus/tests.rs | 14 +- crates/ui-egui/src/menus/ui_commands.rs | 17 +- crates/ui-egui/src/state.rs | 6 +- crates/ui-egui/src/tests/document_drag.rs | 35 +++ crates/ui-egui/src/tests/picks.rs | 15 + crates/ui-egui/src/unsaved.rs | 2 +- docs/gaps.md | 2 +- docs/mcp.md | 11 + docs/target-app-parity.md | 1 + 24 files changed, 937 insertions(+), 378 deletions(-) create mode 100644 crates/ui-egui/src/doc_windows/views.rs diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index ba6ee2f1fe..dd370ff5b0 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -158,6 +158,12 @@ impl Session { self.tool_set_since_reset = false; } + /// Finish the tool's pending work and give it fresh state, as a switch to another document + /// does, while the current document stays the same (a switch to another view of it). + pub fn reset_tool(&mut self) { + self.reset_tool_for_doc_switch(); + } + pub fn set_active(&mut self, index: usize) -> bool { if index < self.docs.len() { if self.active != Some(index) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7cbe32d1eb..fbcf1dd0c2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -444,10 +444,10 @@ impl VectorcraftApp { if !canvas::tiled_area(self, ui) { if floats { let rect = ui.available_rect_before_wrap(); - if let Some(i) = crate::doc_windows::tab_document(self) - && canvas::pane(self, ui, i, rect) + if let Some(w) = crate::doc_windows::tab_window(self) + && canvas::pane(self, ui, w, rect) { - chrome::show_document(self, i); + crate::doc_windows::show_window(self, w); } } else { canvas::show(self, ui); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 0100ed100b..6b5db4fb5b 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -2,7 +2,8 @@ use super::{Value, VectorcraftApp, View, ViewInfo, panels}; impl VectorcraftApp { /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and - /// opens in a floating window while Open Documents As Tabs is cleared). + /// opens in a floating window while Open Documents As Tabs is cleared). The views Window › New + /// Window opened go with their documents. pub fn sync_views(&mut self) { let docs = self.session.documents(); self.views.truncate(docs.len()); @@ -10,6 +11,7 @@ impl VectorcraftApp { for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } + crate::doc_windows::retain_views(self); crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only // invalid indices: valid multiselection, drag state and tool options must survive history. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1330cae2b9..6e4bfa38ee 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -253,7 +253,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let doc = st.doc.clone(); let mask_view = st.shown_mask(); - paint_paper(app, st, ui, &painter, &xf, rect, &t); + paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); // The grid behind the art (Guides & Grid › Grids In Back), else over it below. let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; @@ -574,7 +574,7 @@ fn frame_options( mask_view: Option, smooth_images: bool, ) -> vectorcraft_render::RenderOptions { - let opts = vectorcraft_render::RenderOptions { outline: app.outline_view(), background: None, artboards: false, ..Default::default() }; + let opts = vectorcraft_render::RenderOptions { outline: key.outline, background: None, artboards: false, ..Default::default() }; vectorcraft_render::RenderOptions { proof: vectorcraft_render::proof::active_proof(), overprint_preview: vectorcraft_render::proof::overprint_preview_on(), @@ -678,8 +678,16 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } /// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of -/// document `st`. -fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui, painter: &egui::Painter, xf: &Xf, rect: egui::Rect, t: &Tokens) { +/// document `st`, in Outline when `outline`. +fn paint_paper( + app: &VectorcraftApp, + st: &vectorcraft_engine::DocState, + ui: &Ui, + painter: &egui::Painter, + xf: &Xf, + rect: egui::Rect, + (t, outline): (&Tokens, bool), +) { let doc = &st.doc; // Pasteboard, artboard shadows and paper (Document Setup: the transparency grid's look, the // simulated paper colour; a white Background Contents hides the grid). @@ -691,7 +699,7 @@ fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui, // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). let setup = &doc.setup; painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }); - } else if !app.outline_view() { + } else if !outline { let setup = &doc.setup; let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup)); let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; @@ -709,7 +717,7 @@ fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui, } } } - } else if app.outline_view() { + } else { for ab in &doc.artboards { painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE)); } diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 5876537c3b..5bd974bf92 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,7 +1,8 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document //! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press -//! in it makes its document the current one. +//! in it makes its document the current one. Each view Window › New Window opened has a pane of +//! its own ([`crate::doc_windows`]). use std::collections::HashMap; use std::sync::Arc; @@ -13,28 +14,32 @@ use super::{ Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects, }; +use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; /// A pane's render: what it shows, the document, its size in pixels and view, and its options. type PaneFrame = (CacheKey, Arc, ((u32, u32), Affine), vectorcraft_render::RenderOptions); -/// The renders that the panes of the documents other than the current one draw. +/// Whose render a pane draws: its document's uid and its view's number. +type Slot = (u64, u32); + +/// The renders that the panes of the windows other than the current one draw. #[derive(Default)] pub struct Panes { /// Renders off the UI thread (None: on it, as on wasm). - worker: Option>, + worker: Option>, worker_started: bool, /// Renders on the UI thread when there is no worker. renderer: Option, - /// By document uid: the render shown and what it shows. - shown: HashMap, - /// By document uid: the render the worker is making. - pending: HashMap, - /// The panes the last frame drew, as (document index, pane rect). - pub(crate) last: Vec<(usize, egui::Rect)>, - /// By document uid: the size of the view's area its document was last fitted to in a pane, - /// and the zoom and center the fit gave. - fits: HashMap, + /// By slot: the render shown and what it shows. + pub(crate) shown: HashMap, + /// By slot: the render the worker is making. + pending: HashMap, + /// The panes the last frame drew, as (window, pane rect). + pub(crate) last: Vec<(Win, egui::Rect)>, + /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and + /// center the fit gave. + fits: HashMap, } impl Panes { @@ -46,27 +51,27 @@ impl Panes { self.fits.clear(); } - /// Upload `img`, the render `key` describes. - fn upload(&mut self, ctx: &egui::Context, key: CacheKey, img: &vectorcraft_render::Rendered) { + /// Upload `img`, the render `key` describes, for `slot`. + fn upload(&mut self, ctx: &egui::Context, slot: Slot, key: CacheKey, img: &vectorcraft_render::Rendered) { let color = super::color_image(img); // Pixel Preview's document pixels show hard-edged, as on the canvas. let options = if key.pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; - match self.shown.get_mut(&key.doc) { + match self.shown.get_mut(&slot) { Some((k, tex)) => { tex.set(color, options); *k = key; } None => { - let tex = ctx.load_texture(format!("arrange-pane-{}", key.doc), color, options); - self.shown.insert(key.doc, (key, tex)); + let tex = ctx.load_texture(format!("arrange-pane-{}-{}", slot.0, slot.1), color, options); + self.shown.insert(slot, (key, tex)); } } } - /// Bring the render of the document `key` describes up to `key` (`size` pixels through `view`), - /// on the worker when there is one, then draw the latest render of that document through `xf`, - /// turned and scaled into the view it was rendered for. - fn draw(&mut self, ctx: &egui::Context, painter: &egui::Painter, xf: &Xf, frame: PaneFrame) { + /// Bring `slot`'s render up to `key` (`size` pixels through `view`), on the worker when there + /// is one, then draw the slot's latest render through `xf`, turned and scaled into the view it + /// was rendered for. + fn draw(&mut self, ctx: &egui::Context, painter: &egui::Painter, xf: &Xf, slot: Slot, frame: PaneFrame) { let (key, doc, ((w, h), view), opts) = frame; if !self.worker_started { self.worker_started = true; @@ -75,11 +80,12 @@ impl Panes { match self.worker.as_ref().map(ThumbWorker::poll) { Some(Some(done)) => { for d in done { - if self.pending.get(&d.key.doc) == Some(&d.key) { - self.pending.remove(&d.key.doc); + let (s, k) = d.key; + if self.pending.get(&s) == Some(&k) { + self.pending.remove(&s); } if let Some(img) = d.img { - self.upload(ctx, d.key, &img); + self.upload(ctx, s, k, &img); } } } @@ -90,25 +96,24 @@ impl Panes { } None => {} } - let uid = key.doc; - let current = self.shown.get(&uid).is_some_and(|(k, _)| *k == key) || self.pending.get(&uid) == Some(&key); + let current = self.shown.get(&slot).is_some_and(|(k, _)| *k == key) || self.pending.get(&slot) == Some(&key); if !current { let mut queued = false; if let Some(worker) = &self.worker { let (job_doc, job_opts) = (doc.clone(), opts.clone()); - queued = worker.submit(uid, key.clone(), Box::new(move |r| Some(r.render(&job_doc, w, h, view, &job_opts)))); + queued = worker.submit(slot, (slot, key.clone()), Box::new(move |r| Some(r.render(&job_doc, w, h, view, &job_opts)))); if queued { - self.pending.insert(uid, key.clone()); + self.pending.insert(slot, key.clone()); } else { self.worker = None; } } if !queued { let img = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new).render(&doc, w, h, view, &opts); - self.upload(ctx, key, &img); + self.upload(ctx, slot, key, &img); } } - if let Some((k, tex)) = self.shown.get(&uid) { + if let Some((k, tex)) = self.shown.get(&slot) { // Document pixels: placed over the document rect they cover. if let Some([x0, y0, x1, y1]) = k.pixel { textured_quad(painter, tex.id(), &xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64)), (1.0, 1.0)); @@ -140,21 +145,19 @@ pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. With -/// fewer than two documents open (when the menu item is grayed out) it leaves the view and `tiled` as -/// they are. The documents in floating windows come back under the tabs for it. +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, +/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it +/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { - let n = app.session.documents().len(); + app.sync_views(); + let n = crate::doc_windows::windows(app).len(); if n < 2 { return Ok(json!({"tiled": app.ui.tiled, "panes": n})); } - app.sync_views(); crate::doc_windows::dock_all(app); app.ui.tiled = true; app.ui.home = None; - for v in &mut app.views { - v.fitted = false; - } + crate::doc_windows::unfit_all(app); Ok(json!({"tiled": app.ui.tiled, "panes": n})) } @@ -167,14 +170,14 @@ pub(crate) fn consolidate(app: &mut VectorcraftApp) -> Result bool { if app.session.documents().is_empty() { app.ui.tiled = false; } - let docked = crate::doc_windows::docked(app); + let docked = crate::doc_windows::docked_windows(app); let n = docked.len(); let tiling = app.ui.tiled && n > 1 && app.ui.screen_mode < 3 && !crate::menus::home_showing(app); if !tiling { @@ -185,77 +188,78 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.last.clear(); return false; } - // The current document's pane is the canvas, unless it is in a floating window. - let active = app.session.active_index().filter(|a| docked.contains(a)); + // The current window's pane is the canvas, unless it is a floating one. + let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); app.sync_views(); - let live: Vec = app.session.documents().iter().map(|d| d.uid as usize).collect(); - app.canvas.panes.shown.retain(|uid, _| live.contains(uid)); - app.canvas.panes.pending.retain(|uid, _| live.contains(uid)); - app.canvas.panes.fits.retain(|uid, _| live.contains(uid)); - // A document opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one document: each document fits its new pane. - if app.canvas.panes.last.iter().map(|(i, _)| *i).ne(docked.iter().copied()) { - for i in &docked { - if let Some(v) = app.views.get_mut(*i) { + let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + app.canvas.panes.shown.retain(|s, _| live.contains(s)); + app.canvas.panes.pending.retain(|s, _| live.contains(s)); + app.canvas.panes.fits.retain(|s, _| live.contains(s)); + // A window opened, closed, floated or docked changes the grid, and so does coming back to the + // panes from one window: each window fits its new pane. + if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { + for w in &docked { + if let Some(v) = crate::doc_windows::view_mut(app, *w) { v.fitted = false; } } } let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(usize, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); - let mut areas: Vec> = vec![None; app.session.documents().len()]; - for (i, cell) in &cells { - if let Some(a) = areas.get_mut(*i) { - *a = Some(view_rects(app, *cell, ppp).1); - } - } + let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) // stays over them. - for (i, cell) in cells.iter().copied().filter(|(i, _)| Some(*i) != active) { - if pane(app, ui, i, cell) { - activate = Some(i); + for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) { + if pane(app, ui, w, cell) { + activate = Some(w); } ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); } - if let Some((_, cell)) = cells.iter().copied().find(|(i, _)| Some(*i) == active) { + if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) { let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(cell)); super::show(app, &mut canvas); ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); } // Note the fits this frame made, for `refit_resized`. - for ((i, area), was_unfitted) in areas.iter().enumerate().zip(unfitted) { - if let (Some(area), true, Some(v), Some(d)) = (area, was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) { - app.canvas.panes.fits.insert(d.uid as usize, (area.size(), v.zoom, v.center)); + for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { + if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { + app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); } } app.canvas.panes.last = cells; - if let Some(i) = activate { - crate::chrome::show_document(app, i); + if let Some(w) = activate { + crate::doc_windows::show_window(app, w); } true } -/// Unfit each document whose view is still where a pane fit left it when its view's area (in -/// `areas`, by document index; None for a document without a pane) has changed size, as when the -/// window or a panel is resized: it fits its pane again. A view zoomed or scrolled since keeps its -/// place. → which views are unfitted now. -fn refit_resized(app: &mut VectorcraftApp, areas: &[Option]) -> Vec { - let fits = &app.canvas.panes.fits; - let docs = app.session.documents(); - for ((v, d), area) in app.views.iter_mut().zip(docs).zip(areas) { - if let Some(area) = area - && let Some((size, zoom, center)) = fits.get(&(d.uid as usize)) - && *size != area.size() - && *zoom == v.zoom - && *center == v.center - { - v.fitted = false; - } - } - app.views.iter().map(|v| !v.fitted).collect() +/// Window `w`'s [`Slot`]. +fn slot(app: &VectorcraftApp, (i, n): Win) -> Option { + app.session.documents().get(i).map(|d| (d.uid, n)) +} + +/// Unfit each window whose view is still where a pane fit left it when its view's area (`areas`, +/// by window) has changed size, as when the window or a panel is resized: it fits its pane again. +/// A view zoomed or scrolled since keeps its place. → which of `areas`' views are unfitted now. +fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)]) -> Vec { + areas + .iter() + .map(|(w, area)| { + let fit = slot(app, *w).and_then(|s| app.canvas.panes.fits.get(&s).copied()); + let Some(v) = crate::doc_windows::view_mut(app, *w) else { return false }; + if let Some((size, zoom, center)) = fit + && size != area.size() + && zoom == v.zoom + && center == v.center + { + v.fitted = false; + } + !v.fitted + }) + .collect() } /// Fit `v` to show its artboard (the first if it has gone) in `rect`, as Fit Artboard in Window @@ -268,41 +272,45 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect) { } } -/// The pane of document `i`, not the current one, in `cell`: its paper, art, grid, artboards, -/// guides and selected objects, and its rulers and the room of the canvas's scroll bars, so the -/// document stays where it is when the pane becomes the canvas. True when a press in the pane asks -/// for its document to become the current one. A floating document's window draws its document -/// with this too ([`crate::doc_windows`]). -pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool { +/// The pane of window `w` (document `i`'s view `n`), not the current one, in `cell`: its paper, +/// art, grid, artboards, guides and selected objects, and its rulers and the room of the canvas's +/// scroll bars, so the document stays where it is when the pane becomes the canvas. True when a +/// press in the pane asks for its window to become the current one. A floating window draws its +/// view with this too ([`crate::doc_windows`]). +pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); let (full, rect) = view_rects(app, cell, ppp); - let Some(st) = app.session.documents().get(i) else { return false }; - if let Some(v) = app.views.get_mut(i).filter(|v| !v.fitted) { - fit_pane(v, &st.doc, rect); + let Some(st) = app.session.documents().get(w.0) else { return false }; + let doc = st.doc.clone(); + if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { + fit_pane(v, &doc, rect); } - let v = app.views.get(i).copied().unwrap_or_default(); + let v = crate::doc_windows::view(app, w).copied().unwrap_or_default(); + let Some(st) = app.session.documents().get(w.0) else { return false }; + let slot = (st.uid, w.1); let xf = Xf::new(rect, &v); let painter = ui.painter_at(rect); - paint_paper(app, st, ui, &painter, &xf, rect, &t); + paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline)); let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); } let size = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)); - let (w, h) = (size(rect.width()), size(rect.height())); + let (pw, ph) = (size(rect.width()), size(rect.height())); // View › Pixel Preview, as the canvas draws it. let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten(); let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; - let mut key = cache_key(app, ui, st, &t, &v, (w, h, ppp), (pixel, smooth_images)); - // The current document's drag and Image Trace hold are not this document's. - (key.dragging, key.trace_source) = (false, None); + let mut key = cache_key(app, ui, st, &t, &v, (pw, ph, ppp), (pixel, smooth_images)); + // The current document's drag and Image Trace hold are not this document's, and this view has + // its own Outline or Preview. + (key.dragging, key.trace_source, key.outline) = (false, None, v.outline); let opts = frame_options(app, &key, st.shown_mask(), smooth_images); - let (fw, fh, view) = frame_view(pixel, (w, h), &v, ppp); + let (fw, fh, view) = frame_view(pixel, (pw, ph), &v, ppp); let doc = st.doc.clone(); - app.canvas.panes.draw(ui.ctx(), &painter, &xf, (key, doc, ((fw, fh), view), opts)); - let Some(st) = app.session.documents().get(i) else { return false }; + app.canvas.panes.draw(ui.ctx(), &painter, &xf, slot, (key, doc, ((fw, fh), view), opts)); + let Some(st) = app.session.documents().get(w.0) else { return false }; if let Some(look) = grid_look.filter(|_| !grids_in_back) { grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); } @@ -327,7 +335,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect ui.painter().rect_filled(bar, 0.0, t.ruler); } } - let resp = ui.interact(cell, egui::Id::unique(("arrange-pane", st.uid)), Sense::click_and_drag()); + let resp = ui.interact(cell, egui::Id::unique(("arrange-pane", st.uid, w.1)), Sense::click_and_drag()); resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed()) } diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index cdd6add6dc..91a0ca5737 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -45,7 +45,7 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { - app.canvas.panes.last.iter().copied().unzip() + app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() } #[test] @@ -198,7 +198,7 @@ fn closing_a_document_while_tiled_tiles_the_others() { app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0, [0, 1, 2]); - let first = app.session.documents()[0].uid as usize; + let first = (app.session.documents()[0].uid, 1); assert!(app.canvas.panes.shown.contains_key(&first)); // The first document, not the current one, closes. app.run("file.close", json!({"index": 0})).unwrap(); @@ -220,7 +220,7 @@ fn an_edit_shows_in_its_pane_once_another_document_is_current() { app.run("document.activate", json!({"index": 0})).unwrap(); app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); - let uid = app.session.documents()[1].uid as usize; + let uid = (app.session.documents()[1].uid, 1); let before = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.revision); assert_eq!(before, Some(app.session.documents()[1].revision), "the second document's pane shows it"); app.run("document.activate", json!({"index": 1})).unwrap(); @@ -294,7 +294,7 @@ fn other_panes_show_pixel_preview() { app.ui.view.pixel_preview = true; app.views[0].zoom = 4.0; frame(&mut app, &ctx, vec![]); - let uid = app.session.documents()[0].uid as usize; + let uid = (app.session.documents()[0].uid, 1); let key = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.clone()).unwrap(); let [x0, y0, x1, y1] = key.pixel.expect("the pane renders document pixels"); assert!(x1 > x0 && y1 > y0); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index cac5949161..d81e2fb973 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -1,28 +1,37 @@ use super::{Sense, Stroke, Tokens, Ui, VectorcraftApp, icons, json, theme, vec2, widgets, zoom_label}; -/// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited -/// "Name* @ 66.67 % (/Opacity Mask)". +/// [`view_tab_title`] for a document with one view. +#[cfg(test)] pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, display_print_size: bool) -> String { + view_tab_title(d, None, zoom, outline, display_print_size) +} + +/// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited +/// "Name* @ 66.67 % (/Opacity Mask)". For a view of a document with more than one +/// view, the view's `number` follows the name: "Name:2* @ 66.67 % (RGB/Preview)". +fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, zoom: f64, outline: bool, display_print_size: bool) -> String { let mode = if d.doc.mask_edit.is_some() { format!("<{0}>/{0}", tl!("Opacity Mask")) } else { let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" }; format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") }) }; - format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %")) + let number = number.map(|n| format!(":{n}")).unwrap_or_default(); + format!("{}{number}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %")) } -/// The title of open document `i`'s tab, with its own view's zoom and Outline or Preview. -pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engine::DocState) -> String { - let view = app.views.get(i); +/// The title of window `w`, a view of document `d`: with the view's zoom and Outline or Preview, +/// and the view's number while the document has more than one view. +fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState) -> String { + let view = crate::doc_windows::view(app, w); let zoom = view.map_or(1.0, |v| v.zoom); - tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) + view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) } -/// The title of document `i`'s floating window ([`crate::doc_windows`]): its tab's title. -pub(crate) fn document_window_title(app: &VectorcraftApp, i: usize) -> Option { - let d = app.session.documents().get(i)?; - Some(doc_tab_title(app, i, d)) +/// The title of window `w`'s tab and floating window ([`crate::doc_windows`]). +pub(crate) fn document_window_title(app: &VectorcraftApp, w: crate::doc_windows::Win) -> Option { + let d = app.session.documents().get(w.0)?; + Some(window_tab_title(app, w, d)) } /// The height of the tab strip and the size of a tab's title, in points: larger with User @@ -31,16 +40,16 @@ fn tab_size(app: &VectorcraftApp) -> (f32, f32) { if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) } } -/// The tab at the top of document `i`'s floating OS window ([`crate::doc_windows`]): a strip with -/// the document's tab, as the main window's strip draws it but without its ×. → the tab's -/// response, which senses clicks and drags. -pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, i: usize) -> egui::Response { +/// The tab at the top of window `w`'s floating OS window ([`crate::doc_windows`]): a strip with the +/// window's tab, as the main window's strip draws it but without its ×. → the tab's response, +/// which senses clicks and drags. +pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_windows::Win) -> egui::Response { let t = Tokens::get(ui.ctx()); let (height, title_size) = tab_size(app); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); - let title = document_window_title(app, i).unwrap_or_default(); + let title = document_window_title(app, w).unwrap_or_default(); let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); @@ -88,10 +97,10 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs /// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's /// right end, which lists every open document, and the active tab is always in view (#746). -/// Documents in floating windows have no tab ([`crate::doc_windows`]); while the current document -/// is in one, the tab of the document the strip shows is the highlighted one. A tab dragged more -/// than [`crate::doc_windows::TEAR_OFF`] above or below the strip floats its document in a window -/// under the pointer. +/// Each view Window › New Window opened has a tab of its own. Windows floating have no tab +/// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the +/// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] +/// above or below the strip floats its view in a window under the pointer. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -102,16 +111,16 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. - let shown = crate::doc_windows::tab_document(app).filter(|_| app.ui.home.is_none()); - // The documents under the tabs, by index; `active` is the position of the highlighted one. - let docked = crate::doc_windows::docked(app); - let active = docked.iter().position(|i| Some(*i) == shown); + let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); + // The windows under the tabs; `active` is the position of the highlighted one. + let docked = crate::doc_windows::docked_windows(app); + let active = docked.iter().position(|w| Some(*w) == shown); let tabs: Vec<(String, std::sync::Arc)> = docked .iter() - .filter_map(|i| Some((*i, app.session.documents().get(*i)?))) - .map(|(i, d)| { - let title = doc_tab_title(app, i, d); - let color = if Some(i) == shown { t.text_strong } else { t.text_dim }; + .filter_map(|w| Some((*w, app.session.documents().get(w.0)?))) + .map(|(w, d)| { + let title = window_tab_title(app, w, d); + let color = if Some(w) == shown { t.text_strong } else { t.text_dim }; (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) }) .collect(); @@ -128,10 +137,11 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if x + w > strip.left() + room && Some(k) != active { break; } - let Some(&i) = docked.get(k) else { break }; + let Some(&win) = docked.get(k) else { break }; + let i = win.0; let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); - let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click_and_drag()); + let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag()); if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -142,26 +152,27 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { // (#673). let (x_center, title_left) = if CLOSE_BEFORE_TITLE { (r.left() + 16.0, r.left() + 32.0) } else { (r.right() - 16.0, r.left() + 14.0) }; let xr = egui::Rect::from_center_size(egui::pos2(x_center, r.center().y), vec2(12.0, 12.0)); - let xresp = ui.interact(xr.expand(3.0), ui.scope_id().with(("tabx", i)), Sense::click()); + let xresp = ui.interact(xr.expand(3.0), ui.scope_id().with(("tabx", i, win.1)), Sense::click()); icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text }); ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley.clone(), t.text); - hovering_art |= crate::document_drag::hover_tab(app, &resp, i, xr.expand(3.0)); + hovering_art |= crate::document_drag::hover_tab(app, &resp, win, xr.expand(3.0)); if xresp.clicked() { - close = Some(i); + close = Some(win); } else if resp.clicked() { - activate = Some(i); + activate = Some(win); } else if let Some(at) = tear_off(ui, &resp, strip) { - float = Some((i, at)); + float = Some((win, at)); } x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); - // The » button: every open document, floating ones included, the active one checked. The list + // The » button: every window, floating ones included, the current one checked. The list // scrolls once it reaches the bottom of the window, so every document of a large session stays // reachable (#4017). if overflow { - let current = app.session.active_index().filter(|_| app.ui.home.is_none()); - let titles: Vec = (0..app.session.documents().len()).map(|i| document_window_title(app, i).unwrap_or_default()).collect(); + let current = crate::doc_windows::current(app).filter(|_| app.ui.home.is_none()); + let all = crate::doc_windows::windows(app); + let titles: Vec<(crate::doc_windows::Win, String)> = all.iter().map(|w| (*w, document_window_title(app, *w).unwrap_or_default())).collect(); let more = egui::Rect::from_min_max(egui::pos2(strip.right() - MORE, strip.top()), egui::pos2(strip.right(), strip.bottom() - 1.0)); let resp = ui.interact(more, ui.scope_id().with("tabs-more"), Sense::click()); ui.painter().rect_filled(more, 0.0, if resp.hovered() { t.hover.gamma_multiply(0.4) } else { t.tab_strip }); @@ -169,25 +180,25 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = resp.on_hover_text(tl!("Show all open documents")); egui::Popup::menu(&resp).show(|ui| { widgets::menu_scroll(ui, |ui| { - for (i, title) in titles.iter().enumerate() { - if widgets::menu_item_name(ui, title, true, Some(i) == current) { - activate = Some(i); + for (w, title) in &titles { + if widgets::menu_item_name(ui, title, true, Some(*w) == current) { + activate = Some(*w); ui.close(); } } }); }); } - if let Some(i) = close { - if let Err(e) = crate::unsaved::close(app, i) { + if let Some(w) = close { + if let Err(e) = crate::doc_windows::close_window(app, w) { app.status(e); } - } else if let Some((i, at)) = float { - if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "at": [at.x, at.y]})) { + } else if let Some(((i, n), at)) = float { + if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "view": n, "at": [at.x, at.y]})) { app.status(e); } - } else if let Some(i) = activate { - show_document(app, i); + } else if let Some(w) = activate { + crate::doc_windows::show_window(app, w); } } @@ -212,20 +223,27 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, i: usize) { /// the current one in tab order (before it) the current one, as a click on its tab does. After the /// last document comes the first, and before the first document comes the last. On the Home /// screen, where no tab is the current one, the next document is the first and the previous -/// document is the last. Returns `{index}`. +/// document is the last. Each view Window › New Window opened is a step of its own. Returns +/// `{index}`, with the view's number as `view` while the document has more than one view. pub fn step_document(app: &mut VectorcraftApp, forward: bool) -> Result { - let n = app.session.documents().len(); + let all = crate::doc_windows::windows(app); + let n = all.len(); if n == 0 { return Err("no document open".into()); } - let i = match (app.session.active_index().filter(|_| app.ui.home.is_none()), forward) { + let current = crate::doc_windows::current(app).filter(|_| app.ui.home.is_none()).and_then(|c| all.iter().position(|w| *w == c)); + let k = match (current, forward) { (Some(a), true) => (a + 1) % n, (Some(a), false) => (a + n - 1) % n, (None, true) => 0, (None, false) => n - 1, }; - show_document(app, i); - Ok(json!({ "index": i })) + let Some(&w) = all.get(k) else { return Err("no document open".into()) }; + crate::doc_windows::show_window(app, w); + Ok(match crate::doc_windows::label(app, w) { + Some(view) => json!({ "index": w.0, "view": view }), + None => json!({ "index": w.0 }), + }) } /// The isolation mode breadcrumb bar. It is drawn over the top of `area` (the canvas), after the diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 774de75405..a2773f5f7b 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -873,7 +873,7 @@ fn only_the_outlined_documents_tab_reads_outline() { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); app.run("view.outline", json!({})).unwrap(); - let titles: Vec = app.session.documents().iter().enumerate().map(|(i, d)| super::tabs::doc_tab_title(&app, i, d)).collect(); + let titles: Vec = (0..app.session.documents().len()).filter_map(|i| super::document_window_title(&app, (i, 1))).collect(); assert!(titles[0].ends_with("(RGB/Preview)"), "{titles:?}"); assert!(titles[1].ends_with("(RGB/Outline)"), "{titles:?}"); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d3278e97ea..d25a08f94d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -192,17 +192,23 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()), "canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])), // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index and rect. Canvas coordinates map to the current document's - // pane, inside its rulers and scroll bars (`canvasRect`). + // each one's document index, view number (Window › New Window) and rect. Canvas + // coordinates map to the current window's pane, inside its rulers and scroll bars + // (`canvasRect`). "tiled": app.ui.tiled, - "panes": app.canvas.panes.last.iter().map(|(i, c)| json!({ - "document": i, + "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ + "document": w.0, + "view": w.1, "rect": [c.left(), c.top(), c.width(), c.height()], - "active": app.session.active_index() == Some(*i), + "active": crate::doc_windows::current(app) == Some(*w), })).collect::>(), - // Window › Arrange › Float in Window: the documents in floating windows, by index. While - // the current one floats, `canvasRect` is in its window's coordinates. - "floating": (0..app.session.documents().len()).filter(|i| crate::doc_windows::is_floating(app, *i)).collect::>(), + // Window › Arrange › Float in Window: the floating windows' documents, by index. While the + // current one floats, `canvasRect` is in its window's coordinates. + "floating": crate::doc_windows::floating_windows(app).iter().map(|w| w.0).collect::>(), + // Window › New Window: every window, as [document index, view number], in tab order, and + // the current one. + "windows": crate::doc_windows::windows(app), + "currentWindow": crate::doc_windows::current(app), "window": [r.width(), r.height()], "documents": app.session.documents().iter().map(|d| json!({"title": d.title(), "dirty": d.is_dirty()})).collect::>(), "activeDocument": app.session.active_index(), diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 6c70eb4491..d1984536fe 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -12,11 +12,20 @@ //! //! With Preferences › User Interface › Open Documents As Tabs cleared, each document opened or //! created afterwards opens in a floating window ([`opened`]). +//! +//! Each view of a document that Window › New Window opened ([`views`]) is a window of its own +//! here: it has its own tab, pane or floating window. use serde_json::{Value, json}; use crate::VectorcraftApp; +mod views; +pub(crate) use views::{ + Views, Win, close_current, close_window, current, label, new_window, retain as retain_views, show_window, unfit_all, view, view_mut, windows, +}; +use views::{find, key, window_param}; + /// How far above or below the tab strip, in points, a dragged document tab must be released to /// float its document. pub(crate) const TEAR_OFF: f32 = 24.0; @@ -30,11 +39,13 @@ const CASCADE_MARGIN: f32 = 24.0; /// The smallest size of a document window, in points. const MIN_SIZE: egui::Vec2 = egui::vec2(240.0, 180.0); -/// A document in a floating window. +/// A document's view in a floating window. #[derive(Clone, Debug)] pub struct DocWindow { /// The document ([`vectorcraft_engine::DocState::uid`]). pub uid: u64, + /// The view's number ([`views`]). + pub view: u32, /// Where the window goes, in the main window's points. pub place: egui::Rect, /// The window's own number ([`Windows::opened`]): a document floated again gets a new window, @@ -61,8 +72,8 @@ pub struct DocWindow { type Fit = (egui::Vec2, f64, vectorcraft_geom::Point); impl DocWindow { - fn new(uid: u64, place: egui::Rect) -> Self { - Self { uid, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None } + fn new((uid, view): (u64, u32), place: egui::Rect) -> Self { + Self { uid, view, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None } } } @@ -71,17 +82,19 @@ impl DocWindow { pub struct Windows { /// The document area of the main window (the tabs and the canvas) in its last frame. pub(crate) area: Option, - /// The current document (its uid) when the windows were last drawn: a floating document that - /// becomes the current one comes to the front. - current: Option, - /// While Presentation Mode is on: the floating documents (their uids) it has shown. - presented: Option>, + /// The current window ([`views::key`]) when the windows were last drawn: a floating window + /// that becomes the current one comes to the front. + current: Option<(u64, u32)>, + /// While Presentation Mode is on: the floating windows ([`views::key`]) it has shown. + presented: Option>, /// The main window's tab strip in its last frame, while it was drawn. pub(crate) strip: Option, /// Counts the windows opened ([`DocWindow::number`]). opened: u32, /// The open documents (their uids) when [`opened`] last ran, or when the app started. known: Vec, + /// The documents' views beyond the one each shows ([`views`]). + pub(crate) views: Views, } impl Windows { @@ -97,32 +110,51 @@ pub(crate) fn torn_off(strip: egui::Rect, p: egui::Pos2) -> bool { p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF } -/// Whether document `i` is in a floating window. +/// Whether window `w` is in a floating window. +pub(crate) fn floats(app: &VectorcraftApp, w: Win) -> bool { + key(app, w).is_some_and(|(u, n)| app.ui.floating.iter().any(|x| x.uid == u && x.view == n)) +} + +/// Whether document `i`'s shown view is in a floating window. +#[cfg(test)] pub(crate) fn is_floating(app: &VectorcraftApp, i: usize) -> bool { - app.session.documents().get(i).is_some_and(|d| app.ui.floating.iter().any(|w| w.uid == d.uid)) + floats(app, (i, views::shown(app, i))) } -/// The documents under the tab strip, by index, in tab order. +/// The windows under the tab strip, in tab order. +pub(crate) fn docked_windows(app: &VectorcraftApp) -> Vec { + windows(app).into_iter().filter(|w| !floats(app, *w)).collect() +} + +/// The documents with a window under the tab strip, by index, in tab order. +#[cfg(test)] pub(crate) fn docked(app: &VectorcraftApp) -> Vec { - (0..app.session.documents().len()).filter(|i| !is_floating(app, *i)).collect() + let mut docs: Vec = docked_windows(app).into_iter().map(|(i, _)| i).collect(); + docs.dedup(); + docs } -/// The document the tab strip shows: the current one when it is under the tabs, else the tabbed -/// document that was current last, else the first tabbed one. -pub(crate) fn tab_document(app: &VectorcraftApp) -> Option { - let docked = docked(app); - let active = app.session.active_index(); - if let Some(a) = active.filter(|a| docked.contains(a)) { - return Some(a); +/// The window the tab strip shows: the current one when it is under the tabs, else the tabbed +/// window that was current last, else the first tabbed one. +pub(crate) fn tab_window(app: &VectorcraftApp) -> Option { + let docked = docked_windows(app); + if let Some(c) = current(app).filter(|c| docked.contains(c)) { + return Some(c); } - let last = app.ui.tab_document.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid)); - last.filter(|i| docked.contains(i)).or(docked.first().copied()) + let last = app.ui.tab_document.and_then(|k| find(app, k)); + last.filter(|w| docked.contains(w)).or(docked.first().copied()) } -/// Whether the current document is in a floating window, outside the Home screen and Presentation -/// Mode: the main window's canvas then draws the tab strip's document as a pane. +/// The document of the window the tab strip shows ([`tab_window`]). +#[cfg(test)] +pub(crate) fn tab_document(app: &VectorcraftApp) -> Option { + tab_window(app).map(|(i, _)| i) +} + +/// Whether the current window is a floating one, outside the Home screen and Presentation Mode: +/// the main window's canvas then draws the tab strip's window as a pane. pub(crate) fn current_floats(app: &VectorcraftApp) -> bool { - app.session.active_index().is_some_and(|i| is_floating(app, i)) && !crate::menus::home_showing(app) && !presenting(app) + current(app).is_some_and(|w| floats(app, w)) && !crate::menus::home_showing(app) && !presenting(app) } /// Whether Presentation Mode is on: the main window shows the current document, and the floating @@ -151,11 +183,11 @@ fn area(app: &VectorcraftApp) -> egui::Rect { app.canvas.windows.area.filter(|r| r.is_positive()).unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))) } -/// Float documents `docs` (indices), each at the next cascade place after the windows already -/// open. Each fits its window. -fn float(app: &mut VectorcraftApp, docs: &[usize]) { +/// Float windows `wins`, each at the next cascade place after the windows already open. Each fits +/// its window. +fn float(app: &mut VectorcraftApp, wins: &[Win]) { app.sync_views(); - place(app, docs); + place(app, wins); } /// The documents opened or created since the last call: each one opened while Preferences › User @@ -168,131 +200,120 @@ pub(crate) fn opened(app: &mut VectorcraftApp) { if known.len() == docs.len() && known.iter().zip(docs).all(|(u, d)| *u == d.uid) { return; } - let new: Vec = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| i).collect(); + let new: Vec = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| (i, 1)).collect(); app.canvas.windows.known = docs.iter().map(|d| d.uid).collect(); if !new.is_empty() { place(app, &new); } } -/// [`float`] for documents whose views exist. -fn place(app: &mut VectorcraftApp, docs: &[usize]) { +/// [`float`] for windows whose views exist. +fn place(app: &mut VectorcraftApp, wins: &[Win]) { let first = app.ui.floating.len(); - let places = cascade_places(area(app), first + docs.len()); - for (k, i) in docs.iter().enumerate() { - let Some(uid) = app.session.documents().get(*i).map(|d| d.uid) else { continue }; - if app.ui.floating.iter().any(|w| w.uid == uid) { + let places = cascade_places(area(app), first + wins.len()); + for (k, w) in wins.iter().enumerate() { + let Some(key) = key(app, *w) else { continue }; + if floats(app, *w) { continue; } let place = places.get(first + k).copied().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, MIN_SIZE)); app.canvas.windows.opened = app.canvas.windows.opened.wrapping_add(1); - let mut w = DocWindow::new(uid, place); - w.number = app.canvas.windows.opened; - app.ui.floating.push(w); - if let Some(v) = app.views.get_mut(*i) { + let mut win = DocWindow::new(key, place); + win.number = app.canvas.windows.opened; + app.ui.floating.push(win); + if let Some(v) = view_mut(app, *w) { v.fitted = false; } } - if !docs.is_empty() { + if !wins.is_empty() { app.ui.home = None; } } -/// The floating documents' indices, in the order their windows opened. +/// The floating windows' document indices, in the order the windows opened. fn floating_indices(app: &VectorcraftApp) -> Vec { - app.ui.floating.iter().filter_map(|w| app.session.documents().iter().position(|d| d.uid == w.uid)).collect() + floating_windows(app).into_iter().map(|(i, _)| i).collect() } -/// The open document `p`'s `index` names: `Ok(None)` without one. -fn document_param(app: &VectorcraftApp, p: &Value) -> Result, String> { - match p.get("index") { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_u64() - .and_then(|i| usize::try_from(i).ok()) - .filter(|i| *i < app.session.documents().len()) - .map(Some) - .ok_or_else(|| "no such document".to_string()), - } +/// The floating windows, in the order they opened. +pub(crate) fn floating_windows(app: &VectorcraftApp) -> Vec { + app.ui.floating.iter().filter_map(|w| find(app, (w.uid, w.view))).collect() } -/// `window.arrange.floatInWindow`: the current document, or document `index`, leaves the tab strip -/// for a floating window of its own, with its top-left corner at `at` (`[x, y]` in the main -/// window's points) when given, else at the next cascade place. A document already floating stays -/// where it is. Document `index` becomes the current one. Returns `{floating}`. +/// `window.arrange.floatInWindow`: the current window, or document `index`'s view `view` (its +/// shown view without one), leaves the tab strip for a floating window of its own, with its +/// top-left corner at `at` (`[x, y]` in the main window's points) when given, else at the next +/// cascade place. A window already floating stays where it is. The window `index` names becomes +/// the current one. Returns `{floating}`, the floating windows' document indices. pub(crate) fn float_in_window(app: &mut VectorcraftApp, p: &Value) -> Result { - let index = document_param(app, p)?; + let named = window_param(app, p)?; let at = p .get("at") .and_then(Value::as_array) .and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))) .filter(|at| at.is_finite()); - if let Some(i) = index.or(app.session.active_index()).filter(|i| !is_floating(app, *i)) { - float(app, &[i]); + if let Some(w) = named.or(current(app)).filter(|w| !floats(app, *w)) { + float(app, &[w]); if let (Some(at), Some(w)) = (at, app.ui.floating.last_mut()) { w.place = egui::Rect::from_min_size(at, w.place.size()); } } - if let Some(i) = index { - crate::chrome::show_document(app, i); + if let Some(w) = named { + show_window(app, w); } Ok(json!({ "floating": floating_indices(app) })) } -/// `window.arrange.consolidateAllWindows` with an `index`: document `index`, floating or not, -/// goes back under its tab, fitted there, and becomes the current one; the other windows and Tile -/// stay as they are. Returns `{tiled, floating}`. +/// `window.arrange.consolidateAllWindows` with an `index`: document `index`'s view `view` (its +/// shown view without one), floating or not, goes back under its tab, fitted there, and becomes +/// the current window; the other windows and Tile stay as they are. Returns `{tiled, floating}`. pub(crate) fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { - let Some(i) = document_param(app, p)? else { + let Some(w) = window_param(app, p)? else { return Err("no such document".into()); }; - if is_floating(app, i) { - let uid = app.session.documents().get(i).map(|d| d.uid); - app.ui.floating.retain(|w| Some(w.uid) != uid); - if let Some(v) = app.views.get_mut(i) { + if let Some((u, n)) = key(app, w).filter(|_| floats(app, w)) { + app.ui.floating.retain(|x| !(x.uid == u && x.view == n)); + if let Some(v) = view_mut(app, w) { v.fitted = false; } } - crate::chrome::show_document(app, i); + show_window(app, w); Ok(json!({ "tiled": app.ui.tiled, "floating": floating_indices(app) })) } -/// `window.arrange.floatAllInWindows`: every document under the tab strip goes to a floating window +/// `window.arrange.floatAllInWindows`: every window under the tab strip goes to a floating window /// of its own. Returns `{floating}`. pub(crate) fn float_all(app: &mut VectorcraftApp) -> Result { - let docked = docked(app); + let docked = docked_windows(app); float(app, &docked); Ok(json!({ "floating": floating_indices(app) })) } -/// `window.arrange.cascade`: every document in a floating window, the windows stacked from the -/// document area's upper left to its lower right in tab order, each fitted to its window, the -/// current document's in front. Returns `{floating}`. +/// `window.arrange.cascade`: every window floating, stacked from the document area's upper left to +/// its lower right in tab order, each fitted to its window, the current window in front. Returns +/// `{floating}`. pub(crate) fn cascade(app: &mut VectorcraftApp) -> Result { app.ui.tiled = false; - let docked = docked(app); + let docked = docked_windows(app); float(app, &docked); - let order: Vec = app.session.documents().iter().map(|d| d.uid).collect(); - app.ui.floating.sort_by_key(|w| order.iter().position(|u| *u == w.uid)); + let order: Vec<(u64, u32)> = windows(app).into_iter().filter_map(|w| key(app, w)).collect(); + app.ui.floating.sort_by_key(|w| order.iter().position(|k| *k == (w.uid, w.view))); let places = cascade_places(area(app), app.ui.floating.len()); for (w, place) in app.ui.floating.iter_mut().zip(places) { w.place = place; w.generation += 1; } - for v in &mut app.views { - v.fitted = false; - } - // The current document's window comes to the front. + unfit_all(app); + // The current window comes to the front. app.canvas.windows.current = None; Ok(json!({ "floating": floating_indices(app) })) } -/// Every floating document back under the tab strip ([`crate::canvas::consolidate`], Tile), each +/// Every floating window back under the tab strip ([`crate::canvas::consolidate`], Tile), each /// fitted to where it shows. pub(crate) fn dock_all(app: &mut VectorcraftApp) { - let floating = floating_indices(app); - for i in floating { - if let Some(v) = app.views.get_mut(i) { + for w in floating_windows(app) { + if let Some(v) = view_mut(app, w) { v.fitted = false; } } @@ -319,9 +340,9 @@ fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool { true } -/// The OS window of document window `uid`. -fn viewport_id(uid: u64) -> egui::ViewportId { - egui::ViewportId::from_hash_of(("vectorcraft-document-window", uid)) +/// The OS window of document window `w`. +fn viewport_id(w: &DocWindow) -> egui::ViewportId { + egui::ViewportId::from_hash_of(("vectorcraft-document-window", w.uid, w.number)) } /// The id of document window `w` inside the main window: a new one for each window and each @@ -352,33 +373,36 @@ struct Shown { /// Draw the floating document windows, after the main window's canvas. Call once per frame from /// the main window. pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { - let live: Vec = app.session.documents().iter().map(|d| d.uid).collect(); - app.ui.floating.retain(|w| live.contains(&w.uid)); - let current = app.session.active().map(|d| d.uid); - if let Some(uid) = current.filter(|u| !app.ui.floating.iter().any(|w| w.uid == *u)) { - app.ui.tab_document = Some(uid); + let live: Vec<(u64, u32)> = windows(app).into_iter().filter_map(|w| key(app, w)).collect(); + app.ui.floating.retain(|w| live.contains(&(w.uid, w.view))); + let current = current(app).and_then(|w| key(app, w)); + let floating = |app: &VectorcraftApp, k: &(u64, u32)| app.ui.floating.iter().any(|w| (w.uid, w.view) == *k); + if let Some(k) = current.filter(|k| !floating(app, k)) { + app.ui.tab_document = Some(k); } - // Presentation Mode fits each floating document it shows to the main window: back in their - // floating windows, those documents fit their windows again. + // Presentation Mode fits each floating window it shows to the main window: back in their + // floating windows, those views fit their windows again. let presenting = presenting(app); if presenting { + let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); - if let Some(uid) = current.filter(|u| app.ui.floating.iter().any(|w| w.uid == *u) && !shown.contains(u)) { - shown.push(uid); + if let Some(k) = current.filter(|k| is_floating && !shown.contains(k)) { + shown.push(k); if let Some(v) = app.session.active_index().and_then(|i| app.views.get_mut(i)) { v.fitted = false; ctx.request_repaint(); } } } else if let Some(shown) = app.canvas.windows.presented.take() { - for (d, v) in app.session.documents().iter().zip(app.views.iter_mut()) { - if shown.contains(&d.uid) { + let wins: Vec = shown.into_iter().filter_map(|k| find(app, k)).collect(); + for w in wins { + if let Some(v) = view_mut(app, w) { v.fitted = false; } } } - // While Presentation Mode hides the windows, `current` keeps the document whose window was in - // front, so a document made current meanwhile comes to the front when it ends. + // While Presentation Mode hides the windows, `current` keeps the window that was in front, so a + // window made current meanwhile comes to the front when it ends. if presenting { return; } @@ -402,7 +426,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } #[cfg(not(target_arch = "wasm32"))] if native { - input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(|w| viewport_id(w.uid)).collect()); + input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(viewport_id).collect()); } // While a dialog or other modal is open the windows take no input, as the main window behind // it takes none: each draws its document as a pane, the current one included. @@ -412,31 +436,29 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut dock = None; let mut over_strip = false; for w in app.ui.floating.clone() { - let Some(i) = app.session.documents().iter().position(|d| d.uid == w.uid) else { continue }; - let shown = if native { - os_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) - } else { - app_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) - }; + let Some(win) = find(app, (w.uid, w.view)) else { continue }; + let raised = raise == Some((w.uid, w.view)); + let shown = if native { os_window(app, ctx, &w, (win, blocked), raised) } else { app_window(app, ctx, &w, (win, blocked), raised) }; if blocked { continue; } - if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { - // The OS window took the keyboard: its document becomes the current one. - if shown.focused && !win.focused && app.session.active_index() != Some(i) { - activate = Some(i); + let is_current = views::current(app) == Some(win); + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) { + // The OS window took the keyboard: its view becomes the current window. + if shown.focused && !x.focused && !is_current { + activate = Some(win); } - win.focused = shown.focused; - win.body = shown.body; - win.fit = shown.fit; + x.focused = shown.focused; + x.body = shown.body; + x.fit = shown.fit; } over_strip |= shown.over_strip; if shown.close { - close = Some(i); + close = Some(win); } else if shown.dock { - dock = Some(i); - } else if shown.activate && app.session.active_index() != Some(i) { - activate = Some(i); + dock = Some(win); + } else if shown.activate && !is_current { + activate = Some(win); } } // The tab strip a dragged window would go back under shows where it lands. @@ -446,61 +468,61 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { painter.rect_filled(strip, 0.0, t.accent.gamma_multiply(0.12)); painter.rect_stroke(strip, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); } - if let Some(i) = close { + if let Some(win) = close { // The save prompt opens in the main window. - if let Err(e) = crate::unsaved::close(app, i) { + if let Err(e) = close_window(app, win) { app.status(e); } if native && app.ui.dialog.is_some() { ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); } - } else if let Some(i) = dock { - if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i })) { + } else if let Some((i, n)) = dock { + if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i, "view": n })) { app.status(e); } if native { ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); } - } else if let Some(i) = activate { - crate::chrome::show_document(app, i); - app.canvas.windows.current = app.session.active().map(|d| d.uid); + } else if let Some(win) = activate { + show_window(app, win); + app.canvas.windows.current = views::current(app).and_then(|w| key(app, w)); } } -/// Document `i`'s window body in `ui`: the canvas for the current document, else (and while -/// `blocked` by a modal) a pane. The document fits the body again when the body changed size since -/// `fit` and its view has not moved. → whether a press in the pane asks for its document to become -/// the current one, the body's rect and the fit after this frame. -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (i, blocked): (usize, bool), fit: Option) -> (bool, egui::Rect, Option) { +/// Window `win`'s body in `ui`: the canvas for the current window, else (and while `blocked` by a +/// modal) a pane. The view fits the body again when the body changed size since `fit` and the view +/// has not moved. → whether a press in the pane asks for its window to become the current one, the +/// body's rect and the fit after this frame. +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option) -> (bool, egui::Rect, Option) { let t = crate::theme::Tokens::get(ui.ctx()); let rect = ui.available_rect_before_wrap(); ui.painter().rect_filled(rect, 0.0, t.pasteboard); - if let (Some(v), Some((size, zoom, center))) = (app.views.get_mut(i), fit) + if let (Some(v), Some((size, zoom, center))) = (view_mut(app, win), fit) && size != rect.size() && zoom == v.zoom && center == v.center { v.fitted = false; } - let was_fitted = app.views.get(i).is_some_and(|v| v.fitted); - let pressed = if !blocked && app.session.active_index() == Some(i) && !crate::menus::home_showing(app) { + let was_fitted = view(app, win).is_some_and(|v| v.fitted); + let pressed = if !blocked && views::current(app) == Some(win) && !crate::menus::home_showing(app) { crate::canvas::show(app, ui); false } else { - crate::canvas::pane(app, ui, i, rect) + crate::canvas::pane(app, ui, win, rect) }; ui.advance_cursor_after_rect(rect); - let fit = match app.views.get(i) { + let fit = match view(app, win) { Some(v) if v.fitted && !was_fitted => Some((rect.size(), v.zoom, v.center)), _ => fit, }; (pressed, rect, fit) } -/// Document `i`'s window `w` as an OS window of its own, `blocked` by a modal or not; `raise` -/// brings it to the front. The document's tab is at the top of the window, above its body. -fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { - let vid = viewport_id(w.uid); +/// Window `win`'s floating window `w` as an OS window of its own, `blocked` by a modal or not; +/// `raise` brings it to the front. Its tab is at the top of the window, above its body. +fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, blocked): (Win, bool), raise: bool) -> Shown { + let vid = viewport_id(w); let origin = ctx.input(|inp| inp.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO); let screen = match w.screen { Some((pos, generation)) if generation == w.generation => pos, @@ -510,8 +532,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::OuterPosition(pos)); ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::InnerSize(w.place.size())); } - if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { - win.screen = Some((pos, w.generation)); + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) { + x.screen = Some((pos, w.generation)); } pos } @@ -519,7 +541,7 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b if raise { ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Focus); } - let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let title = crate::chrome::document_window_title(app, win).unwrap_or_default(); let builder = egui::ViewportBuilder::default().with_title(title).with_position(screen).with_inner_size(w.place.size()).with_min_inner_size(MIN_SIZE); let mut forwarded = (Vec::new(), None); @@ -532,9 +554,9 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b // or a modal can keep the document open. ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose); } - let tab = crate::chrome::window_tab(app, ui, i); - let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, (w.uid, origin), &tab, strip) }; - let (pressed, rect, fit) = body(app, ui, (i, blocked), w.fit); + let tab = crate::chrome::window_tab(app, ui, win); + let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, ((w.uid, w.view), origin), &tab, strip) }; + let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit); let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started())); // Keys the window's widgets left over run the main window's shortcuts and tool keys, as a // floating panel's do. @@ -559,18 +581,18 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b shown } -/// A drag of document window `uid`'s OS window by the `tab` at its top: the window follows the -/// pointer, and its document goes back under the tabs when the tab is released over the main -/// window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the +/// A drag of floating window `key`'s ([`views::key`]) OS window by the `tab` at its top: the window +/// follows the pointer, and its view goes back under the tabs when the tab is released over the +/// main window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the /// screen. → whether the pointer is over the strip, and whether the tab was released there. fn drag_tab( app: &mut VectorcraftApp, ui: &egui::Ui, - (uid, origin): (u64, egui::Pos2), + ((uid, view), origin): ((u64, u32), egui::Pos2), tab: &egui::Response, strip: Option, ) -> (bool, bool) { - let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid) else { + let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == view) else { return (false, false); }; if !tab.dragged() && !tab.drag_stopped() { @@ -598,14 +620,14 @@ fn drag_tab( (over, false) } -/// Document `i`'s window `w` as a window inside the main window, `blocked` by a modal or not; -/// `raise` brings it to the front. -fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { +/// Window `win`'s floating window `w` as a window inside the main window, `blocked` by a modal or +/// not; `raise` brings it to the front. +fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, blocked): (Win, bool), raise: bool) -> Shown { let id = window_id(w); if raise { ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); } - let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let title = crate::chrome::document_window_title(app, win).unwrap_or_default(); let mut open = true; let (mut activate, mut rect, mut fit) = (false, None, w.fit); let frame = egui::Frame::window(&ctx.global_style()).inner_margin(0.0); @@ -619,7 +641,7 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, .frame(frame) .open(&mut open) .show(ctx, |ui| { - let (pressed, r, f) = body(app, ui, (i, blocked), fit); + let (pressed, r, f) = body(app, ui, (win, blocked), fit); (activate, rect, fit) = (pressed, Some(r), f); }); // A press on its title bar or edges, which brings the window to the front, also makes its diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index f32e0b2ab6..4311d8bbe8 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -257,11 +257,11 @@ fn tile_brings_floating_documents_back_into_the_grid() { app.run("window.arrange.tile", json!({})).unwrap(); app.run("window.arrange.floatInWindow", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); - let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); frame(&mut app, &ctx, vec![]); - let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1, 2]); assert!(app.ui.floating.is_empty()); } @@ -437,7 +437,7 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); app.run("window.arrange.floatInWindow", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); - let vid = viewport_id(app.session.documents()[1].uid); + let vid = viewport_id(&app.ui.floating[0]); host.borrow_mut().close = true; frame(&mut app, &ctx, vec![]); host.borrow_mut().close = false; @@ -725,3 +725,168 @@ fn the_arrange_items_are_enabled_as_the_documents_allow() { app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); assert_eq!(states(&app), [true, true, true, true, false], "consolidated"); } + +/// The title of window `w`'s tab. +fn title_of(app: &VectorcraftApp, w: Win) -> String { + crate::chrome::document_window_title(app, w).unwrap() +} + +#[test] +fn new_window_opens_a_numbered_view_with_its_own_zoom() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let name = app.session.documents()[0].title(); + assert!(!title_of(&app, (0, 1)).contains(&format!("{name}:")), "one view: no number"); + let zoom = app.view().unwrap().zoom; + assert_eq!(app.run("window.newWindow", json!({})).unwrap(), json!({"index": 0, "view": 2})); + assert_eq!(windows(&app), [(0, 1), (0, 2)]); + assert_eq!(current(&app), Some((0, 2)), "the new view is the current window"); + assert_eq!(app.view().unwrap().zoom, zoom, "it opens where the first view is"); + assert!(title_of(&app, (0, 1)).starts_with(&format!("{name}:1 @")), "{}", title_of(&app, (0, 1))); + assert!(title_of(&app, (0, 2)).starts_with(&format!("{name}:2 @")), "{}", title_of(&app, (0, 2))); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(tab_drawn(&shapes, &format!("{name}:1")) && tab_drawn(&shapes, &format!("{name}:2")), "each view has a tab"); + // Each view keeps its own zoom. + app.run("view.zoomIn", json!({})).unwrap(); + let zoomed = app.view().unwrap().zoom; + assert_ne!(zoomed, zoom); + show_window(&mut app, (0, 1)); + assert_eq!(app.view().unwrap().zoom, zoom, "the first view did not zoom"); + assert_eq!(view(&app, (0, 2)).unwrap().zoom, zoomed); + show_window(&mut app, (0, 2)); + assert_eq!(app.view().unwrap().zoom, zoomed); + assert_eq!(app.run("window.newWindow", json!({})).unwrap(), json!({"index": 0, "view": 3})); +} + +#[test] +fn an_edit_in_one_view_shows_in_the_other() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + app.run("window.newWindow", json!({})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.canvas.panes.last.iter().map(|(w, _)| *w).collect::>(), [(0, 1), (0, 2)], "one pane per view"); + view_mut(&mut app, (0, 1)).unwrap().zoom = 0.5; + app.view_mut().unwrap().zoom = 2.0; + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let d = &app.session.documents()[0]; + let shown = app.canvas.panes.shown.get(&(d.uid, 1)).map(|(k, _)| (k.revision, k.zoom)); + assert_eq!(shown, Some((d.revision, 0.5)), "the other view's pane shows the edit at its own zoom"); + assert_eq!(app.view().unwrap().zoom, 2.0, "the view edited in keeps its zoom"); +} + +#[test] +fn closing_a_view_leaves_the_document_open() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + app.run("window.newWindow", json!({})).unwrap(); + app.run("window.newWindow", json!({})).unwrap(); + show_window(&mut app, (0, 2)); + assert_eq!(app.run("file.close", json!({})).unwrap(), json!({"index": 0, "views": 2})); + assert!(app.ui.dialog.is_none(), "closing a view does not ask to save"); + assert_eq!((app.session.documents().len(), windows(&app)), (1, vec![(0, 1), (0, 3)])); + assert_eq!(current(&app), Some((0, 3)), "the next view becomes the current window"); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.run("file.close", json!({})).unwrap(), json!({"index": 0, "views": 1})); + assert_eq!(windows(&app), [(0, 1)], "the view left is the document's only view again"); + let name = app.session.documents()[0].title(); + assert!(!title_of(&app, (0, 1)).contains(&format!("{name}:")), "{}", title_of(&app, (0, 1))); + // The last view: the document closes, asking to save it first. + app.run("file.close", json!({})).unwrap(); + assert!(app.ui.dialog.is_some(), "the changed document asks to be saved"); + assert_eq!(app.session.documents().len(), 1); +} + +#[test] +fn arrange_treats_each_view_as_a_window() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window"); + app.run("window.newWindow", json!({})).unwrap(); + assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document"); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2})); + app.run("window.arrange.cascade", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let uid = app.session.documents()[0].uid; + let floating: Vec<(u64, u32)> = app.ui.floating.iter().map(|w| (w.uid, w.view)).collect(); + assert_eq!(floating, [(uid, 1), (uid, 2)], "each view in a window of its own, in tab order"); + assert_ne!(app.ui.floating[0].place.min, app.ui.floating[1].place.min, "stacked down and to the right"); + assert!(docked_windows(&app).is_empty()); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert!(app.ui.floating.is_empty()); + assert_eq!(docked_windows(&app), [(0, 1), (0, 2)]); + // Float in Window floats the current view only. + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + assert_eq!(app.ui.floating.iter().map(|w| (w.uid, w.view)).collect::>(), [(uid, 2)]); + assert_eq!(docked_windows(&app), [(0, 1)], "the first view keeps its tab"); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + let name = app.session.documents()[0].title(); + assert!(tab_drawn(&shapes, &format!("{name}:1")) && !tab_drawn(&shapes, &format!("{name}:2"))); + // A new view of a floating view floats too. + app.run("window.newWindow", json!({})).unwrap(); + assert!(floats(&app, (0, 3)), "it opens beside the view it came from"); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + assert!(docked_windows(&app).is_empty()); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 0, "view": 3})).unwrap()["floating"], json!([0, 0])); + assert_eq!((docked_windows(&app), current(&app)), (vec![(0, 3)], Some((0, 3)))); +} + +#[test] +fn each_pane_draws_its_own_views_outline_or_preview() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + app.run("window.newWindow", json!({})).unwrap(); + show_window(&mut app, (0, 1)); + app.run("view.outline", json!({})).unwrap(); + show_window(&mut app, (0, 2)); + assert!(!app.outline_view(), "the second view is in Preview"); + app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let uid = app.session.documents()[0].uid; + assert_eq!(app.canvas.panes.shown.get(&(uid, 1)).map(|(k, _)| k.outline), Some(true), "the first view's pane is in Outline"); +} + +#[test] +fn next_and_previous_document_step_through_the_views() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.newWindow", json!({})).unwrap(); + assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 1})); + assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 0, "view": 1})); + assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 0, "view": 2})); + assert_eq!(current(&app), Some((0, 2))); + assert_eq!(app.run("window.previousDocument", json!({})).unwrap(), json!({"index": 0, "view": 1})); + assert_eq!(app.run("window.previousDocument", json!({})).unwrap(), json!({"index": 1})); +} + +#[test] +fn switching_views_resets_the_tool() { + let mut app = app_with(2); + app.run("window.newWindow", json!({})).unwrap(); + let before = app.session.tool_resets(); + show_window(&mut app, (1, 1)); + assert_eq!(app.session.tool_resets(), before + 1, "another view of the current document resets the tool"); + show_window(&mut app, (1, 1)); + assert_eq!(app.session.tool_resets(), before + 1, "the current view stays as it is"); +} + +#[test] +fn switching_views_targets_the_artboard_the_view_shows() { + let mut app = app_with(1); + app.run("artboard.new", json!({})).unwrap(); + app.run("tool.select", json!({"tool": "artboard"})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + app.run("window.newWindow", json!({})).unwrap(); + crate::panels::artboards::select(&mut app, 1); + assert_eq!(app.session.tool_options()["active"], json!(1)); + show_window(&mut app, (0, 1)); + assert_eq!(app.session.tool_options()["active"], json!(0), "the first view shows the first artboard"); + show_window(&mut app, (0, 2)); + assert_eq!(app.session.tool_options()["active"], json!(1)); +} diff --git a/crates/ui-egui/src/doc_windows/views.rs b/crates/ui-egui/src/doc_windows/views.rs new file mode 100644 index 0000000000..dda76952ee --- /dev/null +++ b/crates/ui-egui/src/doc_windows/views.rs @@ -0,0 +1,247 @@ +//! Window › New Window: more views of an open document, each with its own zoom, center, rotation, +//! artboard and Outline or Preview, shown as tabs titled with the view's number ("Name:2"). Tile, +//! Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as +//! they arrange a document. Every view shows the same document, so an edit made in one shows in +//! all of them. Closing a view leaves the document open until its last view closes. +//! +//! A window is a document's index and its view's number ([`Win`]). The view a document shows +//! while it is the current one is in [`VectorcraftApp::views`]; its other views are kept in +//! [`Views`]. + +use std::collections::HashMap; + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::state::View; + +/// A window: an open document's index and its view's number (1 for a document's first view). +pub(crate) type Win = (usize, u32); + +/// A view of an open document other than the one [`VectorcraftApp::views`] holds for it. +#[derive(Clone, Debug)] +struct OtherView { + /// The document ([`vectorcraft_engine::DocState::uid`]). + uid: u64, + /// The view's number. + number: u32, + view: View, +} + +/// The views of the open documents beyond the one each document shows. +#[derive(Default)] +pub struct Views { + others: Vec, + /// By document uid: the number of the view in [`VectorcraftApp::views`] (1 when absent). + shown: HashMap, +} + +fn uid(app: &VectorcraftApp, i: usize) -> Option { + app.session.documents().get(i).map(|d| d.uid) +} + +/// The number of the view of document `i` that [`VectorcraftApp::views`] holds. +pub(crate) fn shown(app: &VectorcraftApp, i: usize) -> u32 { + uid(app, i).and_then(|u| app.canvas.windows.views.shown.get(&u).copied()).unwrap_or(1) +} + +/// The numbers of document `i`'s views, in order; none for a document that is not open. +pub(crate) fn numbers(app: &VectorcraftApp, i: usize) -> Vec { + let Some(u) = uid(app, i) else { return vec![] }; + let mut n: Vec = + std::iter::once(shown(app, i)).chain(app.canvas.windows.views.others.iter().filter(|o| o.uid == u).map(|o| o.number)).collect(); + n.sort_unstable(); + n +} + +/// Every window, by document and then by view number: the tab order. +pub(crate) fn windows(app: &VectorcraftApp) -> Vec { + (0..app.session.documents().len()).flat_map(|i| numbers(app, i).into_iter().map(move |n| (i, n))).collect() +} + +/// The current window: the current document's shown view. +pub(crate) fn current(app: &VectorcraftApp) -> Option { + app.session.active_index().map(|i| (i, shown(app, i))) +} + +/// Window `w`'s key, which stays the same while documents before it close: its document's uid and +/// its view's number. +pub(crate) fn key(app: &VectorcraftApp, (i, n): Win) -> Option<(u64, u32)> { + uid(app, i).map(|u| (u, n)) +} + +/// The window `key` ([`key`]) names, while its document is open. +pub(crate) fn find(app: &VectorcraftApp, (u, n): (u64, u32)) -> Option { + let i = app.session.documents().iter().position(|d| d.uid == u)?; + numbers(app, i).contains(&n).then_some((i, n)) +} + +/// Window `w`'s view. +pub(crate) fn view(app: &VectorcraftApp, (i, n): Win) -> Option<&View> { + if n == shown(app, i) { + return app.views.get(i); + } + let u = uid(app, i)?; + app.canvas.windows.views.others.iter().find(|o| o.uid == u && o.number == n).map(|o| &o.view) +} + +/// Window `w`'s view, to change. +pub(crate) fn view_mut(app: &mut VectorcraftApp, (i, n): Win) -> Option<&mut View> { + if n == shown(app, i) { + return app.views.get_mut(i); + } + let u = uid(app, i)?; + app.canvas.windows.views.others.iter_mut().find(|o| o.uid == u && o.number == n).map(|o| &mut o.view) +} + +/// Unfit every window's view: each fits where it shows next. +pub(crate) fn unfit_all(app: &mut VectorcraftApp) { + for v in &mut app.views { + v.fitted = false; + } + for o in &mut app.canvas.windows.views.others { + o.view.fitted = false; + } +} + +/// The number a window's title shows: its view's while its document has more than one view. +pub(crate) fn label(app: &VectorcraftApp, (i, n): Win) -> Option { + (numbers(app, i).len() > 1).then_some(n) +} + +/// Make view `n` the one [`VectorcraftApp::views`] holds for document `i`. False when the document +/// has no such view. While document `i` is the current one, the tool is reset first, as a switch to +/// another document resets it, and with the Artboard tool the artboard the view shows becomes the +/// tool's target. +fn bring(app: &mut VectorcraftApp, (i, n): Win) -> bool { + let old = shown(app, i); + if n == old { + return app.views.get(i).is_some(); + } + let Some(u) = uid(app, i) else { return false }; + if app.views.get(i).is_none() || !app.canvas.windows.views.others.iter().any(|o| o.uid == u && o.number == n) { + return false; + } + if app.session.active_index() == Some(i) { + app.session.reset_tool(); + } + let views = &mut app.canvas.windows.views; + let (Some(other), Some(shown)) = (views.others.iter_mut().find(|o| o.uid == u && o.number == n), app.views.get_mut(i)) else { + return false; + }; + std::mem::swap(shown, &mut other.view); + other.number = old; + views.shown.insert(u, n); + if app.session.active_index() == Some(i) + && app.session.tool_id() == "artboard" + && let Some(count) = app.session.active().map(|d| d.doc.artboards.len()) + { + let board = crate::panels::artboards::selected(app, count); + crate::panels::artboards::select(app, board); + } + true +} + +/// Make window `w` the current one, as a click on its tab does. +pub(crate) fn show_window(app: &mut VectorcraftApp, w: Win) { + bring(app, w); + crate::chrome::show_document(app, w.0); +} + +/// Forget the views of documents that have closed, and keep each other view on an artboard its +/// document has. Called by [`VectorcraftApp::sync_views`]. +pub(crate) fn retain(app: &mut VectorcraftApp) { + let views = &mut app.canvas.windows.views; + if views.others.is_empty() && views.shown.is_empty() { + return; + } + let docs = app.session.documents(); + views.shown.retain(|u, _| docs.iter().any(|d| d.uid == *u)); + views.others.retain_mut(|o| match docs.iter().find(|d| d.uid == o.uid) { + Some(d) => { + o.view.artboard = o.view.artboard.min(d.doc.artboards.len().saturating_sub(1)); + true + } + None => false, + }); +} + +/// `window.newWindow`: another view of the current document, numbered after its others, which +/// starts where the current view is and becomes the current window. It opens as a tab, or in a +/// floating window of its own when the current view is in one. Returns `{index, view}`. +pub(crate) fn new_window(app: &mut VectorcraftApp) -> Result { + app.sync_views(); + let Some((i, n)) = current(app) else { return Err("no document open".into()) }; + let (Some(u), Some(view)) = (uid(app, i), app.views.get(i).copied()) else { return Err("no document open".into()) }; + let number = numbers(app, i).last().copied().unwrap_or(n) + 1; + let floats = super::floats(app, (i, n)); + app.canvas.windows.views.others.push(OtherView { uid: u, number, view }); + show_window(app, (i, number)); + if floats { + super::place(app, &[(i, number)]); + } + Ok(json!({ "index": i, "view": number })) +} + +/// Close window `w`: its view goes, and its document stays open with its other views. A +/// document's last view closes the document, asking to save it first when it has changed +/// ([`crate::unsaved::close`]). When one view is left, it is numbered 1 again. Nothing closes while +/// a file dialog's sheet is on the window. +pub(crate) fn close_window(app: &mut VectorcraftApp, (i, n): Win) -> Result { + let nums = numbers(app, i); + if nums.len() <= 1 { + return crate::unsaved::close(app, i); + } + crate::unsaved::refuse_while_picking(app)?; + let Some(u) = uid(app, i) else { return Err("no such document".into()) }; + if !nums.contains(&n) { + return Err("no such document".into()); + } + let was_current = current(app) == Some((i, n)); + // The document's next view in the tab strip takes the closing one's place. + let next = nums.iter().copied().find(|m| *m > n).or(nums.iter().copied().rfind(|m| *m != n)); + if n == shown(app, i) + && let Some(next) = next + { + bring(app, (i, next)); + } + app.canvas.windows.views.others.retain(|o| !(o.uid == u && o.number == n)); + app.ui.floating.retain(|w| !(w.uid == u && w.view == n)); + if app.ui.tab_document == Some((u, n)) { + app.ui.tab_document = None; + } + let left = numbers(app, i); + if let [only] = left[..] { + app.canvas.windows.views.shown.remove(&u); + for w in app.ui.floating.iter_mut().filter(|w| w.uid == u && w.view == only) { + w.view = 1; + } + if app.ui.tab_document == Some((u, only)) { + app.ui.tab_document = Some((u, 1)); + } + } + if was_current { + crate::chrome::show_document(app, i); + } + Ok(json!({ "index": i, "views": left.len() })) +} + +/// `file.close` without an `index`: the current window closes ([`close_window`]). +pub(crate) fn close_current(app: &mut VectorcraftApp) -> Result { + let Some(w) = current(app) else { return Err("no document open".into()) }; + close_window(app, w) +} + +/// `params`' `index` and `view`: the window they name, `Ok(None)` without an `index`. Without a +/// `view`, the document's shown view. +pub(crate) fn window_param(app: &VectorcraftApp, p: &Value) -> Result, String> { + let i = match p.get("index") { + None | Some(Value::Null) => return Ok(None), + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < app.session.documents().len()).ok_or("no such document")?, + }; + let n = match p.get("view") { + None | Some(Value::Null) => shown(app, i), + Some(v) => v.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| numbers(app, i).contains(n)).ok_or("no such document")?, + }; + Ok(Some((i, n))) +} diff --git a/crates/ui-egui/src/document_drag.rs b/crates/ui-egui/src/document_drag.rs index 72ea5a3c1f..e85e95ae78 100644 --- a/crates/ui-egui/src/document_drag.rs +++ b/crates/ui-egui/src/document_drag.rs @@ -26,6 +26,8 @@ struct Artwork { #[derive(Clone)] struct Hover { uid: u64, + /// The hovered tab's view of its document (Window › New Window). + view: u32, since: f64, } @@ -91,14 +93,16 @@ pub(crate) fn cleanup(app: &VectorcraftApp, ctx: &Context) { } } -/// Hover uses `contains_pointer`: the source canvas still owns egui's dragged widget. -pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize, close: egui::Rect) -> bool { +/// Hover uses `contains_pointer`: the source canvas still owns egui's dragged widget. The tab is +/// window `win`'s: another view of the current document's is a tab to switch to as well. +pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, win: crate::doc_windows::Win, close: egui::Rect) -> bool { let ctx = &resp.ctx; + let (index, view) = win; let eligible = resp.contains_pointer() && ctx .input(|i| i.pointer.primary_down() && !i.key_pressed(egui::Key::Escape) && i.pointer.interact_pos().is_some_and(|p| !close.contains(p))) && app.ui.dialog.is_none(); - if !eligible || app.session.active_index() == Some(index) || ctx.data(|d| d.get_temp::(activated_at_id()).is_some()) { + if !eligible || crate::doc_windows::current(app) == Some(win) || ctx.data(|d| d.get_temp::(activated_at_id()).is_some()) { return false; } let transfer = egui::DragAndDrop::has_payload_of_type::(ctx); @@ -110,7 +114,7 @@ pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize, return false; }; let now = ctx.input(|i| i.time); - let hover = ctx.data(|d| d.get_temp::(hover_id())).filter(|h| h.uid == uid).unwrap_or(Hover { uid, since: now }); + let hover = ctx.data(|d| d.get_temp::(hover_id())).filter(|h| h.uid == uid && h.view == view).unwrap_or(Hover { uid, view, since: now }); ctx.data_mut(|d| d.insert_temp(hover_id(), hover.clone())); let remaining = HOVER_SECONDS - (now - hover.since); if remaining > 0.0 { @@ -147,7 +151,7 @@ pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize, egui::DragAndDrop::set_payload(ctx, art); } app.ui.home = None; - app.session.set_active(index); + crate::doc_windows::show_window(app, win); ctx.request_repaint(); let at = ctx.input(|i| i.pointer.interact_pos()); ctx.data_mut(|d| { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5661450266..5f3969546f 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -544,7 +544,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("brightness must be dark|mediumDark|mediumLight|light".into()), }, - "window.newWindow" => Err("New Window isn't available yet: a document opens in one window".into()), + "window.newWindow" => crate::doc_windows::new_window(app), "window.arrange.cascade" => crate::doc_windows::cascade(app), "window.arrange.tile" => crate::canvas::tile(app), "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), @@ -609,10 +609,15 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { - let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).or(app.session.active_index())?; - crate::unsaved::close(app, i) - } + // Without an `index`, the current window closes: one of several views of a document closes + // without closing the document (Window › New Window). + "file.close" => match p.get("index").and_then(Value::as_u64).map(|i| i as usize) { + Some(i) => crate::unsaved::close(app, i), + None => { + app.session.active_index()?; + crate::doc_windows::close_current(app) + } + }, "file.closeAll" => crate::unsaved::close_all(app, "closeAll"), "app.quit" => crate::unsaved::close_all(app, "quit"), "ui.swatchOptions" => match s("name") { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 523d930e0d..2dd1051b12 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -283,17 +283,16 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { app.session.active().is_some() && crate::dialogs::perspective_presets::slot_preset(app, id).is_some() } "ui.perspectivePlane" => app.session.active().is_some(), - // Only one window per document so far: grayed out (#3724). - "window.newWindow" => false, - // Tile and Cascade with two documents or more; Float in Window for a current document under - // the tabs; Float All in Windows while a document is under the tabs; Consolidate All - // Windows while documents are tiled or floating. - "window.arrange.tile" | "window.arrange.cascade" => app.session.documents().len() > 1, - "window.arrange.floatInWindow" => app.session.active_index().is_some_and(|i| !crate::doc_windows::is_floating(app, i)), - "window.arrange.floatAllInWindows" => !crate::doc_windows::docked(app).is_empty(), + "window.newWindow" => app.session.active().is_some(), + // Tile and Cascade with two windows or more (documents, or views of one from New Window); + // Float in Window for a current window under the tabs; Float All in Windows while a window + // is under the tabs; Consolidate All Windows while windows are tiled or floating. + "window.arrange.tile" | "window.arrange.cascade" => crate::doc_windows::windows(app).len() > 1, + "window.arrange.floatInWindow" => crate::doc_windows::current(app).is_some_and(|w| !crate::doc_windows::floats(app, w)), + "window.arrange.floatAllInWindows" => !crate::doc_windows::docked_windows(app).is_empty(), "window.arrange.consolidateAllWindows" => { - let n = app.session.documents().len(); - n > 0 && (app.ui.tiled || crate::doc_windows::docked(app).len() < n) + let n = crate::doc_windows::windows(app).len(); + n > 0 && (app.ui.tiled || crate::doc_windows::docked_windows(app).len() < n) } "window.nextDocument" | "window.previousDocument" => !app.session.documents().is_empty(), _ => true, diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 4b46453ca7..3918b9fb1c 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -912,15 +912,17 @@ fn unlock_all_and_show_all_clicked_with_shift_alt_act_within_the_group() { } } -/// #3724: Window › New Window is greyed out until VectorCraft can open a second window on a -/// document, instead of being enabled and answering with an internal milestone note. +/// #4116: Window › New Window is enabled with a document open and opens a second view of it; with +/// no document open it is greyed out. #[test] -fn new_window_is_disabled_until_it_opens_a_window() { +fn new_window_opens_a_view_of_the_current_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(!enabled(&app, "window.newWindow"), "no document to open a window on"); + assert_eq!(app.run("window.newWindow", json!({})).unwrap_err(), "no document open"); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - assert!(!enabled(&app, "window.newWindow"), "New Window is enabled but opens no window"); - let e = app.run("window.newWindow", json!({})).unwrap_err(); - assert!(!e.contains("M11.5"), "a user-facing message, not a milestone: {e}"); + assert!(enabled(&app, "window.newWindow")); + assert_eq!(app.run("window.newWindow", json!({})).unwrap(), json!({"index": 0, "view": 2})); + assert_eq!(app.session.documents().len(), 1, "the same document, in a second window"); } /// #4143: Window menu panels and panel submenus are listed in alphabetical order according to the diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 9e887870a1..31b263d3b4 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -580,7 +580,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("window.workspace.delete", "Delete Workspace", "", "{name}"), ("window.workspace.rename", "Rename Workspace", "", "{name, to}"), ("window.workspace.list", "List Workspaces", "", "{}"), - ("window.newWindow", "New Window", "", "{}"), + ( + "window.newWindow", + "New Window", + "", + "{} open another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own (titled with the view's number, \"Name:2\") or, when the current view floats, in a floating window; it becomes the current window; the Arrange commands treat each view as a window; file.close closes the current view and the last view closes the document; returns {index, view}", + ), ( "window.arrange.cascade", "Cascade", @@ -591,13 +596,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; documents in floating windows come back under the tabs first; with fewer than two documents open the view stays as it is; returns {tiled, panes}", + "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", ), ( "window.arrange.floatInWindow", "Float in Window", "", - "{index?, at?: [x, y]} move the current document, or document `index` (which becomes the current one), out of the tab strip into a floating window of its own, fitted to it, with the window's top-left corner at `at` (main window points) or else at the next place of a cascade; dragging a document tab more than 24 pt above or below the tab strip does this at the pointer; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", + "{index?, view?, at?: [x, y]} move the current window, or document `index`'s view `view` (its current view without one; it becomes the current window), out of the tab strip into a floating window of its own, fitted to it, with the window's top-left corner at `at` (main window points) or else at the next place of a cascade; dragging a document tab more than 24 pt above or below the tab strip does this at the pointer; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", ), ( "window.arrange.floatAllInWindows", @@ -609,19 +614,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.consolidateAllWindows", "Consolidate All Windows", "", - "{index?} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}; with `index`, only document `index` goes back under its tab and becomes the current one, the other windows and Tile staying as they are, as when a document window is dragged by its title bar (an OS window by the tab at its top) onto the tab strip; returns {tiled, floating} (document indices)", + "{index?, view?} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}; with `index`, only document `index` (its view `view`, else its current view) goes back under its tab and becomes the current one, the other windows and Tile staying as they are, as when a document window is dragged by its title bar (an OS window by the tab at its top) onto the tab strip; returns {tiled, floating} (document indices)", ), ( "window.nextDocument", "Next Document", "Cmd+F6", - "{} make the open document after the current one in tab order the current one, as a click on its tab does (after the last document it goes to the first, and from the Home screen to the first); returns {index}", + "{} make the open document after the current one in tab order the current one, as a click on its tab does (after the last document it goes to the first, and from the Home screen to the first); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ( "window.previousDocument", "Previous Document", "Cmd+Shift+F6", - "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); returns {index}", + "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools)"), ( diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4fc10697f6..294b5bb4d2 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -468,10 +468,10 @@ pub struct UiState { /// saved, as `tiled` is not. #[serde(skip)] pub floating: Vec, - /// The document (its uid) the tab strip shows while the current document is in a floating - /// window: the tabbed document that was current last. + /// The window (its document's uid and its view's number) the tab strip shows while the current + /// window is a floating one: the tabbed window that was current last. #[serde(skip)] - pub tab_document: Option, + pub tab_document: Option<(u64, u32)>, /// Draw Normal / Behind / Inside. pub draw_mode: u8, pub about: bool, diff --git a/crates/ui-egui/src/tests/document_drag.rs b/crates/ui-egui/src/tests/document_drag.rs index 7001e13be9..b5727eaada 100644 --- a/crates/ui-egui/src/tests/document_drag.rs +++ b/crates/ui-egui/src/tests/document_drag.rs @@ -361,3 +361,38 @@ fn scrolling_tabs_under_a_stationary_drag_does_not_cascade_to_other_documents() frame(&mut app, &ctx, 2.3, vec![button(drop, false)]); assert_eq!(app.session.active().unwrap().selection.objects.len(), 1); } + +/// Artwork held over the tab of another view of its own document (Window › New Window) switches to +/// that view, and a drop there moves it. +#[test] +fn dragging_artwork_over_another_views_tab_switches_to_that_view() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "name": "Logo"})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("window.newWindow", json!({})).unwrap(); + crate::doc_windows::show_window(&mut app, (0, 1)); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![]); + let tabs = frame(&mut app, &ctx, 0.01, vec![]); + assert_eq!(tabs.len(), 2); + let grab = canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(100.0, 100.0)); + frame(&mut app, &ctx, 0.05, vec![Event::PointerMoved(grab), button(grab, true)]); + frame(&mut app, &ctx, 0.1, vec![Event::PointerMoved(grab + egui::vec2(20.0, 10.0))]); + assert!(app.session.in_interaction()); + frame(&mut app, &ctx, 0.2, vec![Event::PointerMoved(tabs[1].center())]); + frame(&mut app, &ctx, 0.25, vec![]); + frame(&mut app, &ctx, 0.8, vec![]); + assert_eq!(crate::doc_windows::current(&app), Some((0, 2)), "holding the artwork over the other view's tab shows that view"); + assert!(!app.session.tool_busy(), "the switch resets the Selection tool before the drop"); + let drop = canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(200.0, 150.0)); + frame(&mut app, &ctx, 0.9, vec![Event::PointerMoved(drop)]); + frame(&mut app, &ctx, 1.0, vec![button(drop, false)]); + let st = app.session.active().unwrap(); + let moved = st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + assert!((moved.center().x - 200.0).abs() < 0.01 && (moved.center().y - 150.0).abs() < 0.01, "{moved:?}"); + assert!(!app.session.tool_busy(), "the move leaves the Selection tool idle"); +} diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 574bb07b51..65e7f57624 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -640,6 +640,21 @@ fn nothing_closes_or_quits_while_a_sheet_is_open() { assert_eq!(app.ui.status, "quit"); } +/// A view Window › New Window opened does not close while a dialog's sheet is on the window either. +#[test] +fn no_view_closes_while_a_sheet_is_open() { + let (mut app, shown, _) = app(); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.run("window.newWindow", json!({})).unwrap(); + assert!(app.run("file.open", json!({})).is_err()); + assert_eq!(app.run("file.close", json!({})), Err(picks::busy().to_string())); + assert_eq!(crate::doc_windows::windows(&app), [(0, 1), (0, 2)]); + shown.answer(&[]); + poll(&mut app); + app.run("file.close", json!({})).unwrap(); + assert_eq!(crate::doc_windows::windows(&app), [(0, 1)]); +} + /// On Linux the dialog is a window of its own, not a sheet: Close and Quit go on while it is open, /// and its answer for the document closed meanwhile is dropped, nothing written. #[test] diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs index 4518dcb7fb..01eafaed9f 100644 --- a/crates/ui-egui/src/unsaved.rs +++ b/crates/ui-egui/src/unsaved.rs @@ -19,7 +19,7 @@ pub const KIND: &str = "saveChanges"; /// Nothing closes while a file dialog's sheet is on the window (macOS): what asked for it runs /// again when it answers. (Elsewhere the dialog is a window of its own, and closing goes on.) -fn refuse_while_picking(app: &VectorcraftApp) -> Result<(), String> { +pub(crate) fn refuse_while_picking(app: &VectorcraftApp) -> Result<(), String> { if app.file_sheet_open() { Err(crate::picks::busy().into()) } else { Ok(()) } } diff --git a/docs/gaps.md b/docs/gaps.md index 53b3e97f87..3edba26df1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -608,7 +608,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. - **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. - **Done:** a document tab dragged off the tab strip floats its document in a window under the pointer, and a document window dragged by its title bar (an OS window by the tab at its top) onto the tab strip goes back under the tabs. Estimate unchanged. -- **Missing:** several windows of one document (Window › New Window). +- **Done (#4116):** Window › New Window (`window.newWindow`) opens another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab titled with the view's number ("Name:2"); Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document. Closing a view leaves the document open until its last view closes. Estimate unchanged. - **Estimate:** 15–25 h. ## G6 Automation and scripting diff --git a/docs/mcp.md b/docs/mcp.md index 2f750cbdd5..688d57ffc5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3692,6 +3692,17 @@ it returns `{tiled, floating}`. An `index` that names no open document fails wit is not saved. `ui.inspect` reports `tiled`, `panes` (each pane's `document` index, `rect` and whether it is `active`) and `floating`; canvas coordinates map to the current document's pane or window (`canvasRect`), in that window's coordinates while it floats. +`window.newWindow` (Window › New Window) opens another view of the current document, with its own zoom, center, +rotation, artboard and Outline or Preview, makes it the current window and returns `{index, view}`, the view's number. +Each view has a tab of its own; while a document has more than one view, its tabs and windows show the view's number +after the name ("Name:2"). It opens in a floating window when the view it came from is in one. With no document open +it fails with "no document open". The Arrange commands treat each view as a window: `floatInWindow` and +`consolidateAllWindows` take `view` beside `index` (the document's current view without it), and Tile and Cascade +count views. `file.close` without an `index` closes the current view, and the document's last view closes the document; +with an `index` it closes the document and all its views. `window.nextDocument` and `window.previousDocument` step +through the views in tab order and add `view` to their reply for a document with more than one view. `ui.inspect` +reports `windows` (every window as `[document index, view number]`, in tab order), `currentWindow` and each pane's +`view`. Views are not saved. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 20dae8ba93..104d8b27f3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -543,6 +543,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html): "When you create or open documents, they are arranged in tabs in a single document window"). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "You can open multiple windows of a single document at the same time."), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From e3a6ec68fa84db7347685c6fb8691e61bc1c2e52 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:39:41 -0800 Subject: [PATCH 45/50] Docs: describe the New Window source in our own words The New Window line in docs/target-app-parity.md quoted the help page word for word. It now describes what the page says and keeps the link. --- 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 104d8b27f3..fc40894eac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -543,7 +543,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html): "When you create or open documents, they are arranged in tabs in a single document window"). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. -- **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "You can open multiple windows of a single document at the same time."), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 7fe42986c2c15f395c3cd809cedac2592f415974 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 17:17:43 -0800 Subject: [PATCH 46/50] Select: the font Same commands take their reference from type that can be selected Select > Same > Font Family, Font Family & Style, Font Family, Style & Size, Font Size and the text fill and stroke color commands took the type to match from the first type found among the selected objects. Type that is hidden or locked inside a selected group, type on a template layer and type outside the isolated group could set the reference. They now take it from the type that Link Block Series starts from, in the same selection order. A selection whose only type cannot be selected returns "select a text object". --- crates/engine/src/cmd/docmenu.rs | 17 ++++------- crates/engine/src/tests/menucmds.rs | 47 +++++++++++++++++++++++++++++ docs/mcp.md | 6 ++++ docs/target-app-parity.md | 1 + 4 files changed, 60 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 58d5daf17a..413e8c401a 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -304,21 +304,16 @@ fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result Option { let st = s.active()?; let mut out = None; - for id in &st.selection.objects { - st.doc.node(*id)?.walk(&mut |n| { - if out.is_none() - && let NodeKind::Text(t) = &n.kind - { - out = Some(t.first_style()); - } - }); - if out.is_some() { - break; + each_selected_text(s, |id| { + if let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) { + out = Some(t.first_style()); } - } + out.is_none() + }); out } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 0c351dba7d..18ffe69cb9 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1948,6 +1948,53 @@ fn select_same_font_size_and_fill() { assert!(s.execute("select.same.fontSize", &json!({})).is_err()); } +/// The font Same commands take their reference from the first selected type that can be selected: +/// type that is hidden or locked inside a selected group, on a template layer, or outside the +/// isolated group is passed over. +#[test] +fn select_same_font_skips_type_that_cannot_be_selected() { + let mut s = session(); + let typed = + |s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap()); + let hid = typed(&mut s, 20.0, "Arial"); + let courier = typed(&mut s, 60.0, "Courier"); + let arial = typed(&mut s, 100.0, "Arial"); + let other_courier = typed(&mut s, 140.0, "Courier"); + sel(&mut s, &[hid, courier]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let on_template = typed(&mut s, 180.0, "Courier"); + s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap(); + // Hidden or locked type inside the selected group is not the reference. + for (on, off) in [ + (json!({"id": hid.0, "visible": false}), json!({"id": hid.0, "visible": true})), + (json!({"id": hid.0, "locked": true}), json!({"id": hid.0, "locked": false})), + ] { + s.execute("layer.setProps", &on).unwrap(); + sel(&mut s, &[g]); + assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2, "{on}"); + assert_eq!(selected(&s), vec![courier, other_courier], "{on}"); + s.execute("layer.setProps", &off).unwrap(); + } + // Type on a template layer, selected by id, is not the reference. + sel(&mut s, &[on_template, arial]); + s.execute("select.same.fontFamily", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![hid, arial]); + // Type outside the isolated group is not the reference. + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[arial, courier]); + s.execute("select.same.fontFamily", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![courier]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A selection whose only type cannot be selected has no reference. + for id in [hid, courier] { + s.execute("layer.setProps", &json!({"id": id.0, "visible": false})).unwrap(); + } + sel(&mut s, &[g]); + assert!(s.execute("select.same.fontFamily", &json!({})).is_err()); + assert_eq!(selected(&s), vec![g]); +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match diff --git a/docs/mcp.md b/docs/mcp.md index 688d57ffc5..fd739b4064 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1445,6 +1445,12 @@ several runs, one run has to match both: type with the fill in one run and the s and stroke of other objects are not compared. Without type among the selected objects it returns the error "select a text object", and it records no undo step. +The font and text color commands (`select.same.fontFamily`, `fontFamilyStyle`, `fontFamilyStyleSize`, `fontSize`, +`textFillColor`, `textStrokeColor` and `textFillAndStrokeColor`) take the first character of the first type among the +selected objects and the objects inside them, in selection order, as the one to match. Type that is hidden or locked, +inside a hidden or locked group or layer, on a template layer, or outside the isolated group is passed over. When the +selection holds no other type, they return the error "select a text object". + ## Shaper Groups `shaper.releaseSource {source, group?}` takes the original shape `source` out of its Shaper Group: the shape becomes a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fc40894eac..d813ec507b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -922,6 +922,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type › Create Outlines, Object › Expand and Object › Expand Appearance on a frame of threaded text take it out of the thread with the text it shows, which the outlines draw, and the other frames keep the text they hold. When the last frame is outlined, the text it has no room for goes after the text of the last frame that stays. When Expand Appearance keeps the frame as type in a group with its shadow, outer glow or Crop Marks, the type stays in the thread. The public help on threads ([Create text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html), [Remove or break text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/remove-or-break-text-threads-between-objects.html)) does not describe outlining a threaded frame; this handling is VectorCraft's own behavior. Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. + The Select › Same font and text color commands take the type to match from the selected type that can be selected: type that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. From 8cf4b90a653e8542fa04ff59f508e095a7a16115 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 17:20:45 -0800 Subject: [PATCH 47/50] Contextual Task Bar: type on a path offers Type on a Path Options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The task bar offered no Type on a Path item for a selected type on a path: of the type actions, it showed only Create Outlines. It now also offers Type on a Path Options, which opens the same dialog as Type › Type on a Path › Type on a Path Options, with the selected type's effect, alignment and spacing filled in. Point and area type keep their Convert To Area Type and Convert To Point Type buttons. --- crates/ui-egui/src/canvas/task_bar.rs | 9 +++++---- crates/ui-egui/src/tests/taskbar.rs | 23 +++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 73a6334866..e6579d8f31 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -117,8 +117,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { items.push((tl!("Smooth"), "dc-anchor-smooth", TASK_BAR_TO_SMOOTH, none())); } // As in the reference app, open paths offer Join and Edit Path, compound paths and clipping - // masks their Release, images selected with vector art Make Clipping Mask, and type converts - // between point and area type (). + // masks their Release, images selected with vector art Make Clipping Mask, type converts + // between point and area type, and type on a path offers its options (). if n > 1 { items.push((tl!("Group"), "group", "object.group", none())); if mixed { @@ -144,11 +144,12 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { items.push((tl!("Release Compound Path"), "ungroup", "object.compoundPath.release", none())); } else if let Some(kind) = text { items.push((tl!("Create Outlines"), "type", "type.createOutlines", none())); - // Point type converts to area type and back; type on a path doesn't. + // Point type converts to area type and back. The overview above gives type on a path an item to add + // an effect and rearrange the text; here it opens Type on a Path Options. match kind { TextKind::Area { .. } => items.push((tl!("Convert To Point Type"), "type", "type.convertToPointType", none())), TextKind::Point => items.push((tl!("Convert To Area Type"), "dc-type-area", "type.convertToAreaType", none())), - TextKind::OnPath { .. } => {} + TextKind::OnPath { .. } => items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())), } } else if is_image { // Offset Path and Simplify don't apply to an image. diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 7a6bd26168..a1374bd373 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1,7 +1,7 @@ //! The Contextual Task Bar's actions for each kind of selection: open paths offer Join and Edit //! Path, compound paths and clipping masks their Release, images selected with vector art Make -//! Clipping Mask, type converts between point and area type, and a basic shape shows its -//! properties in place of Lock. +//! Clipping Mask, type converts between point and area type, type on a path opens its options, and +//! a basic shape shows its properties in place of Lock. use egui::{Event, PointerButton, Pos2, Rect, vec2}; use serde_json::json; @@ -165,6 +165,25 @@ fn type_converts_between_point_and_area_type() { assert!(matches!(text_kind(&app), TextKind::Point)); } +#[test] +fn type_on_a_path_offers_its_options() { + let mut app = app(); + let path = id(app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Along", "at": [200, 160]})).unwrap()); + assert!(matches!(kind(&app, t), NodeKind::Text(ref t) if matches!(t.kind, TextKind::OnPath { .. }))); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + select(&mut app, &[t]); + // A non-default effect, so the dialog shows the selected type's options rather than defaults. + app.run("type.pathOptions", json!({"effect": "skew"})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Create Outlines") && has(&texts, "Type on a Path Options"), "{texts:?}"); + assert!(!has(&texts, "Convert To Area Type") && !has(&texts, "Convert To Point Type"), "{texts:?}"); + click(&mut app, "Type on a Path Options"); + let d = app.ui.dialog.as_ref().expect("the options dialog opens"); + assert_eq!(d.str("__command"), "type.pathOptions"); + assert_eq!(d.fields.get("effect"), Some(&json!("skew"))); +} + /// The path's anchors (its first subpath). fn anchors(app: &VectorcraftApp, id: u64) -> Vec { match kind(app, id) { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d813ec507b..6bb9818b09 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -607,7 +607,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, and point or area type Convert To Area Type or Convert To Point Type beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. + - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). From 5e495cf9009d06e57e42f1621fe294c0922165d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 23:52:30 -0700 Subject: [PATCH 48/50] .ai import: objects that draw differently from the page come in as its art, and the layers stay When the layers fail the comparison with the file's own page because some objects draw differently (an object in another color, or one that only one side draws), the import finds each top-level object whose bounds hold a patch of such pixels (the smallest one that holds it) and replaces it with the page's art in its bounds, in the same way as an unread object. It then compares the layers with the page again. When that comparison passes, the layers stay, and a warning names the layer or sublayer of each replaced object (`` for one without a name) and how many were replaced on it. Like the warning for unread objects, this warning counts as a loss, so an export or Save As to the file's own path needs `acknowledgeLoss: true`. A replaced wrap object keeps its wrap options, and area type is wrapped again around the page's art. Placed files at their other placement are tried too when the first placement can't be kept. The file still comes in as its PDF part, with the same reason, when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects (or more than 64) hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays would be copied into a replacement, when the page's art can't replace an object for the reasons it can't replace an unread one, when matching the differences to the objects would take too much work, or when the second comparison still fails. Trusting the editing data keeps the objects as read. --- .../engine/src/cmd/fileio/tests_aiimport.rs | 39 ++++ crates/eps/src/import/native/build.rs | 155 ++++++++++++- crates/eps/src/import/native/compare.rs | 82 ++++++- crates/eps/src/import/native/slots.rs | 8 +- crates/eps/src/import/tests_native.rs | 209 ++++++++++++++++++ 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/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/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/file-format-parity.md | 2 +- 32 files changed, 505 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 50d09b0256..e0f6600d95 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -127,6 +127,45 @@ fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() { assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}"); } +#[test] +fn a_differing_object_keeps_the_layers_with_a_note() { + let square = |cmyk: &str, x: f64| format!("{cmyk} k\n{}f\n", ai::rect(x, 40.0, x + 16.0, 56.0)); + let front = square("0 0 0 1", 90.0) + &square("0 0 1 0", 160.0); + let data = ai::editing_data(200.0, 100.0, &(ai::layer("Back", &square("0 0 1 0", 20.0)) + &ai::layer("Front", &front))); + let page = "0 0 1 0 k 20 40 16 16 re f 1 0 0 0 k 90 40 16 16 re f 0 0 1 0 k 160 40 16 16 re f"; + let mut session = Session::new(); + let result = open(&mut session, "differs.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + let doc = &session.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Back", "Front"], "{result}"); + let front = doc.layers[1].children().unwrap(); + assert!(matches!(front[0].kind, NodeKind::Group { .. }) && matches!(front[1].kind, NodeKind::Path { .. }), "{result}"); + let replacement = &front[0].children().unwrap()[0]; + assert!( + matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))), + "{result}" + ); + assert!( + result["warnings"].to_string().contains("objects that drew differently from the file's own page came in as its art: Front (1)"), + "{result}" + ); + // An export to the file's own path is refused unless it is given `acknowledgeLoss`. + let d = std::env::temp_dir().join(format!("vc-aidiffers-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let path = d.join("differs.ai"); + let file = ai::ai(&compressed(data.as_bytes()), page); + std::fs::write(&path, &file).unwrap(); + let path = path.to_string_lossy().to_string(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("left things out") && e.contains("objects that drew differently"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), file); + s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap(); + assert_ne!(std::fs::read(&path).unwrap(), file); + std::fs::remove_dir_all(d).ok(); +} + /// A palette of three swatches and a color group `Inks` holding a fourth. const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\ 0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n"; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index f73121f235..07e88e540b 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,8 +1,8 @@ -use super::compare::{MAX_DIFFERENCE, PageView, compare, difference}; +use super::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, difference}; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, - fill_slots, letters, text_objects, words, + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, + extent, few, fill_slots, letters, text_objects, words, }; use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; @@ -341,10 +341,22 @@ pub(super) fn build_from( doc = other; notes.extend(unseen_note(unseen).into_iter().chain(note)); } - _ => { - let more = drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow)?; - notes.extend(more); - } + other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow) { + Ok(more) => notes.extend(more), + // The objects that draw differently from the page come in as its art, from + // the placement that draws closer to it. + Err(why) => { + let other = other.map(|(_, other, unseen)| (other, unseen)); + let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow); + let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| { + keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n)) + }) else { + return Err(why); + }; + doc = kept; + notes.extend(unseen_note(unseen).into_iter().chain(kept_notes)); + } + }, }, } } @@ -766,6 +778,135 @@ fn replace_unread( Ok(counts.into_iter().map(|(kind, count)| format!("{kind} ({count})")).collect()) } +/// Most objects of the layers that come in as the page's art where they draw differently from it. +const MAX_DIFFERING: usize = 64; + +/// Most pairs of a patch where the layers and the page differ and a top-level object that may hold +/// it, weighed to find the objects that come in as the page's art. +const MAX_PATCH_PAIRS: usize = 4_000_000; + +/// The layers as read and at the placed files' other placement (each with its count of text +/// objects the page doesn't draw), the one that draws closer to the page first. `reflow` as in +/// [`PageView::difference`]. +fn closer_first( + frame: &Frame<'_>, + view: &mut PageView, + doc: (Document, usize), + other: Option<(Document, usize)>, + reflow: bool, +) -> Vec<(Document, usize)> { + match other { + Some(other) if view.difference(&other.0, frame.rect, reflow).any < view.difference(&doc.0, frame.rect, reflow).any => vec![other, doc], + Some(other) => vec![doc, other], + None => vec![doc], + } +} + +/// `doc`, whose layers draw differently from the page (an object in another color, or one that only +/// one of them draws), with each of its top-level objects that holds such a difference replaced by the +/// page's art in its bounds, when that makes the two look alike → the document and its notes: the +/// comparison's, and how many objects were replaced on each layer (by name, in the layers' order). +/// `None` when only edges or type differ, a difference lies outside every object, more than half +/// of the objects (or more than [`MAX_DIFFERING`]) hold one, one of them holds type or a wrap +/// object, the page's art can't replace one of them ([`replace_unread`]), the page's type of a text +/// object that stays is copied into a replacement, or the two still differ. `shown` is the page's +/// type of each text object that shows. `reflow` as in [`PageView::difference`]. +fn keep_differing( + doc: &Document, + frame: &Frame<'_>, + view: &mut PageView, + threaded_frames: &BTreeSet, + shown: &[Vec>], + reflow: bool, +) -> Option<(Document, Vec)> { + /// The top-level objects that show and print (the outermost objects under a layer or + /// sublayer), with the name of that layer or sublayer as the Layers panel shows it and their + /// bounds. + fn top_level(nodes: &[Arc], layer: &str, out: &mut Vec<(String, NodeId, Rect)>) { + for n in nodes.iter().filter(|n| n.visible) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => {} + NodeKind::Layer { .. } => { + let name = Some(n.display_name()).filter(|name| !name.is_empty()).unwrap_or_else(|| format!("<{}>", n.kind_label())); + top_level(n.children().map_or(&[], Vec::as_slice), &name, out); + } + NodeKind::Path { guide: true, .. } => {} + _ => { + if let Some(b) = n.visual_bounds().filter(|b| b.area().is_finite() && b.area() > 0.0) { + out.push((layer.to_string(), n.id, b)); + } + } + } + } + } + + // Where only spread edges or type differ, or only the art around the page, no object is + // replaced. + let (diff, regions) = view.solid_regions(doc, frame.rect, reflow)?; + if diff.solid <= MAX_SOLID_DIFFERENCE { + return None; + } + let mut objects = vec![]; + top_level(&doc.layers, "", &mut objects); + objects.retain(|(_, _, b)| !b.intersect(frame.rect).is_zero_area()); + if regions.len().saturating_mul(objects.len()) > MAX_PATCH_PAIRS { + return None; + } + // Each patch is the smallest object's that holds it. + let most = MAX_DIFFERING.min(objects.len() / 2); + let mut targets = BTreeSet::new(); + for region in regions { + let (_, id, _) = objects.iter().filter(|(_, _, b)| inside(region, *b)).min_by(|a, b| a.2.area().total_cmp(&b.2.area()))?; + targets.insert(*id); + if targets.len() > most { + return None; + } + } + if targets.is_empty() { + return None; + } + // A replaced wrap object keeps its wrap options, and the area type is wrapped around the page's + // art that replaces it. An object inside a replaced group can't keep them, so such a group isn't + // replaced. Neither is an object that holds type: the page's art that replaces it would hold + // type the page draws for other text objects too. + let mut wraps = vec![]; + for id in &targets { + let node = doc.node(*id)?; + let mut held = matches!(node.kind, NodeKind::Text(_)); + for child in node.children().into_iter().flatten() { + child.walk(&mut |n| held |= n.extras().wrap.is_some() || matches!(n.kind, NodeKind::Text(_))); + } + if held { + return None; + } + if let Some(wrap) = node.extras().wrap { + wraps.push((*id, wrap)); + } + } + let mut kept = doc.clone(); + let replace: Vec<(NodeId, Vec)> = targets.iter().map(|id| (*id, vec![])).collect(); + let mut copied = BTreeSet::new(); + replace_unread(&mut kept, frame, &replace, &[], threaded_frames, &mut copied).ok()?; + // A text object that stays draws its page type, so a copy of that type would draw it twice. + if shown.iter().flatten().any(|n| copied.contains(&n.id)) { + return None; + } + for (id, wrap) in wraps { + kept.node_mut(id)?.extras_mut().wrap = Some(wrap); + } + resolve_text_wrap(&mut kept).ok()?; + let note = compare(frame, view, &kept, reflow).ok()?; + let mut layers: Vec<(String, usize)> = vec![]; + for (layer, _, _) in objects.iter().filter(|(_, id, _)| targets.contains(id)) { + match layers.iter_mut().find(|(name, _)| name == layer) { + Some((_, count)) => *count += 1, + None => layers.push((layer.clone(), 1)), + } + } + let layers: Vec = layers.into_iter().map(|(layer, count)| format!("{layer} ({count})")).collect(); + Some((kept, note.into_iter().chain([format!("{DREW_DIFFERENTLY}: {}", layers.join(", "))]).collect())) +} + /// Copy page drawing IDs, including mask art outside the ordinary child tree. fn reid_page_art(doc: &mut Document, source: &Node) -> Node { let mut copy = doc.reid(source); diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index f382059b64..ac1718e1a5 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -182,6 +182,12 @@ impl PageView { let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); + let areas = self.counted_type(b, rb, reflow); + compared(&self.page, &y, &areas, &self.restyled) + } + + /// Where [`Self::difference`] counts `b`'s and the page's pixels as type, in the page's pixels. + fn counted_type(&self, b: &Document, rb: Rect, reflow: bool) -> Vec { let mut areas = vec![]; type_areas(&b.layers, rb, self.scale, &mut areas); if reflow { @@ -194,7 +200,7 @@ impl PageView { } else { areas.extend(&self.page_type); } - compared(&self.page, &y, &areas, &self.restyled) + areas } /// The share (0 to 1) of the pixels where `b` on `rb` draws another colour than the page @@ -210,6 +216,52 @@ impl PageView { let differing = self.page.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| differ_in_colour(p, q)).count(); differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0) } + + /// How `b` on `rb` draws differently from the page ([`Self::difference`]), and the boxes (in + /// `b`'s terms) around each patch of the pixels counted in its `solid` share (they and all + /// their neighbors differ, away from type), neighbors touching corner to corner counting as one patch. `None` when the two + /// drawings aren't the same size. + pub(super) fn solid_regions(&mut self, b: &Document, rb: Rect, reflow: bool) -> Option<(Difference, Vec)> { + let printed = as_printed(b); + let b = printed.as_ref().unwrap_or(b); + let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); + let areas = self.counted_type(b, rb, reflow); + let (diff, mut solid) = compared_with_solid(&self.page, &y, &areas, &self.restyled); + let (w, h) = (y.width as usize, y.height as usize); + if solid.len() != w * h { + return None; + } + let mut regions = vec![]; + let mut stack = vec![]; + for start in 0..solid.len() { + if !solid.get(start).copied().unwrap_or(false) { + continue; + } + // The patch's pixels are cleared as they are taken, so each is taken once. + if let Some(s) = solid.get_mut(start) { + *s = false; + } + stack.push(start); + let (mut i0, mut j0, mut i1, mut j1) = (start % w, start / w, start % w, start / w); + while let Some(k) = stack.pop() { + let (i, j) = (k % w, k / w); + (i0, j0, i1, j1) = (i0.min(i), j0.min(j), i1.max(i), j1.max(j)); + for n in j.saturating_sub(1)..=(j + 1).min(h - 1) { + for m in i.saturating_sub(1)..=(i + 1).min(w - 1) { + if let Some(s) = solid.get_mut(n * w + m).filter(|s| **s) { + *s = false; + stack.push(n * w + m); + } + } + } + } + let s = self.scale; + let at = |i: usize, j: usize| (rb.x0 + i as f64 / s, rb.y0 + j as f64 / s); + let ((x0, y0), (x1, y1)) = (at(i0, j0), at(i1 + 1, j1 + 1)); + regions.push(Rect::new(x0, y0, x1, y1)); + } + Some((diff, regions)) + } } /// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]), @@ -233,8 +285,14 @@ pub(super) fn difference(a: &Document, ra: Rect, b: &Document, rb: Rect) -> Diff /// at all ([`differ`]): the page of an RGB document is written in the colours' CMYK equivalents, /// and what the comparison looks for is art that is missing or out of place. pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> Difference { + compared_with_solid(x, y, areas, skip).0 +} + +/// [`compared`], and which of the pixels (row by row) are counted in its `solid` share: none when +/// the drawings can't be compared. +fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec) { if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { - return Difference { any: 1.0, art: 1.0, solid: 1.0 }; + return (Difference { any: 1.0, art: 1.0, solid: 1.0 }, vec![]); } let (w, h) = (x.width as usize, x.height as usize); // Pixels in `skip` count as alike. @@ -245,12 +303,22 @@ pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: let typed = in_areas(areas, w, h); let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count(); // A pixel on the region's edge has neighbours outside it, which don't count as differing. - let solid = (1..h.saturating_sub(1)) - .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) - .filter(|&(i, j)| !typed.get(j * w + i).copied().unwrap_or(true) && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))) - .count(); + let mut solid = vec![false; w * h]; + for (i, j) in (1..h.saturating_sub(1)).flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) { + if !typed.get(j * w + i).copied().unwrap_or(true) + && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n))) + && let Some(s) = solid.get_mut(j * w + i) + { + *s = true; + } + } let area = (w as f64 * h as f64).max(1.0); - Difference { any: differs.iter().filter(|d| **d).count() as f64 / area, art: art as f64 / area, solid: solid as f64 / area } + let shares = Difference { + any: differs.iter().filter(|d| **d).count() as f64 / area, + art: art as f64 / area, + solid: solid.iter().filter(|s| **s).count() as f64 / area, + }; + (shares, solid) } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 1033effa9a..cbb4787527 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -18,6 +18,10 @@ pub(super) const PAGE_TYPE_UNCHECKED: &str = pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read"; +/// Objects of the layers replaced with the page's art where they drew differently from it, +/// followed by the layers they are on. +pub(super) const DREW_DIFFERENTLY: &str = "objects that drew differently from the file's own page came in as its art"; + /// Does this import note say that the file has something the document doesn't (hidden text, art or /// layers that could not be read, or the page's type that no text object takes or may not take)? /// Writing the document over the file would lose it for good. @@ -27,7 +31,9 @@ pub fn is_loss(note: &str) -> bool { || note.ends_with("they came in as the page's art") || note == PAGE_TYPE_LEFT_OUT || note == PAGE_TYPE_UNCHECKED - || [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n)) + || [ART_LEFT_OUT, LAYERS_UNREAD, DREW_DIFFERENTLY, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY] + .iter() + .any(|n| note.starts_with(n)) } /// Most text objects in the layers, and most pieces of type in one place on the page, that are matched diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index daeea4826a..6c409bd405 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -824,6 +824,215 @@ fn top_level_placed_file_without_page_art_falls_back() { assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}"); } +const BLACK: &str = "0 0 0 1"; +const YELLOW: &str = "0 0 1 0"; +const PAGE_CYAN: [f32; 4] = [1.0, 0.0, 0.0, 0.0]; +const PAGE_YELLOW: [f32; 4] = [0.0, 0.0, 1.0, 0.0]; + +/// A square of 16 points at (`x`, 10) in the format's operators, painted in CMYK `cmyk`. +fn square_16(x: u32, cmyk: &str) -> String { + format!("{cmyk} k\n{x} 10 m\n{} 10 L\n{} 26 L\n{x} 26 L\nf", x + 16, x + 16) +} + +/// A 100 × 100 page with a square of 16 points at each (`x`, `y`, CMYK) of `squares`: at `y` 74 +/// where [`square_16`] puts the layers' squares. +fn page_16(squares: &[(f64, f64, [f32; 4])]) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + for (i, (x, y, [c, m, ye, k])) in squares.iter().enumerate() { + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(*x, *y, x + 16.0, y + 16.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(*c, *m, *ye, *k)); + let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint)); + let n = Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() }); + d.insert(Some(layer), i, n).unwrap(); + } + d +} + +/// Three squares on two layers, the middle one black in the layers and cyan on the page. +fn middle_differs() -> (String, Document) { + let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, YELLOW)); + let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front))); + (art, page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)])) +} + +#[test] +fn an_object_that_draws_differently_comes_in_as_the_page_art() { + let (art, page) = middle_differs(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Back", "Front"]); + assert_eq!(kinds(&doc.layers[0]), ["path"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + let note = "objects that drew differently from the file's own page came in as its art: Front (1)"; + assert!(notes.iter().any(|n| n == note && crate::is_loss(n)), "{notes:?}"); + assert!(!notes.iter().any(|n| n.contains("weren't read")), "{notes:?}"); +} + +#[test] +fn two_differing_objects_on_different_layers_are_both_replaced() { + let back = format!("{}\n{}", square_16(4, BLACK), square_16(28, YELLOW)); + let front = format!("{}\n{}", square_16(52, YELLOW), square_16(76, BLACK)); + let art = native(&(layer("Back", true, &back) + &layer("Front", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (28.0, 74.0, PAGE_YELLOW), (52.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_CYAN)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Back", "Front"]); + assert_eq!(kinds(&doc.layers[0]), ["group[1]", "path"]); + assert_eq!(kinds(&doc.layers[1]), ["path", "group[1]"]); + replacement_is_cyan(&doc, 0, 0); + replacement_is_cyan(&doc, 1, 1); + let note = "objects that drew differently from the file's own page came in as its art: Back (1), Front (1)"; + assert!(notes.iter().any(|n| n == note), "{notes:?}"); +} + +/// The text wrap options of a 2-point offset, for the object before them. +const WRAP_OPTIONS: &str = "%_/ArtDictionary :\n%_0 /Bool (AI11TextWrapInvert) ,\n%_2 /Real (AI11TextWrapOffset) ,\n%_;\n%_\n"; + +#[test] +fn a_differing_wrap_object_keeps_its_wrap_options() { + let front = format!("{}\n{WRAP_OPTIONS}{}", square_16(40, BLACK), square_16(76, YELLOW)); + let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + let group = &doc.layers[1].children().unwrap()[0]; + assert_eq!(group.extras().wrap, Some(vectorcraft_doc::TextWrap { offset: 2.0, invert: false })); +} + +#[test] +fn a_differing_group_holding_a_wrap_object_still_falls_back() { + let group = os1_group(&format!("{}\n{WRAP_OPTIONS}", square_16(40, BLACK))); + let front = format!("{group}\n{}", square_16(76, YELLOW)); + let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}"); +} + +#[test] +fn a_page_that_differs_everywhere_still_comes_in_as_its_pdf_part() { + let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, BLACK)); + let art = native(&(layer("Back", true, &square_16(4, BLACK)) + &layer("Front", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_CYAN)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("weren't read") && n.contains("differs from the page's")), "{notes:?}"); + assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}"); +} + +#[test] +fn a_page_object_outside_every_layer_object_still_falls_back() { + let front = format!("{}\n{}", square_16(40, YELLOW), square_16(76, YELLOW)); + let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_YELLOW), (40.0, 20.0, PAGE_CYAN)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("differs from the page's")), "{notes:?}"); +} + +#[test] +fn a_differing_object_with_live_art_inside_falls_back() { + // The group reaches over the square between its own two. + let group = os1_group(&format!("{}\n{}", square_16(4, BLACK), square_16(40, YELLOW))); + let front = format!("{group}\n{}\n{}", square_16(22, YELLOW), square_16(76, YELLOW)); + let art = native(&layer("Front", true, &front)); + let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (22.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_YELLOW)]); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("differs from the page's")), "{notes:?}"); +} + +#[test] +fn trusted_editing_data_keeps_a_differing_object() { + let (art, page) = middle_differs(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Back", "Front"]); + assert_eq!(kinds(&doc.layers[1]), ["path", "path"]); + assert!(notes.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{notes:?}"); + assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}"); +} + +#[test] +fn a_differing_object_on_an_unnamed_layer_is_counted_under_its_panel_name() { + let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, YELLOW)); + let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("", true, &front))); + let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]); + let (_, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let note = "objects that drew differently from the file's own page came in as its art: (1)"; + assert!(notes.iter().any(|n| n == note), "{notes:?}"); +} + +#[test] +fn at_most_64_differing_objects_come_in_as_the_page_art() { + // 130 squares of 4 points, the first `black` of them black in the layers and cyan on the page. + let grid = |black: usize| { + let at = |i: usize| (4 + 7 * (i % 13) as u32, 4 + 7 * (i / 13) as u32); + let art: String = (0..130) + .map(|i| { + let (x, y) = at(i); + if i < black { format!("{BLACK} k\n{}", square_path(x, y)) } else { square(x, y) } + }) + .collect::>() + .join("\n"); + let mut page = Document::new(100.0, 100.0); + let layer_id = page.layers[0].id; + for i in 0..130 { + let (x, y) = at(i); + let (x, y) = (f64::from(x), 96.0 - f64::from(y)); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, y, x + 4.0, y + 4.0)); + let color = + if i < black { vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0) } else { vectorcraft_color::Color::cmyk(0.0, 0.0, 1.0, 0.0) }; + let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(color))); + let n = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() }); + page.insert(Some(layer_id), i, n).unwrap(); + } + crate::layered_ai(&private(&native(&layer("Grid", true, &art))), page, vec![], false, false, 1.0) + }; + let (_, notes, read) = grid(64); + assert!(read, "{notes:?}"); + let note = "objects that drew differently from the file's own page came in as its art: Grid (64)"; + assert!(notes.iter().any(|n| n == note), "{notes:?}"); + let (doc, notes, read) = grid(65); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}"); +} + +#[test] +fn a_differing_object_under_the_type_of_a_text_object_that_stays_falls_back() { + // A black rectangle under area type whose frame reaches past it; the page draws the rectangle + // cyan, with the type on it. + let big = format!("{BLACK} k\n10 2 m\n60 2 L\n60 40 L\n10 40 L\nf"); + let doc = document_of(&[area_frame(34.0, 26.0, 95.0, 38.0)], &[story("Hi\\r", &[0], "/0 0", "/1 8.0")]); + let art = native_with_text(&(layer("Art", true, &format!("{big}\n{}", frame_object(0, 0))) + &layer("Top", true, &square_16(76, YELLOW))), &doc); + let mut page = page_16(&[(76.0, 74.0, PAGE_YELLOW)]); + let layer_id = page.layers[0].id; + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 60.0, 60.0, 98.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint)); + let square = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() }); + page.insert(Some(layer_id), 0, square).unwrap(); + let style = vectorcraft_doc::CharStyle { size: 8.0, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(34.0, 69.0), "Hi", style); + let text = Node::new(page.alloc_id(), NodeKind::Text(Box::new(text))); + page.insert(Some(layer_id), 1, text).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}"); +} + #[test] fn unread_object_on_second_artboard_takes_second_page_art() { let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3bda3f6b84..576b657ec7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6026,6 +6026,7 @@ breakText Glyphs Глифи Gap 5 Разстояние 5 @msg {_1}: they came in as the page's art {_1}: те са внесени като изображението от страницата +@msg objects that drew differently from the file's own page came in as its art: {_1} обектите, изобразени различно от собствената страница на файла, са внесени като изображението от страницата: {_1} @msg You must choose a side pattern. Трябва да изберете страничен шаблон. @msg invalid pattern tile choice невалиден избор на плочка за шаблон diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 20744b85ee..fa99041494 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6060,6 +6060,7 @@ shape Open Otvoren @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena @msg {_1}: they came in as the page's art {_1}: uvezeni su kao ilustracija stranice +@msg objects that drew differently from the file's own page came in as its art: {_1} objekti koji su se iscrtali drugačije od vlastite stranice datoteke uvezeni su kao ilustracija stranice: {_1} @msg You must choose a side pattern. Morate odabrati bočni uzorak. @msg invalid pattern tile choice nevažeći izbor pločice uzorka diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ccc19399..0e21ff719c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6158,6 +6158,7 @@ breakText Glyphs Glifs Gap 5 Separació 5 @msg {_1}: they came in as the page's art {_1}: han entrat com a art de la pàgina +@msg objects that drew differently from the file's own page came in as its art: {_1} els objectes que es dibuixaven diferent de la pàgina pròpia del fitxer han entrat com a art de la pàgina: {_1} @msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000 @msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index aa81fbca3c..bc3ccd20bd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6174,6 +6174,7 @@ breakText Glyphs Glyfy Gap 5 Mezera 5 @msg {_1}: they came in as the page's art {_1}: byly načteny jako kresba ze stránky +@msg objects that drew differently from the file's own page came in as its art: {_1} objekty, které se vykreslily jinak než vlastní stránka souboru, byly načteny jako kresba ze stránky: {_1} @msg You must choose a side pattern. Musíte zvolit boční vzorek. @msg invalid pattern tile choice neplatná volba dlaždice vzorku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8556ae44ec..4a2c248dcc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6042,6 +6042,7 @@ breakText Glyphs Glyffer Gap 5 Mellemrum 5 @msg {_1}: they came in as the page's art {_1}: de blev importeret som sidens grafik +@msg objects that drew differently from the file's own page came in as its art: {_1} objekter, der blev tegnet anderledes end filens egen side, blev importeret som sidens grafik: {_1} @msg You must choose a side pattern. Du skal vælge et sidemønster. @msg invalid pattern tile choice ugyldigt valg af mønsterflise diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0e1bf7ece6..c9955c72b8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5760,6 +5760,7 @@ breakText Glyphs Glyphen Gap 5 Lücke 5 @msg {_1}: they came in as the page's art {_1}: sie wurden als Seitengrafik importiert +@msg objects that drew differently from the file's own page came in as its art: {_1} Objekte, die anders als die eigene Seite der Datei gezeichnet wurden, wurden als Seitengrafik importiert: {_1} @msg You must choose a side pattern. Sie müssen ein Seitenmuster auswählen. @msg invalid pattern tile choice ungültige Auswahl einer Musterkachel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 01471ba16b..67b9a73176 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6126,6 +6126,7 @@ breakText Glyphs Γλύφοι Gap 5 Διάκενο 5 @msg {_1}: they came in as the page's art {_1}: εισήχθησαν ως γραφικά της σελίδας +@msg objects that drew differently from the file's own page came in as its art: {_1} τα αντικείμενα που σχεδιάστηκαν διαφορετικά από την ίδια τη σελίδα του αρχείου εισήχθησαν ως γραφικά της σελίδας: {_1} @msg You must choose a side pattern. Πρέπει να επιλέξετε πλευρικό μοτίβο. @msg invalid pattern tile choice μη έγκυρη επιλογή πλακιδίου μοτίβου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b68ba40d6f..09ec906bc4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6116,6 +6116,7 @@ breakText Glyphs Glifos Gap 5 Hueco 5 @msg {_1}: they came in as the page's art {_1}: se importaron como el arte de la página +@msg objects that drew differently from the file's own page came in as its art: {_1} los objetos que se dibujaban de forma distinta a la página del propio archivo se importaron como el arte de la página: {_1} @msg You must choose a side pattern. Debe elegir un motivo lateral. @msg invalid pattern tile choice selección de mosaico de motivo no válida diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e44dac5b1a..ad10d08752 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6204,6 +6204,7 @@ breakText Glyphs Merkit Gap 5 Väli 5 @msg {_1}: they came in as the page's art {_1}: ne tuotiin sivun piirroksena +@msg objects that drew differently from the file's own page came in as its art: {_1} objektit, jotka piirtyivät eri tavoin kuin tiedoston oma sivu, tuotiin sivun piirroksena: {_1} @msg You must choose a side pattern. Valitse sivukuvio. @msg invalid pattern tile choice virheellinen kuviolaatan valinta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e435b22b8b..18dffaeb44 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6169,6 +6169,7 @@ breakText Glyphs Glyphes Gap 5 Écart 5 @msg {_1}: they came in as the page's art {_1} : ils ont été importés comme le dessin de la page +@msg objects that drew differently from the file's own page came in as its art: {_1} les objets dessinés différemment de la page du fichier lui-même ont été importés comme le dessin de la page : {_1} @msg You must choose a side pattern. Vous devez choisir un motif latéral. @msg invalid pattern tile choice choix de tuile de motif non valide diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1b6037294e..fb1f9c7bc0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6158,6 +6158,7 @@ breakText Glyphs Glifák Gap 5 Hézag 5 @msg {_1}: they came in as the page's art {_1}: az oldal rajzaként lettek importálva +@msg objects that drew differently from the file's own page came in as its art: {_1} a fájl saját oldalától eltérően rajzolt objektumok az oldal rajzaként lettek importálva: {_1} @msg You must choose a side pattern. Válasszon oldalsó mintát. @msg invalid pattern tile choice érvénytelen mintacsempe-választás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3e784fe339..abf75d9658 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6042,6 +6042,7 @@ breakText Glyphs Glif Gap 5 Jarak 5 @msg {_1}: they came in as the page's art {_1}: diimpor sebagai gambar halaman +@msg objects that drew differently from the file's own page came in as its art: {_1} objek yang tergambar berbeda dari halaman file itu sendiri diimpor sebagai gambar halaman: {_1} @msg You must choose a side pattern. Anda harus memilih pola sisi. @msg invalid pattern tile choice pilihan ubin pola tidak valid diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f51eb524aa..9d61d8c3e9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5794,6 +5794,7 @@ breakText Glyphs Glifi Gap 5 Spazio 5 @msg {_1}: they came in as the page's art {_1}: sono stati importati come elementi grafici della pagina +@msg objects that drew differently from the file's own page came in as its art: {_1} gli oggetti disegnati in modo diverso dalla pagina del file stesso sono stati importati come elementi grafici della pagina: {_1} @msg You must choose a side pattern. Devi scegliere un motivo laterale. @msg invalid pattern tile choice scelta della tessera motivo non valida diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8630535a52..50241341d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5859,6 +5859,7 @@ breakText Glyphs 字形 Gap 5 間隔 5 @msg {_1}: they came in as the page's art {_1}: ページのアートとして読み込みました +@msg objects that drew differently from the file's own page came in as its art: {_1} ファイル自身のページと描画が異なるオブジェクトをページのアートとして読み込みました: {_1} @msg You must choose a side pattern. 側面パターンを選択してください。 @msg invalid pattern tile choice パターンタイルの選択が無効です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6cf5cdb6b4..112dfa657f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6162,6 +6162,7 @@ breakText Glyphs გლიფები Gap 5 შუალედი 5 @msg {_1}: they came in as the page's art {_1}: იმპორტირებულია გვერდის გამოსახულების სახით +@msg objects that drew differently from the file's own page came in as its art: {_1} ობიექტები, რომლებიც ფაილის საკუთარი გვერდისგან განსხვავებულად იხატებოდა, იმპორტირებულია გვერდის გამოსახულების სახით: {_1} @msg You must choose a side pattern. აირჩიეთ გვერდითი ნიმუში. @msg invalid pattern tile choice ნიმუშის ფილა არასწორად არის არჩეული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 338be6dce0..4ad48aa619 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5755,6 +5755,7 @@ breakText Glyphs 글리프 Gap 5 간격 5 @msg {_1}: they came in as the page's art {_1}: 페이지의 아트로 가져왔습니다 +@msg objects that drew differently from the file's own page came in as its art: {_1} 파일 자체 페이지와 다르게 그려진 오브젝트를 페이지의 아트로 가져왔습니다: {_1} @msg You must choose a side pattern. 측면 패턴을 선택해야 합니다. @msg invalid pattern tile choice 잘못된 패턴 타일 선택 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 263545d27c..5096aa81cd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6086,6 +6086,7 @@ breakText Glyphs Glyphs Gap 5 Tussenruimte 5 @msg {_1}: they came in as the page's art {_1}: ze zijn geïmporteerd als pagina-afbeelding +@msg objects that drew differently from the file's own page came in as its art: {_1} objecten die anders werden getekend dan de eigen pagina van het bestand, zijn geïmporteerd als pagina-afbeelding: {_1} @msg You must choose a side pattern. Kies een zijpatroon. @msg invalid pattern tile choice ongeldige keuze voor patroontegel diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4cb23d6ac5..d431ce0fb3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6029,6 +6029,7 @@ breakText Glyphs Glify Gap 5 Odstęp 5 @msg {_1}: they came in as the page's art {_1}: zaimportowano je jako grafikę strony +@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako grafikę strony: {_1} @msg You must choose a side pattern. Musisz wybrać wzór boczny. @msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f53f0798e9..b726d9ddb7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6092,6 +6092,7 @@ breakText Glyphs Glifos Gap 5 Lacuna 5 @msg {_1}: they came in as the page's art {_1}: foram importados como arte da página +@msg objects that drew differently from the file's own page came in as its art: {_1} os objetos desenhados de forma diferente da própria página do arquivo foram importados como arte da página: {_1} @msg You must choose a side pattern. Você deve escolher um padrão lateral. @msg invalid pattern tile choice escolha inválida de ladrilho de padrão diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c5a493ad84..0cb2785ac8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6151,6 +6151,7 @@ breakText Glyphs Глифы Gap 5 Зазор 5 @msg {_1}: they came in as the page's art {_1}: импортированы как графика страницы +@msg objects that drew differently from the file's own page came in as its art: {_1} объекты, которые отрисовывались иначе, чем собственная страница файла, импортированы как графика страницы: {_1} @msg You must choose a side pattern. Выберите боковой узор. @msg invalid pattern tile choice недопустимый выбор плитки узора diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 77d5c41b6d..4fdd6abf23 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6226,6 +6226,7 @@ breakText Glyphs Glyfer Gap 5 Mellanrum 5 @msg {_1}: they came in as the page's art {_1}: de importerades som sidans bild +@msg objects that drew differently from the file's own page came in as its art: {_1} objekt som ritades annorlunda än filens egen sida importerades som sidans bild: {_1} @msg You must choose a side pattern. Du måste välja ett sidomönster. @msg invalid pattern tile choice ogiltigt val av mönsterplatta diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index efbcf69343..ac0931554e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6131,6 +6131,7 @@ breakText Glyphs Glifler Gap 5 Boşluk 5 @msg {_1}: they came in as the page's art {_1}: sayfanın çizimi olarak içe aktarıldılar +@msg objects that drew differently from the file's own page came in as its art: {_1} dosyanın kendi sayfasından farklı çizilen nesneler sayfanın çizimi olarak içe aktarıldı: {_1} @msg You must choose a side pattern. Bir yan desen seçmelisiniz. @msg invalid pattern tile choice geçersiz desen döşemesi seçimi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b7d8962a90..a7febfd3aa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5774,6 +5774,7 @@ breakText Glyphs Гліфи Gap 5 Проміжок 5 @msg {_1}: they came in as the page's art {_1}: їх імпортовано як графіку сторінки +@msg objects that drew differently from the file's own page came in as its art: {_1} об’єкти, що малювалися інакше, ніж власна сторінка файлу, імпортовано як графіку сторінки: {_1} @msg You must choose a side pattern. Виберіть бічний візерунок. @msg invalid pattern tile choice недійсний вибір плитки візерунка diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 41a5d4c64a..7c7d89b791 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5775,6 +5775,7 @@ breakText Glyphs Glyph Gap 5 Khoảng hở 5 @msg {_1}: they came in as the page's art {_1}: đã được nhập dưới dạng hình vẽ của trang +@msg objects that drew differently from the file's own page came in as its art: {_1} các đối tượng được vẽ khác với trang riêng của tệp đã được nhập dưới dạng hình vẽ của trang: {_1} @msg You must choose a side pattern. Bạn phải chọn mẫu bên. @msg invalid pattern tile choice lựa chọn ô mẫu không hợp lệ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8e383be64c..2b70c03aab 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6015,6 +6015,7 @@ breakText Glyphs 字形 Gap 5 间隔 5 @msg {_1}: they came in as the page's art {_1}:已作为页面图稿导入 +@msg objects that drew differently from the file's own page came in as its art: {_1} 与文件自身页面绘制不同的对象已作为页面图稿导入:{_1} @msg You must choose a side pattern. 必须选择侧边图案。 @msg invalid pattern tile choice 图案拼块选项无效 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e401ee090f..26e592e8fc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5812,6 +5812,7 @@ breakText Glyphs 字符 Gap 5 間隙 5 @msg {_1}: they came in as the page's art {_1}:已作為頁面圖稿匯入 +@msg objects that drew differently from the file's own page came in as its art: {_1} 與檔案本身頁面繪製不同的物件已作為頁面圖稿匯入:{_1} @msg You must choose a side pattern. 必須選擇側邊圖樣。 @msg invalid pattern tile choice 圖樣拼塊選項無效 diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6f02703ca5..be0bc3596b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -113,7 +113,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format From b5c69e25fdd9113f9d9b139973faa93966f3c3a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 18:25:02 -0800 Subject: [PATCH 49/50] Add command to begin recording Actions --- crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 ++ crates/ui-egui/src/panels/actions.rs | 80 ++++++++++++++++++++----- docs/mcp.md | 4 ++ 4 files changed, 76 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5f3969546f..1666e147ec 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -823,6 +823,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::new_action(app, p), crate::panels::actions::ACTION_OPTIONS => crate::panels::actions::action_options(app, p), crate::panels::actions::PLAY_ACTION => crate::panels::actions::play_action(app, p), + crate::panels::actions::START_RECORDING => crate::panels::actions::record(app, p), crate::panels::actions::STOP_RECORDING => crate::panels::actions::stop(app, p), "ui.batchDialog" => { let set = p.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 31b263d3b4..d4677597ae 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1205,6 +1205,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{action: name, set?: name} play the Actions panel's action named action as one undoable batch; set names the set to look in (default: every set). A name no action has, or one that more than one action in the sets looked in has, is an error and nothing plays → what command.batch returns", ), + ( + crate::panels::actions::START_RECORDING, + "Begin Recording", + "", + "{set?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. An explicit invalid set or an existing recording is an error and changes nothing → {set, name}", + ), ( crate::panels::actions::STOP_RECORDING, "Stop Playing/Recording", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 174fab9bc3..8948fbef2e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -235,8 +235,10 @@ pub fn new_action(app: &mut VectorcraftApp, p: &Value) -> Result s.actions.push(action); let index = s.actions.len() - 1; start_recording(app, set, name, Some(id)); - app.ui.action_set = Some(set); - app.ui.action_sets_selected = vec![set]; + if app.ui.action_set != Some(set) { + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; + } if let Some(ctx) = app.ui_ctx.clone() { set_pstate::>(&ctx, "actions-selected", Some((set, index))); } @@ -328,6 +330,40 @@ pub fn play_action(app: &mut VectorcraftApp, p: &Value) -> Result /// The command that ends a recording ([`stop`]). pub const STOP_RECORDING: &str = "ui.action.stop"; +/// The command that begins a plain recording ([`record`]). +pub const START_RECORDING: &str = "ui.action.record"; + +/// `ui.action.record {set?}`: begins recording an automatically named Action N in `set`, or in +/// the current set (the first if none is current). With no sets, makes Set 1. Stop adds the action +/// after the set's existing actions. An explicit invalid set or an existing recording is an error +/// and leaves the panel unchanged. → {set, name} +pub fn record(app: &mut VectorcraftApp, p: &Value) -> Result { + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + let set = match p.get("set") { + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < app.ui.action_sets.len()).ok_or("no such action set")?, + _ => { + if app.ui.action_sets.is_empty() { + app.ui.action_sets.push(ActionSet::new("Set 1", vec![])); + } + app.ui.action_set.filter(|&i| i < app.ui.action_sets.len()).unwrap_or(0) + } + }; + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; + let mut number = app.ui.action_sets[set].actions.len() + 1; + let name = loop { + let name = format!("Action {number}"); + if app.ui.action_sets[set].actions.iter().all(|action| action.name != name) { + break name; + } + number += 1; + }; + start_recording(app, set, name.clone(), None); + Ok(json!({ "set": set, "name": name })) +} + /// `ui.action.stop {}`: ends the recording in progress and keeps its steps, in the action New /// Action made for it, else in a new action after the last action of its set, as the bottom bar's /// Stop Playing/Recording does. With nothing recording it changes nothing. → {stopped} @@ -786,19 +822,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } let (r, resp) = ui.allocate_exact_size(egui::vec2(24.0, 24.0), egui::Sense::click()); ui.painter().circle_filled(r.center(), 6.0, if recording { egui::Color32::from_rgb(0xe0, 0x30, 0x30) } else { t.icon }); - if resp.on_hover_text(tl!("Begin Recording")).clicked() && !recording { - if app.ui.action_sets.is_empty() { - app.ui.action_sets.push(ActionSet::new("Set 1", vec![])); - } - let set = current.filter(|&s| s < app.ui.action_sets.len()).unwrap_or(0); - // With no set current, the recording goes into the first set, which becomes current so - // the panel shows where the recording goes. - if app.ui.action_set != Some(set) { - app.ui.action_set = Some(set); - app.ui.action_sets_selected = vec![set]; - } - let n = app.ui.action_sets.get(set).map_or(0, |s| s.actions.len()) + 1; - start_recording(app, set, format!("Action {n}"), None); + if resp.on_hover_text(tl!("Begin Recording")).clicked() + && !recording + && let Err(e) = app.run(START_RECORDING, json!({})) + { + app.status(e); } if widgets::icon_button(ui, "dc-actions", tl!("Play Current Selection"), false, 24.0).clicked() && let Some(s) = selected @@ -847,6 +875,28 @@ mod tests { } } + #[test] + fn begin_recording_command_matches_the_panel_button() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.action_sets.clear(); + app.ui.action_set = None; + assert_eq!(app.run(START_RECORDING, json!({})).unwrap(), json!({"set": 0, "name": "Action 1"})); + assert_eq!((app.ui.action_sets[0].name.as_str(), app.ui.action_set), ("Set 1", Some(0))); + assert_eq!(app.run(START_RECORDING, json!({})).unwrap_err(), "an action is already recording"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": true})); + assert_eq!((app.ui.action_sets[0].actions[0].name.as_str(), app.ui.action_sets[0].actions[0].steps.len()), ("Action 1", 1)); + + app.ui.action_sets.push(ActionSet::new("Other", vec![])); + assert_eq!(app.run(START_RECORDING, json!({"set": 99})).unwrap_err(), "no such action set"); + assert_eq!(app.run(START_RECORDING, json!({"set": null})).unwrap_err(), "no such action set"); + assert!(app.ui.recording.is_none()); + assert_eq!(app.run(START_RECORDING, json!({"set": 1})).unwrap(), json!({"set": 1, "name": "Action 1"})); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.as_slice()), (Some(1), &[1][..])); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": true})); + } + /// #1629: a clicked action stays selected, so Play Current Selection plays it and Delete /// Selection deletes it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index fd739b4064..af2adefa7a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1774,6 +1774,10 @@ already walks Image Trace. Short agent entry points: cannot be used. While an action is recording, and for an index past the last set, an empty name, or a key or color that is not one of these, it is an error and nothing is added. The panel's Create New Action button and menu's New Action… open the `actionNew` dialog, whose Record runs this. +- Actions: `ui.action.record {set?}` starts recording a new action in the chosen set, or the current set when `set` + is left out, and returns `{set, name}`. With no sets, it creates Set 1. The action gets the next available + `Action N` name in that set. The Actions panel's Begin Recording button runs this command. An invalid set or an + existing recording is an error and leaves the sets and recording unchanged. - Actions: `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}` changes the action at `action` in set `set` and keeps its steps: `name` renames it, `key` with `cmd` and `shift` sets its function key, and `color` its Button Mode color, as `ui.action.new` takes them; a param left out keeps what the action has, and From 821757acef2da048ea1610e9c25cd428f2506e3f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 4 Nov 2026 09:24:46 +0700 Subject: [PATCH 50/50] Control server: the junk-closes test leaves no unread input On Windows, closing a socket with unread input resets the connection, and the reset can discard the reply before the client reads it, so the test failed under load. The request after junk is still covered by the in-memory tests. --- apps/vectorcraft/src/control_server/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs index e3d946ef0a..aad5d7d083 100644 --- a/apps/vectorcraft/src/control_server/tests.rs +++ b/apps/vectorcraft/src/control_server/tests.rs @@ -334,7 +334,9 @@ fn tcp_connection_is_closed_after_junk() { }); let mut c = TcpStream::connect(addr).unwrap(); c.set_read_timeout(Some(WAIT)).unwrap(); - c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap(); + // Nothing after the junk line: on Windows, closing a socket with unread input resets the + // connection, and the reset can discard the reply before the client reads it. + c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap(); let mut text = String::new(); c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection server.join().unwrap();