From 944ba1c0c18a7cac086ec2fe633176a5bc6fd9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:49:16 -0800 Subject: [PATCH 01/13] Direct Selection: a press on a member of a selected group keeps the group With a group selected, Direct Selection treated a click on one of its paths as a click on an unselected path: it selected that path alone, so a drag moved only that path. The tools checked whether the path itself was in the selection and ignored a selected group around it. A path inside a selected object now counts as selected whole: - A click on its fill keeps the group selected, and a drag from its fill or one of its anchors moves the group whole. - A click on one of its anchors or segments selects that anchor or segment alone, as for a selected path. - Its anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. - Group Selection adds the group above the outermost selected one, and keeps the selection when that is the top group. This applies to the Cmd/Ctrl press the Selection tool lends Direct Selection too. --- crates/tools/src/direct.rs | 113 +++++++++++++++++++++---------- crates/tools/src/direct/tests.rs | 77 +++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 157 insertions(+), 34 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 15c2f354d4..e3dc1ad1e4 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -18,6 +18,10 @@ //! the drag makes it select only the objects entirely inside it, whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. +//! An object inside a selected group counts as selected whole: a click on its fill keeps the group +//! selected, a drag from its fill or one of its anchors moves the group whole, and a click on an +//! anchor or a segment selects that anchor or segment alone. With Group Selection a click there +//! adds the next group up, if any. //! Both move objects selected as a whole as the Selection tool does, snapping alike. When the //! selection also holds direct-selected anchors or segments, a drag from an object moves those //! anchors and the objects selected whole, as an anchor drag does, and while Alt is held it @@ -53,7 +57,7 @@ //! moves its anchors. use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; @@ -556,12 +560,14 @@ fn line_end_leave(cx: &ToolContext, grab: Point) -> Option { /// objects behind it (#3405). fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> { let mut owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n) || is_path_type(n)); - owners.sort_by_key(|id| !cx.selection.contains(*id)); + // The members of a selected group count as selected. + let selected = in_selection_all(cx); + owners.sort_by_key(|id| !selected.contains(id)); // 1. Check selected objects first. Selected objects are NEVER occluded (#1508). let mut unselected_idx = owners.len(); for (i, &id) in owners.iter().enumerate() { - if !cx.selection.contains(id) { + if !selected.contains(&id) { unselected_idx = i; break; } @@ -621,12 +627,26 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { return true; } - // The editable paths' control bounds are listed once per document state and selection; a - // hover measures only the paths whose bounds it is near. - let boxes = crate::select::selected_part_boxes(cx, || { + selected_part_boxes(cx).iter().any(|&(id, b)| { + b.inflate(tol, tol).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() + }) + }) +} + +/// The editable paths of the selected objects and inside them (a selected group's members), with +/// their control bounds: each selected object's paths topmost first, in selection order. The list +/// is made once per document state and selection; a hover measures only the paths whose bounds it +/// is near. +fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> { + crate::select::selected_part_boxes(cx, || { let editable = cx.doc.editable(); let mut v = vec![]; for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + let from = v.len(); walk_pickable_from(root, &mut |n| { if editable(n.id) && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) @@ -634,16 +654,9 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { v.push((n.id, b)); } }); + v[from..].reverse(); } v.into() - }); - boxes.iter().any(|&(id, b)| { - b.inflate(tol, tol).contains(p) - && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { - #[cfg(test)] - MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); - nearest_anchor(&pd, p, tol, None).is_some() - }) }) } @@ -820,13 +833,37 @@ struct SegmentHit { fn next_group(cx: &ToolContext, ancestry: &[NodeId]) -> Option { // Skip the layer and its sublayers: they are not objects. let layers = ancestry.iter().take_while(|id| cx.doc.node(**id).is_some_and(Node::is_layer)).count().max(1); - ancestry + let chain: Vec = ancestry .iter() .skip(layers) .rev() .copied() .take_while(|id| in_scope(cx.doc, cx.isolation, *id) && !cx.doc.node(*id).is_some_and(Node::is_layer)) - .find(|id| !cx.selection.contains(*id)) + .collect(); + // The groups inside a selected group are selected with it: the next one is above the outermost + // selected one. + let outermost = chain.iter().rposition(|id| cx.selection.contains(*id)); + chain.get(outermost.map_or(0, |i| i + 1)).copied() +} + +/// Is `id` selected as an object: itself, or inside a selected group or other selected object? A +/// press on a member of a selected group keeps the group selected, and a drag moves the group +/// whole, as for a path that is itself selected. +fn in_selection(cx: &ToolContext, id: NodeId) -> bool { + !cx.selection.objects.is_empty() + && (cx.selection.contains(id) || cx.doc.ancestry(id).is_some_and(|a| a.iter().any(|x| cx.selection.contains(*x)))) +} + +/// The selected objects and the objects inside them that Direct Selection may pick: the objects +/// among those [`walk_pickable`] visits that [`in_selection`] accepts. +fn in_selection_all(cx: &ToolContext) -> HashSet { + let mut set = HashSet::new(); + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + set.insert(n.id); + }); + } + set } /// Is an object of instance `id`'s art selected ([`vectorcraft_doc::Selection::symbol_part`]), @@ -1327,7 +1364,7 @@ impl DirectSelectionTool { // anchors on mouse over finds them: walking every path on each hover is too slow. let hit = hit_test(cx.doc, p, cx.selection_hit_options()); if let Some((id, _)) = hovered_anchor_with_hit(cx, p, hit.as_ref()) { - return Some(if cx.selection.contains(id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); + return Some(if in_selection(cx, id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); } if hit_frame_edge(cx, p, tol).is_some() { return None; @@ -1339,7 +1376,7 @@ impl DirectSelectionTool { return None; } let h = hit?; - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none(); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none(); let curved = matches!(h.kind, HitKind::Stroke | HitKind::Outline) && segment_at(cx, h.leaf, p).is_some_and(|s| s.curved); (!whole && curved).then_some(Cursor::ReshapeSegment) } @@ -1355,7 +1392,11 @@ fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> { fn hovered_anchor_with_hit(cx: &ToolContext, p: Point, hit: Option<&Hit>) -> Option<(NodeId, Point)> { let tol = cx.point_tol(); let under = hit.map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf)); - cx.selection.objects.iter().copied().filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { + // The paths inside a selected group come before an object above them, as a press takes them + // ([`hit_anchor`]). + let selected = if cx.selection.objects.is_empty() { None } else { Some(selected_part_boxes(cx)) }; + let near = selected.iter().flat_map(|boxes| boxes.iter()).filter(|(_, b)| b.inflate(tol, tol).contains(p)).map(|&(id, _)| id); + near.filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { let path = cx.doc.node(id).and_then(editable_path)?; nearest_anchor(&path, p, tol, None).map(|(.., a)| (id, a)) }) @@ -1476,7 +1517,9 @@ impl DirectSelectionTool { h.ancestry.push(part); h.leaf = part; } - let target = if cx.selection.contains(h.leaf) { next_group(cx, &h.ancestry).unwrap_or(h.leaf) } else { h.leaf }; + // On an object selected itself or inside a selected group, a click adds the next group up, + // and keeps the selection when the outermost group is selected already. + let inside = in_selection(cx, h.leaf); let mut deselect = None; let mut out = vec![]; if ev.mods.shift { @@ -1485,15 +1528,13 @@ impl DirectSelectionTool { if cx.selection.contains(h.leaf) { deselect = Some(h.leaf); } else { - out.push(Action::Exec("select.toggle".into(), json!({"id": target.0}))); - } - } else if !cx.selection.contains(target) { - if cx.selection.contains(h.leaf) { - // A completed click climbs the group; a drag moves only the selected art. - self.click_group = Some(target); - } else { - out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); + out.push(Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))); } + } else if !inside { + out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))); + } else if let Some(target) = next_group(cx, &h.ancestry) { + // A completed click climbs the group; a drag moves only the selected art. + self.click_group = Some(target); } self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect }; out @@ -1534,15 +1575,16 @@ impl DirectSelectionTool { // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None }; - let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); + let whole = in_selection(cx, id) && cx.selection.partial(id).is_none(); if whole && !ev.mods.shift { self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); } return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } - // A path with all its anchors selected is stored whole (no partial entry). + // A path with all its anchors selected is stored whole (no partial entry), and so is each + // path inside a selected group. let already = - cx.selection.contains(id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); + in_selection(cx, id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { @@ -1620,7 +1662,7 @@ impl DirectSelectionTool { // A segment pick keeps its endpoints available for movement without selecting // the anchors themselves. Dragging reshapes a curve, else moves it. Alt picks // the whole path (and Alt-drag copies it), as with Group Selection. - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); if !ev.mods.alt && matches!(h.kind, HitKind::Stroke | HitKind::Outline) && let Some(s) = segment_at(cx, h.leaf, p) @@ -1656,7 +1698,8 @@ impl DirectSelectionTool { return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))]; } self.frame.clear(); - if !cx.selection.contains(h.leaf) || cx.selection.partial(h.leaf).is_some() || part_picked(cx, h.leaf) { + // A press inside a selected group keeps the group: a drag moves it whole. + if !whole { return vec![Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))]; } vec![] @@ -1857,7 +1900,9 @@ impl DirectSelectionTool { (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { - if has_multiple_selected_anchors(cx) { + // The key anchor is on a path selected itself (`select.key`); a click on an anchor of + // a path inside a selected group selects that anchor alone. + if cx.selection.contains(id) && has_multiple_selected_anchors(cx) { if cx.selection.key_anchor == Some((id, (si, ai))) { vec![Action::Exec("select.key".into(), json!({}))] } else { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..1b03ad81d0 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1306,6 +1306,83 @@ fn group_selection_distinguishes_selected_leaf_drags_from_clicks() { assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty()); } +/// A path inside a selected group counts as selected whole. With Direct Selection a click on its +/// fill keeps the group, a drag from its fill or an anchor moves the group whole, and a click on an +/// anchor selects that anchor alone; its anchors show the selected-anchor cursor and an object +/// above the group does not take a press on one. With Group Selection a click adds the next group +/// up and keeps the selection at the outermost one, and a drag moves the selection. +#[test] +fn a_press_inside_a_selected_group_keeps_the_group() { + let (mut d, inside, _, inner, outer) = nested_group_doc(); + let p = paint(); + let mut s = Selection::default(); + s.set([outer]); + let moves = |a: &[Action]| matches!(a, [Action::Begin(n), Action::Preview(c, _)] if n == "Move" && c == "object.transform"); + for group in [false, true] { + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(group); + let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0); + assert!(t.pointer(&c, &down).is_empty(), "a press on the fill (group: {group})"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty(), "a click on the fill (group: {group})"); + assert!(t.pointer(&c, &down).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0)); + assert!(moves(&a), "a drag from the fill (group: {group}): {a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]); + } + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + let corner = PointerEvent::new(PointerKind::Down, 100.0, 100.0); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)); + assert!(moves(&a), "a drag from an anchor: {a:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 115.0)); + t.pointer(&c, &corner); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor" + ); + assert_eq!(DirectSelectionTool::new(false).cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty(), "a press on a segment"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); + assert!(matches!(a.as_slice(), [Action::Exec(c, v)] if c == "select.segments" && v["id"] == inside.0), "a click on a segment: {a:?}"); + // Group Selection climbs from a selected inner group to the group around it. + let mut climb = Selection::default(); + climb.set([inner]); + let c = cx(&d, &climb, &p); + let mut t = DirectSelectionTool::new(true); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), vec![Action::Exec("select.add".into(), json!({"ids": [outer.0]}))]); + // With two anchors of a path beside the group selected too, the click still selects the anchor + // alone: the key anchor is on a path selected itself. + let l = d.layers[0].id; + let beside = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(beside, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut mixed = Selection::default(); + mixed.set([outer, beside]); + mixed.anchors.insert(beside, BTreeSet::from([(0, 0), (0, 1)])); + let c = cx(&d, &mixed, &p); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &corner).is_empty()); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor with anchors of {beside:?} selected" + ); + // An opaque object above the group, over the anchor. + let cover = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(cover, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + assert_eq!(hovered_anchor(&c, Point::new(100.0, 100.0)), Some((inside, Point::new(100.0, 100.0))), "the anchor under {cover:?} is highlighted"); + assert_eq!(t.cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor under {cover:?}"); + assert!(moves(&t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)))); +} + /// Isolation mode: a marquee and an anchor click take the path inside the isolated group and /// leave the path beside it. Group Selection stops at the isolated group instead of adding /// the group around it. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..465681c751 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -844,6 +844,7 @@ since 2026-10-01. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then hide; a Shift-click on another corner's anchor adds that corner and shows its widget, and a Shift-click on a showing widget deselects its corner. Adding a corner by Shift-clicking its widget while it is hidden stays open (#1232). Corner widgets are chosen by clicking one and Shift-clicking the others ([Logos By Nick, rounded corners in Illustrator](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **A press inside a selected group** (VectorCraft's own rule): with Direct Selection, a path inside a selected group counts as selected whole. A click on its fill keeps the group selected, a drag from its fill or one of its anchors moves the group whole, and a click on an anchor or a segment selects it alone. The path's anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. Group Selection adds the group above the outermost selected one. This also applies to the Cmd/Ctrl press the Selection tool lends Direct Selection. Test: `direct::tests::a_press_inside_a_selected_group_keeps_the_group`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). From 2b83acd239efd9882b60e6e85dc0f353ca98cf15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:07:50 -0800 Subject: [PATCH 02/13] Document Setup: menus and fields apply a value only once it is chosen or committed Language, the Grid Colors menu, the two grid color hex fields and the bleed fields read the value each control reported in the frame, which includes a highlighted menu entry and a draft still being typed. A language highlighted with the arrow keys replaced the quotes, and Escape left them replaced; a highlighted Grid Colors preset replaced both colors; a partly typed hex code or bleed changed the dialog's values before Enter or Tab. The four reads now take the committed value, as New Document does. --- crates/ui-egui/src/dialogs/document_setup.rs | 149 ++++++++++++++++++- 1 file changed, 142 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0c6e1b5f56..94ff0e8339 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -316,7 +316,6 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext let bare_points = fields.bool("numbersWithoutUnitsArePoints").unwrap_or(true); let lengths = crate::fields::bare_points(LengthUnits::new(UnitKind::Points, unit_kind(unit), 72.0), bare_points); let parts = bleed_of(fields).map(|b| Mixed::Same(Some(b))); - // PLAN: assumed the linked fields' output reads as `out.edit.value()`, as the shape dialog uses it. let out = LinkedFields::<4>::new(tl!("Bleed:"), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) .layout(LinkedLayout::Columns) @@ -324,7 +323,7 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext .range(0.0..=MAX_BLEED) .lengths(lengths) .show(ui); - if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.value().copied() { + if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.events.committed().copied() { fields.set("bleed", FieldValue::List([t, b, l, r].map(FieldValue::Number).to_vec())); } if fields.bool("bleedLinked") != Some(linked) { @@ -397,7 +396,8 @@ fn grid_colors_row(setup: DocSetup) -> Param { let mut picked = None; let (mut wells, mut edits) = ([None; 2], [None; 2]); let shown = Stack::new().show(ui, |ui, _| { - picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + picked = + Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).events.committed().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let number = (i + 1).to_string(); @@ -411,7 +411,7 @@ fn grid_colors_row(setup: DocSetup) -> Param { let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); - edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).events.committed().copied(); } }); }); @@ -548,7 +548,7 @@ fn typography() -> Vec { fn language_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext) -> egui::Response { let languages: Vec> = LANGUAGES.iter().map(|(l, _, _)| Entry::new(l.to_string(), l.to_string())).collect(); let current = fields.text("language").unwrap_or_default().to_string(); - let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).value().cloned(); + let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).events.committed().cloned(); if let Some(language) = picked { if let Some(q) = language_quotes(&language) { fields.set("quotes.double", q.double.iter().collect::()); @@ -581,15 +581,18 @@ fn color(mode: ColorMode) -> Vec { #[cfg(test)] mod tests { use craft::theme::Srgba; + use craft::ui::contract::Role; use craft::ui::dialog::{DialogId, HeldOk, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedPropertiesDialog}; - use egui::{Pos2, Rect, vec2}; + use egui::{Key, Modifiers, Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint, cms}; - use vectorcraft_doc::{ColorMode, NodeId}; + use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES}; + use vectorcraft_doc::{ColorMode, NodeId, Quotes}; use vectorcraft_engine::Session; use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; /// The dialog's id. fn id() -> DialogId { @@ -656,6 +659,138 @@ mod tests { app.session.active().unwrap().history.undo.len() } + /// Document Setup open on `tab` over a 200 × 200 document, drawn in the panel harness. + fn setup_panel(tab: &str) -> Panel { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1280.0, 1100.0)); + panel.app().run("file.documentSetup", json!({})).unwrap(); + set(&panel.app(), panel.ctx(), "tab", json!(tab)); + panel.frame(); + panel.frame(); + panel + } + + /// The dialog's values in the panel harness. + fn panel_values(panel: &Panel) -> serde_json::Map { + super::json_map(&fields(&panel.app())) + } + + /// Clicks OK in the panel harness: the dialog closes with the values applied. + fn panel_ok(panel: &mut Panel) { + panel.click("OK"); + let app = panel.app(); + assert!(!is_open(&app), "{}", app.ui.status); + } + + /// A language highlighted in the Language menu changes neither the language nor the quotes, and + /// Escape closes the menu with the dialog open and its values as they were. + #[test] + fn a_highlighted_language_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Type"); + let before = panel_values(&panel); + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted language changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the language and quotes as they were"); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (LANGUAGES[0].0, Quotes::ENGLISH)); + } + + /// A language chosen with Enter brings its quotes, and OK applies both. + #[test] + fn a_language_chosen_with_enter_brings_its_quotes() { + let mut panel = setup_panel("Type"); + let (language, _, quotes) = LANGUAGES[LANGUAGES.len() - 1]; + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let values = panel_values(&panel); + assert_eq!(values["language"], json!(language)); + assert_eq!(values["quotes.double"], json!(quotes.double.iter().collect::())); + assert_eq!(values["quotes.single"], json!(quotes.single.iter().collect::())); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (language, quotes)); + } + + /// A preset highlighted in the Grid Colors menu changes no color, and Escape closes the menu with + /// the dialog open and the grid colors as they were. + #[test] + fn a_highlighted_grid_colors_preset_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted preset changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the grid colors as they were"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + } + + /// A Grid Colors preset chosen with Enter sets both colors, and OK applies them. + #[test] + fn a_grid_colors_preset_chosen_with_enter_sets_both_colors() { + let mut panel = setup_panel("Transparency"); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let medium = GRID_COLOR_PRESETS[1].1; + assert_eq!(dialog_grid(&panel.app()), medium.to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, medium); + } + + /// A hex code typed into a grid color's field changes no color while it is a draft; Tab commits + /// it, and OK applies it. + #[test] + fn a_grid_color_hex_draft_applies_once_committed() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors: 1", Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("123456"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(dialog_grid(&panel.app()), ["#123456", LIGHT[1]].map(hex).to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, ["#123456", LIGHT[1]].map(hex)); + } + + /// A bleed typed into Top changes no side while it is a draft; Tab commits it to the four linked + /// sides, and OK applies them. + #[test] + fn a_bleed_draft_applies_once_committed() { + let mut panel = setup_panel("General"); + let before = panel_values(&panel); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + assert_eq!(panel.value("Top").as_deref(), Some("3"), "the field holds the typed draft"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(super::bleed_of(&fields(&panel.app())), [3.0; 4]); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + + /// A bleed draft still in the focused field when OK is clicked is applied. + #[test] + fn ok_applies_the_focused_bleed_draft() { + let mut panel = setup_panel("General"); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + fn check_source_document(edit_artboards: bool) { let (mut app, ctx) = new_app(); let source = app.session.active().unwrap().uid; From 658151d45cd4472828da889445aa7db428641bac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:08:44 -0800 Subject: [PATCH 03/13] Docs: Outline view row says which layers draw placed documents crossed in Preview mode The Outline view row in docs/ui-parity.md said Preview mode draws linked images and placed documents as before. On screen, a layer whose Preview is off draws in outline in Preview mode, so its placed documents are crossed and its linked images show their crossed frames. A template layer in Outline mode draws them as Preview mode does. The row now says so. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index de4dbdbc48..bceff53d7b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -558,7 +558,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Preview mode and output draw them as before. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | From fda03c81ede18bf75aea82fa0b6b81ada0471be9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:55:53 -0800 Subject: [PATCH 04/13] .ai import: a placed EPS file whose bytes the editing data includes opens as a placed document A .ai file's editing data can include a placed EPS file's bytes between %%BeginDocument: and %%EndDocument. The reader did not read those bytes: in the %AI5_BeginPlace form the placed file showed only the preview the data keeps of it, or an unread placeholder box without one, and in the version 7 form the art the file draws came in as editable paths with a note that placed files weren't read. - The reader keeps those bytes (up to 256 MB) and makes the placed file a placed document of them, in the file's bounding box where the matrix puts it. It draws its art whether or not its file is found, and a native save keeps the bytes. The version 7 form's placed EPS art is no longer editable on open. - A placed file stays as before when its bytes are a DCS file (File > Place makes those linked images), have no bounding box of their own, carry a VectorCraft document (as VectorCraft's EPS export writes), don't read as an EPS file, or belong to a file named .ai or .ait. What reading the bytes warns of is in the open result. - One with a preview that an image variable binds stays the linked image showing its preview, as a placed PDF page does. - The link takes the size and hash of the bytes, so a file found unchanged is neither missing nor modified. - Drawing and the open check each read at most 8 placed EPS files inside one another, so a file whose included files include others opens. The open check draws the placed documents inside the bytes from their previews, and it reads each included file once at each depth. A file nested 12 levels deep opens with at most 8 drawing reads and 72 checks. - File > Package with Copy Fonts reads the type of a placed EPS file, as it reads a placed PDF page's, and of the EPS files it includes in turn, pattern art included. - On %_ lines the %_ that starts each line is taken off. Then one line end is taken off the end of the bytes when another line end comes before it: the one the %%BeginDocument: line ends with when the bytes end with it, otherwise the last one. An LF after a CR is kept with it when the file's first line ends with CRLF. Docs: docs/target-app-parity.md. --- crates/doc/src/placed_document.rs | 44 +++- crates/engine/Cargo.toml | 3 +- crates/engine/src/cmd/package.rs | 39 ++- crates/engine/src/cmd/place/document.rs | 35 ++- crates/engine/src/tests/package.rs | 76 ++++++ crates/engine/src/tests/placed_document.rs | 121 +++++++++ crates/engine/tests/import_fuzz.rs | 37 +++ crates/eps/Cargo.toml | 3 +- crates/eps/src/import.rs | 6 + crates/eps/src/import/ai.rs | 8 +- crates/eps/src/import/ai/read.rs | 37 ++- crates/eps/src/import/ai/read/art.rs | 270 ++++++++++++++++++++- crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ai/read/types.rs | 23 +- crates/eps/src/import/ai/tests.rs | 188 +++++++++++++- crates/eps/src/import/native.rs | 2 + crates/eps/src/import/native/build.rs | 45 +++- crates/eps/src/import/tests_illustrator.rs | 41 +++- crates/eps/src/import/tests_native.rs | 113 +++++++++ crates/eps/src/lib.rs | 12 + docs/target-app-parity.md | 1 + 21 files changed, 1054 insertions(+), 51 deletions(-) diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index d72048dc0a..ef627c6840 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>; static LOADER: OnceLock = OnceLock::new(); +std::thread_local! { + /// Open checks use previews rather than loading placed documents for drawing. + static PREVIEWS_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Restores whether only previews are used when an open check ends, including on unwind. +struct PreviewsOnly(bool); + +impl Drop for PreviewsOnly { + fn drop(&mut self) { + PREVIEWS_ONLY.with(|p| p.set(self.0)); + } +} + +/// Run an open check using placed documents' previews instead of loading their art on this +/// thread. Nested checks keep the scope active until the outer check ends. This prevents an +/// open check and drawing from recursively loading each other's nested files. +pub fn with_previews(check: impl FnOnce() -> T) -> T { + let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true))); + check() +} + /// Register how files are read (the first registration stays). pub fn set_loader(l: Loader) { // Already set: the same loader, registered by another session. @@ -454,8 +476,12 @@ impl Cache { } /// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a -/// placed document from. `None` when it can't be read (or no loader is registered). +/// placed document from. `None` when it can't be read, no loader is registered, or an open check +/// uses [`with_previews`]. pub fn read(p: &PlacedDocument, bytes: &Arc>) -> Option> { + if PREVIEWS_ONLY.with(std::cell::Cell::get) { + return None; + } if let Some(e) = cache().get(&p.key, false, Some(bytes)) { return Some(e); } @@ -738,6 +764,22 @@ mod tests { Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0))) } + /// Nested open checks skip both new and cached art, and restore ordinary reads afterward. + #[test] + fn open_checks_leave_placed_documents_for_drawing_afterward() { + set_loader(stub_loader); + let p = placed("open-check-1"); + let bytes = Arc::new(b"leaf".to_vec()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_some()); + with_previews(|| { + assert!(read(&p, &bytes).is_none()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_none()); + }); + assert!(read(&p, &bytes).is_some()); + } + /// A color-masked image in a placed document's art keeps its masked pixels under the prefixed /// names its resources get. #[test] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index eb751c26d2..4d576cf153 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -122,7 +122,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# The work `.ai` blends take to be checked and made live. +# The work `.ai` blends take to be checked and made live, and how many included EPS open checks +# an open performs. vectorcraft-eps = { workspace = true, features = ["work-count"] } # How many times the symbol list is read to find symbols by name, and how many objects are # measured against locked artboards. diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index e959f126c0..83d9fab4d3 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>; #[cfg(test)] thread_local! { - /// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread. + /// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread. pub(crate) static PAGES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread, /// to keep them in the rewritten copy. @@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { } } -/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); -/// none for other files. +/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at +/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or +/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet { + nested_page_fonts(name, bytes, path, pages, 0) +} + +/// The most placed documents [`page_fonts`] reads inside one another. +const MAX_NESTED_PAGES: usize = 8; + +/// [`page_fonts`], `depth` placed documents in. +fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet { let mut fonts = BTreeSet::new(); - if super::place::document::is_pdf(name, bytes) { + if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) { for &(page, bounding, page_box) in pages { #[cfg(test)] PAGES_READ.with(|c| c.set(c.get() + 1)); - if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) { - fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue }; + fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + if depth + 1 >= MAX_NESTED_PAGES { + continue; + } + let mut inner = Vec::new(); + let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n)); + for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + inner.push(p.clone()); + } + }); + } + for p in inner { + // Only the bytes the art keeps: its own file isn't looked for. + let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue }; + fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1)); } } } @@ -319,7 +344,7 @@ impl<'a> Collector<'a> { // Different linked documents can reuse the same stale absolute path yet // resolve it to distinct local assets. Keep a mapping per document. let mut local = BTreeMap::::new(); - // The fonts of the type on the PDF and `.ai` pages placed linked. + // The fonts of the type on the PDF, `.ai` and EPS pages placed linked. let mut placed_fonts = BTreeSet::new(); let mut placed = BTreeMap::::new(); let linked_files = |doc: &Document| match lookup { diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index a14b89fd25..f24242ed70 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -1,6 +1,7 @@ //! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file //! from a file, with `link`): one locked object showing an artboard of the document, a page of the -//! PDF or the EPS file's art, a [`PlacedDocument`]. +//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing +//! data includes opens as one too, read from those bytes. //! //! The object keeps the file's bytes (in the document's images, like image data) and the link; the //! art it shows is read from them the way placing the file without Link reads it @@ -223,6 +224,27 @@ impl Drop for Reading { } } +std::thread_local! { + /// How many placed documents [`read_document`] is reading inside one another on this thread. + static DRAWING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes. +struct Drawing; + +impl Drawing { + /// `None` when [`MAX_NESTED_READS`] are being read. + fn enter() -> Option { + DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing) + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + DRAWING.with(|d| d.set(d.get().saturating_sub(1))); + } +} + /// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads). fn group(nodes: Vec, clip: Option) -> Node { let mut children: Vec> = nodes.into_iter().map(Arc::new).collect(); @@ -234,11 +256,22 @@ fn group(nodes: Vec, clip: Option) -> Node { /// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents /// ([`vectorcraft_doc::placed_document::set_loader`]). +/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can +/// draw the placed documents in it, whose files can place others. pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { + let _drawing = Drawing::enter()?; + #[cfg(test)] + DOCUMENT_READS.with(|n| n.set(n.get() + 1)); let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?; Some((a.doc, group(a.nodes, a.clip), a.frame)) } +#[cfg(test)] +std::thread_local! { + /// Placed documents read for drawing on this thread, for tests that count work. + pub(crate) static DOCUMENT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `p`'s file read again, while it is the file it was read from (how the document model gets it /// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]). pub(crate) fn read_file_again(p: &PlacedDocument) -> Option> { diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 344b5e436e..f0eeefd810 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() { } } +/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's +/// editing data included, as it reads a placed PDF page's. +#[test] +fn package_reads_a_placed_eps_files_type_for_copy_fonts() { + use cmd::package::PAGES_READ; + use vectorcraft_testkit::ai; + let dir = Folder::new("package-placed-eps-fonts"); + let eps = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let src = dir.file("art/shape.eps"); + write(&src, eps.as_bytes()); + let src = src.replace('\\', "/"); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page)); + let mut s = session(); + open(&mut s, &doc_path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); + save(&mut s, &dir.file("poster.vectorcraft")); + let before = PAGES_READ.with(std::cell::Cell::get); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true})); + assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}"); + let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64); + assert_eq!(listed(&r), 1, "the type's font: {r}"); + + // Type only in an EPS file that the placed one, a legacy-format file, includes in turn. + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let typed = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n"); + let outer = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + {inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the inner file's font: {r}"); + + // The included file is only in a pattern definition, outside the page's nodes. + let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n"); + let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer")); + let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap(); + let pattern = a.doc.pattern("Type").expect("the pattern definition is read"); + let mut placements = 0; + for n in &pattern.art { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file"); + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + placements += 1; + let blob = &a.doc.images[&p.key]; + assert!(!blob.is_proxy()); + assert_eq!(blob.bytes.as_slice(), typed.as_bytes()); + } + }); + } + assert_eq!(placements, 1, "the pattern holds the included file"); + for n in &a.nodes { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_)))); + } + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}"); +} + /// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px, /// with a 2×1 preview) → its path. fn ai_placing(dir: &Folder, pics: &[&str]) -> String { diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3458c5ae37..00f976ab3f 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() { assert_eq!(found, [at], "{r}"); } +/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:` +/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file +/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the +/// bytes, so the copy reopens and draws without the file. +#[test] +fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() { + use vectorcraft_testkit::ai; + let dir = Folder::new("placed-eps-in-ai"); + // The file draws red and the page blue, so each check shows which one drew. + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n"; + let (red, blue) = ([255, 0, 0], [0, 0, 255]); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\ + %%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\ + %AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)); + write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let shown = |s: &Session| { + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true); + let [r, g, b, _] = img.pixel(50, 50); + [r, g, b] + }; + let one = |s: &Session| { + let d = &s.doc().unwrap().doc; + let mut found = vec![]; + d.visit_placed(|n, p| found.push((n.id, p.clone()))); + let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") }; + (*id, p.clone(), d.images[&p.key].clone()) + }; + let mut s = session(); + + let r = open(&mut s, &doc_path); + assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}"); + let (id, p, blob) = one(&s); + assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript")); + assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps")); + let at = bounds(&s, id); + assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}"); + assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s)); + + write(&dir.file("src/shape.eps"), eps.as_bytes()); + let r = open(&mut s, &doc_path); + assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}"); + assert!(near(shown(&s), red)); + + let copy = dir.file("copy.vectorcraft"); + save(&mut s, ©); + std::fs::remove_file(dir.file("src/shape.eps")).unwrap(); + open(&mut s, ©); + let (_, _, blob) = one(&s); + assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved"); + assert!(near(shown(&s), red), "and draw: {:?}", shown(&s)); + + // A file named as PostScript of another kind, or with a name that doesn't say, draws the same. + for name in ["shape.ps", "shape", "shape.dat"] { + let named = place.replace("shape.eps", name); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + open(&mut s, &doc_path); + let (_, p, blob) = one(&s); + assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript")); + assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s)); + } + + // Bytes that can't be read leave the placed file unread: the file is read from its PDF part, + // and the object comes in as what the page draws there. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let r = open(&mut s, &doc_path); + assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s)); +} + +/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep. +fn nested_included_eps(depth: usize) -> String { + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string(); + for _ in 0..depth { + eps = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + [1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + } + eps +} + +/// Open checks and drawing must not recursively multiply each other's work. +#[test] +fn placed_eps_files_included_open_work_is_bounded() { + let dir = Folder::new("placed-eps-open-work"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(12).as_bytes()); + let mut s = session(); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get); + let checks = vectorcraft_eps::included_eps_reads(); + open(&mut s, &path); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings; + let checks = vectorcraft_eps::included_eps_reads() - checks; + eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks"); + // At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8. + // Repeated structural reads share completed checks within each chain. + assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks"); + assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks"); + assert!(drawings > 0 && checks > 0, "both read paths were exercised"); +} + +/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes, +/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them. +#[test] +fn placed_eps_files_included_300_deep_open() { + let dir = Folder::new("placed-eps-300-deep"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(300).as_bytes()); + let mut s = session(); + open(&mut s, &path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); +} + #[test] fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() { let dir = Folder::new("placed-ai-linked"); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 906f26771a..636c19fb36 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4950,6 +4950,37 @@ proptest! { survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and + /// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it), + /// damaged, opened and drawn: their bytes are read as an EPS file when drawn. + #[test] + fn ai_placed_eps_files_with_included_bytes_never_panic( + cut in 0usize..4_000, + edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n"; + let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; + let place = |path: &str, matrix: &str, doc: &str| { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ) + }; + let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect(); + let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested)); + let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body)); + // A session reads placed documents' files when they are drawn. + let _ = vectorcraft_engine::Session::new(); + let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f")); + let mut placed = 0; + whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1)); + prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings)); + let text = mutate_text(&fixture, cut, &edits); + let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f"); + survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?; + } + /// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type /// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai` /// writer writes them) is damaged: read from its editing data alone and beside a page. @@ -6390,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy { "\n%%BeginData: 14 Binary Bytes\n", "\n%%BeginBinary: 99999999999\n", "\n%%BeginData: 3 Hex Lines\n", + // A placed EPS file's bytes included in the data: one drawn, one with a box it can't + // take, one on `%_` lines. + "\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n", + "\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n", + "\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n", + "[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `", "\n%AI5_EndPlace\n", "Xm", "50 -50 -100 -100 5000 -2000 Xm", diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 52413b8c28..6539bf6686 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -9,7 +9,8 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P workspace = true [features] -# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only). +# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests +# (dev-dependencies only). work-count = [] [dependencies] diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 4458f29d2b..38fba94616 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result { Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly)) } +/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own +/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one. +pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> { + Dsc::read(program(bytes).ok()?).bbox +} + /// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data` /// (else what its page prints, as any EPS). pub fn import_with(bytes: &[u8], editing_data: bool) -> Result { diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 149728decf..525eb71f22 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -62,12 +62,12 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color, - read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, + BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, + parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ - BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, - palette, read_beside, read_in, symbols, variables, + BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, + graphic_styles, palette, read_beside, read_in, symbols, variables, }; #[cfg(test)] pub(crate) use style::ART_STYLE_PARSES; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..2e822ec772 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -57,8 +57,13 @@ //! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and //! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`, //! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before -//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document -//! that doesn't end leave the placed file unread. +//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and +//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them, +//! its file found or not; its box is the +//! file's bounding box, which the matrix takes from the file's own space (y up) into art space, +//! as in the version 7 form. +//! Operands of any other shape, a second `` ` `` before `~` or an included document that +//! doesn't end leave the placed file unread. //! - Art with an appearance the format can't write as plain art (several fills or strokes, //! effects, brushes) comes first as that look, drawn (a group, or an image where an effect //! rasterizes it), then the object itself on `%_` @@ -148,7 +153,7 @@ mod raster; mod types; pub(crate) use art::join_and; -use art::preview_png; +use art::{included_document, preview_png}; pub use document::{ BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, symbols, variables, @@ -159,11 +164,12 @@ pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_typ #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; +pub(crate) use types::LINKED_PREVIEWS; pub(crate) use types::MAX_NODES; -pub use types::PlacedPage; -use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; #[cfg(test)] pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; +pub use types::{PlacedEps, PlacedPage}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] @@ -212,6 +218,8 @@ pub struct Structure { pub placed_elsewhere: Vec<(NodeId, Affine)>, /// The placed files that are pages of PDF or `.ai` files. pub placed_pages: Vec, + /// Included EPS files whose previews wait for variable binding before conversion. + pub placed_eps: Vec, /// The live envelopes read from the editing data, by id, with the drawn art each took the place /// of: the importer puts that art back when the layers with the envelopes don't draw as the page. pub envelopes_drawn: Vec<(NodeId, Node)>, @@ -667,6 +675,8 @@ struct Reader<'a> { placed_elsewhere: Vec<(NodeId, Affine)>, /// See [`Structure::placed_pages`]. placed_pages: Vec, + /// See [`Structure::placed_eps`]. + placed_eps: Vec, unread_elsewhere: Vec<(NodeId, Rect)>, /// CMYK samples converted, by value. cmyk_cache: HashMap<[u8; 4], [u8; 3]>, @@ -901,6 +911,7 @@ impl<'a> Reader<'a> { placeholders: vec![], placed_elsewhere: vec![], placed_pages: vec![], + placed_eps: vec![], placed_tails: vec![], unread_elsewhere: vec![], mesh: None, @@ -939,6 +950,15 @@ impl<'a> Reader<'a> { } } + /// The line end just before `doc`, an included document the lexer has just read: the one that + /// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far. + fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> { + let read = self.lex.slice(0, self.lex.offset()); + let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?; + let before = read.get(..at)?; + [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e)) + } + fn run(&mut self) -> Result<(), String> { while let Some(t) = self.lex.next_token() { if self.done { @@ -961,11 +981,14 @@ impl<'a> Reader<'a> { p.preview = preview_png(d); } } - // A placed file's document, included whole: its art isn't read here. When no - // `%%EndDocument` ends it, the placed file isn't read. + // A placed file's document, included whole: its art isn't read here, its bytes are + // kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't + // read. Tok::Document(d) => { + let sep = d.and_then(|d| self.line_end_before(d)); if let Some(p) = self.place.as_mut() { p.broken |= d.is_none(); + p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep)); } } } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 030c70aa51..95606c9ebb 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,17 +2,88 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, - MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, + MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; -use vectorcraft_doc::links::missing_placeholder; +use vectorcraft_doc::PlacedDocument; +use vectorcraft_doc::links::{hash_bytes, missing_placeholder}; use vectorcraft_doc::placed_document::key_for; +use vectorcraft_pdf::is_postscript; + +/// Open-check results by content and nesting depth: the remaining depth changes their warnings. +type EpsChecks = Vec<((String, usize), Option>)>; + +/// The most open-check results kept during one outer check; no file bytes are retained. +const MAX_EPS_CHECKS: usize = 64; + +std::thread_local! { + /// How many included EPS files [`readable_eps`] is reading inside one another on this thread. + static READING_EPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Checks completed during this thread's outer check, including files that do not read. + static EPS_CHECKS: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when +/// this goes. +struct ReadingEps; + +impl ReadingEps { + /// `None` when 8 are being read. + fn enter() -> Option { + READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self) + } +} + +impl Drop for ReadingEps { + fn drop(&mut self) { + READING_EPS.with(|d| d.set(d.get().saturating_sub(1))); + if READING_EPS.with(std::cell::Cell::get) == 0 { + EPS_CHECKS.with_borrow_mut(Vec::clear); + } + } +} + +/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from +/// them (art left out after an operator that isn't read, for one); `None` when they don't read. +/// Past 8 included files read inside one another they count as readable without warnings; drawing +/// reads a bounded number of them in turn. The check uses previews for placed documents, so +/// drawing does not start another chain of checks inside this one. Repeated structural reads +/// share completed checks at the same depth until the outer check ends. +fn readable_eps(bytes: &[u8]) -> Option> { + let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get)); + if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) { + return warnings; + } + let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) }; + #[cfg(any(test, feature = "work-count"))] + crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1)); + let warnings = vectorcraft_doc::placed_document::with_previews(|| { + crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings) + }); + EPS_CHECKS.with_borrow_mut(|c| { + if c.len() >= MAX_EPS_CHECKS { + c.remove(0); + } + c.push((key, warnings.clone())); + }); + warnings +} impl<'a> Reader<'a> { + /// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading + /// them warns of is a warning of this file's too. + fn read_included(&mut self, eps: &[u8]) -> bool { + let Some(warnings) = readable_eps(eps) else { return false }; + for w in warnings { + self.warn(&format!("a placed EPS file: {w}")); + } + true + } + /// A text object (`/AI11Text`): an empty group standing for it, named after its story. pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> { if self.pattern.is_some() { @@ -838,8 +909,9 @@ impl<'a> Reader<'a> { } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that - /// shows the preview the data keeps of it, as a linked image whose file is missing does. One - /// without a preview, a path or a matrix isn't read. + /// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS + /// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]). + /// One without a preview or those bytes, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { // Where a symbol's art puts a placed file's pixels isn't known. if self.symbol.is_some() { @@ -847,11 +919,43 @@ impl<'a> Reader<'a> { self.left_out_of_symbol(); return Ok(()); } + let mut deferred = None; let (m, b, path, png, w, h, folder) = match self.place.take() { Some(Place { broken: true, .. }) => { self.unreadable("placed files", hidden); return Ok(()); } + Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. }) + // A file without a bounding box of its own has its art read on a page of another + // size, which the placed box can't be matched to. + // One named `.ai` or `.ait` is read with the artboard its header gives rather than + // its bounding box, so it isn't read either. Bytes that don't read as an EPS file + // leave it as a placed file without them: its preview, or an unread one. + if !path.is_empty() + && !ai_named(&path) + && is_postscript(&eps) + // A native document's artboard, rather than its bounding box, frames what the loader reads. + && !native_eps(&eps) + && crate::dcs::read(&eps).is_none() + && sane(b) + && b.width() > 0.0 + && b.height() > 0.0 + && eps_box(&eps).is_some() + && self.read_included(&eps) => + { + let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) }; + if let Some((png, w, h)) = preview { + // No image variable binds pattern or brush art, which a reader of its own + // reads: there the placed document goes in at once. + if self.pattern.is_some() { + return self.add_placed_eps(placed, blob, hidden); + } + deferred = Some((placed, blob)); + (m, b, path, png, w, h, folder) + } else { + return self.add_placed_eps(placed, blob, hidden); + } + } Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => { (m, b, path, png, w, h, folder) } @@ -902,6 +1006,10 @@ impl<'a> Reader<'a> { .filter(|a| a.as_coeffs().iter().all(|v| v.is_finite())); let xf = self.space() * m * over_file; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + // An included EPS file is still read when its preview can't be placed. + if let Some((placed, blob)) = deferred { + return self.add_placed_eps(placed, blob, hidden); + } self.unreadable("placed files", hidden); return Ok(()); } @@ -911,7 +1019,11 @@ impl<'a> Reader<'a> { let key = linked_key(&blob, &path); let fresh = !self.doc.images.contains_key(&key); self.doc.images.entry(key.clone()).or_insert(blob); - self.warn(LINKED_PREVIEWS); + // An included EPS file shows its preview only when an image variable binds it, which the + // importer notes then. + if deferred.is_none() { + self.warn(LINKED_PREVIEWS); + } let id = NodeId(self.doc.peek_next_id()); if let Some(shift) = elsewhere && self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE @@ -928,7 +1040,11 @@ impl<'a> Reader<'a> { self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth }); let mut link = LinkInfo::new(path); link.relative = folder.and_then(|f| relative_path(&f, link.name())); - self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden) + self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?; + if let Some((placed, blob)) = deferred { + self.placed_eps.push(PlacedEps { id, placed, blob }); + } + Ok(()) } /// The dictionary `o` after the placed file just read: with a page or a box in it, that file is @@ -962,6 +1078,54 @@ impl<'a> Reader<'a> { self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size }); } + /// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space, + /// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into + /// art space by `m`: a placed document showing that box, which keeps the bytes and draws them + /// whether or not its file is found. Its link has the size and hash of those bytes, so a file + /// found unchanged isn't reported as modified. The placed document has no preview, so a save + /// keeps the bytes. Not read without that box. + fn placed_eps(&mut self, m: Affine, path: String, eps: Vec, folder: Option, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> { + let Some(b) = eps_box(&eps) else { + self.unreadable("placed files", hidden); + return None; + }; + // The placed document's box runs down from the file's top left corner. + let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.unreadable("placed files", hidden); + return None; + } + let hash = hash_bytes(&eps); + let key = key_for(&hash, 1, false, PageBox::Crop); + let mut link = LinkInfo::new(path); + link.relative = folder.and_then(|f| relative_path(&f, link.name())); + (link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash)); + let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() }; + let placed = PlacedDocument { + link, + key, + bounding: false, + page_box: PageBox::Crop, + width: b.width(), + height: b.height(), + xf, + placement: Default::default(), + }; + Some((placed, blob)) + } + + /// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key. + /// Placements of the same bytes share one blob. + fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> { + self.doc.images.entry(placed.key.clone()).or_insert(blob); + let gs = self.gs.clone(); + let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs); + node.opacity = gs.opacity; + node.blend = gs.blend; + node.knockout_shape = gs.knockout_shape; + self.add(node, hidden) + } + pub(super) fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 { self.warnings.push(w.to_string()); @@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> { } } +/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and +/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that +/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's +/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the +/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the +/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's +/// first line ends with CRLF: that CRLF is one line end of the file's. +pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec { + let mut out = if hidden { unhidden(doc) } else { doc.to_vec() }; + let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n"); + let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2)); + let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n"); + let added = sep + .filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n")) + .or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e))) + .map(|e| out.len() - e.len()); + if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) { + out.truncate(n); + } + out +} + +/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its +/// own space; `None` without one, or when it is empty or out of range. +fn eps_box(eps: &[u8]) -> Option { + let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?; + Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0) +} + +/// Does `eps` have a native document's begin comment line, without reading that document? +fn native_eps(eps: &[u8]) -> bool { + eps.split(|b| *b == b'\r' || *b == b'\n') + .any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes())) +} + +/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case? +fn ai_named(path: &str) -> bool { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait")) +} + +/// `doc` without the `%_` that starts each of its lines. +fn unhidden(doc: &[u8]) -> Vec { + let mut out = Vec::with_capacity(doc.len()); + let mut line_start = true; + let mut i = 0; + while let Some(&b) = doc.get(i) { + if line_start && doc.get(i..i + 2) == Some(b"%_") { + i += 2; + line_start = false; + continue; + } + out.push(b); + line_start = b == b'\r' || b == b'\n'; + i += 1; + } + out +} + /// A placed file's path relative to the document's folder (`/` separators): its relative `folder` /// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the /// document's own folder). `None` when the folder is absolute or holds control characters, or @@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String { [rest @ .., last] => format!("{} and {last}", rest.join(", ")), } } + +#[cfg(test)] +mod tests { + use super::{ReadingEps, readable_eps}; + + /// Check results keep their warnings and failures, respect depth, and expire with the outer check. + #[test] + fn included_eps_checks_keep_the_depth_limit_and_expire() { + let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n"; + { + let _outer = ReadingEps::enter().unwrap(); + let warnings = readable_eps(eps).unwrap(); + assert!(!warnings.is_empty(), "a partly read file still passes, with warnings"); + let reads = crate::included_eps_reads(); + assert_eq!(readable_eps(eps).unwrap(), warnings); + assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again"); + let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect(); + assert!(!limits.is_empty()); + assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read"); + drop(limits); + assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings"); + let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(readable_eps(broken).is_none()); + let reads = crate::included_eps_reads(); + assert!(readable_eps(broken).is_none()); + assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again"); + } + let _outer = ReadingEps::enter().unwrap(); + let reads = crate::included_eps_reads(); + assert!(readable_eps(eps).is_some()); + assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded"); + } +} diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 8492cca6f0..e63e670b7f 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1441,6 +1441,7 @@ impl<'a> Reader<'a> { placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, placed_pages: self.placed_pages, + placed_eps: self.placed_eps, envelopes_drawn: self.envelopes_drawn, warped_type: super::super::envelope::WarpedType { looks: self.warped_type, diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index a155d9f505..27eb8a8576 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -312,6 +312,9 @@ pub(super) struct Place { pub(super) folder: Option, /// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end. pub(super) folder_at: Option, + /// The file's bytes, when the data includes them between `%%BeginDocument:` and + /// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]). + pub(super) document: Option>, /// Its `` ` `` was read. pub(super) ticked: bool, /// It began on a `%_` line, in a hidden object or on a layer that doesn't show. @@ -361,8 +364,26 @@ pub struct PlacedPage { pub size: (f64, f64), } +/// An included EPS whose linked preview becomes a placed document after variable binding. +#[derive(Debug)] +pub struct PlacedEps { + /// The linked image. + pub id: NodeId, + /// The document that replaces the image unless an image variable binds it. + pub placed: vectorcraft_doc::PlacedDocument, + /// The EPS bytes stored under the placed document's key only when it replaces the image. + pub blob: vectorcraft_doc::ImageBlob, +} + +/// The largest placed file kept from the bytes the data includes (the largest file File › Place +/// reads). +pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20; + +/// The type a placed EPS file's bytes are stored with. +pub(super) const EPS_MIME: &str = "application/postscript"; + /// What the open result says of placed files: they show the preview the file keeps of them. -pub(super) const LINKED_PREVIEWS: &str = +pub(crate) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; /// What the open result says of linked images the data keeps no pixels of (`XF`): they show a diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..b4d56c9e08 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -12,7 +12,9 @@ use super::*; /// [`super::read`] as an EPS reads it. fn read(data: &[u8]) -> Result { - super::read(data, true) + let mut r = super::read(data, true)?; + super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps); + Ok(r) } /// Editing data: header comments (crop marks 0 0 200 100), then `body`. @@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() { assert_eq!(relative_of(&cut), None); } +/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`. +fn red_eps(w: u32, h: u32, eol: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}") + .into_bytes() +} + +/// `data` with the first `from` in it replaced by `to`. +fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec { + let at = data.windows(from.len()).position(|w| w == from).unwrap(); + [&data[..at], to, &data[at + from.len()..]].concat() +} + +/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the +/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and +/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`). +fn placed_eps_file(doc: &[u8]) -> Vec { + let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, ""); + let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0"); + let data = splice(&data, b"\r()\r", b"\r(src/)\r"); + let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0"); + let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat(); + splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included) +} + +/// The one placed document of `data`, with the blob its key names. +fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) { + let r = read(data).unwrap(); + let a = art(&r.doc); + let [n] = &a[..] else { panic!("one object: {a:?}") }; + let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) }; + let blob = r.doc.images[&p.key].clone(); + ((**n).clone(), (**p).clone(), blob, r) +} + +#[test] +fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() { + let eps = red_eps(80, 50, "\n"); + let (_, p, blob, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds"); + assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true)); + assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps"))); + assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps)))); + assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop)); + assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings); + // The matrix takes the file's own space (y up) into art space; the box's top left corner is the + // file's (0, 50). + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] { + let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file)); + assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}"); + } +} + +#[test] +fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() { + let eps = red_eps(80, 50, "\n"); + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let section = + [&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat(); + let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion); + // The placed document has no preview, so a save keeps its bytes. + let (_, _, blob, _) = one_placed(&data); + assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true)); + // The same bytes placed twice share the blob. + let one = placed_eps_file(&eps); + let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r"); + let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()]; + let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat()); + let r = read(&twice).unwrap(); + let a = art(&r.doc); + let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect(); + assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}"); + assert!(r.doc.images[&keys[0]].proxy.is_none()); +} + +#[test] +fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() { + let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments"); + let (_, p, _, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!((p.width, p.height), (79.0, 49.0)); + // The box's top left corner is the file's (0.5, 49.5), where the matrix puts it. + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5)); + assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}"); +} + +#[test] +fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() { + let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0"); + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); +} + +#[test] +fn an_included_eps_files_own_last_line_end_is_kept() { + // The data's line end after the file's own is taken off; a single one is the file's. + let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n"); + for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] { + let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}"); + } + // The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose + // lines end with CR isn't read as a CRLF of the file's. + let data = + splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument"); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r"); + // A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own. + let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf); +} + +#[test] +fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() { + let eps = red_eps(80, 50, "\r"); + let hidden = hide_placed(&placed_eps_file(&eps)); + let (_, _, blob, _) = one_placed(&hidden); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off"); + // The line end added before `%%EndDocument` on a `%_` line of its own. + let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument")); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off"); +} + +#[test] +fn an_included_postscript_file_named_as_an_ai_file_stays_unread() { + // Read through its name with the artboard its header gives, not the box the placed one shows. + for name in ["shape.ai", "SHAPE.AIT"] { + let mut data = placed_eps_file(&red_eps(80, 50, "\n")); + while data.windows(9).any(|w| w == b"shape.eps") { + data = splice(&data, b"shape.eps", name.as_bytes()); + } + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread); + } +} + +#[test] +fn included_eps_with_a_native_document_leaves_the_placed_file_unread() { + // Even unreadable native data leaves the file unread: the loader can read an artboard + // larger than the EPS bounding box, which would shrink and offset the art when placed. + for eol in ["\n", "\r", "\r\n"] { + let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF"); + let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes()); + let r = read(&placed_eps_file(&eps)).unwrap(); + assert!( + !art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), + "included EPS with a native document must stay on the fallback path" + ); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + +#[test] +fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() { + // A DCS file, which the placed document reader doesn't read (File › Place makes it a linked + // image), stays unread too. + let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n"; + // An EPS file without a bounding box, whose art is read on a page of another size, stays unread. + let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n"; + // An EPS file whose program doesn't read draws nothing, so it stays unread too. + let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n"; + for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] { + let r = read(&placed_eps_file(bytes)).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + #[test] fn hidden_placed_file_ended_by_comment_stays_hidden() { let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, "")); @@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { NodeKind::Group { .. } => "group", NodeKind::Path { .. } => "path", NodeKind::Image(_) => "image", + NodeKind::PlacedDocument(_) => "placed", _ => "other", }) .collect() @@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { #[test] fn version7_placed_file_included_whole_is_read() { // The included document's operators, a `~`, a nested document and counted data in it aren't - // the editing data's. - let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\ + // the editing data's (the file defines them, so its program reads). + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\ %%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); let r = placed_read7(true, &body).unwrap(); - assert_eq!(art_kinds(&r.doc), ["path"]); - assert_unread(&r, "placed files"); + // A placed document of the file's bytes. + assert_eq!(art_kinds(&r.doc), ["placed"]); + let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() }; + assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes()); + assert!(r.unread.is_empty(), "{:?}", r.unread); // One that doesn't end leaves the layer without its end. let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n"); assert!(placed_read7(true, &cut).is_err()); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index dad13c569f..df97114506 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -50,6 +50,8 @@ mod slots; #[cfg(test)] pub(crate) use build::READ_AFRESH; #[cfg(test)] +pub(super) use build::placed_documents; +#[cfg(test)] use build::{Frame, MADE, prune_unseen}; pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1ef5706e68..d5d7dbc1c8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -334,6 +334,7 @@ pub(super) fn build_weighing( placeholders, placed_elsewhere, placed_pages, + placed_eps, envelopes_drawn, styles_read, text_paints, @@ -644,33 +645,50 @@ pub(super) fn build_weighing( } doc.limit_depth_noting(&mut notes); bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); - placed_documents(&mut doc, &placed_pages); + if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { + notes.push(ai::LINKED_PREVIEWS.to_string()); + } if small.is_some() { scale_read_document(&mut doc, unit, styles_read, symbols_own_size); } Ok((doc, notes)) } -/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed -/// documents of their page and box, over the same place, each showing the same preview until its -/// file is read. An image bound to an image variable stays a linked image, the object an image -/// variable binds. -fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) { - if pages.is_empty() { - return; +/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed +/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included +/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds. +/// Returns whether an included EPS file stays a linked image that way, showing its preview. +pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool { + if pages.is_empty() && eps.is_empty() { + return false; } let vars = &doc.variables; let image_bound = |id: &NodeId| { vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image))) }; let pages: std::collections::HashMap = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect(); + let previews = eps.iter().any(|p| image_bound(&p.id)); + let eps: std::collections::HashMap = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect(); for layer in &mut doc.layers { - to_placed_documents(Arc::make_mut(layer), &pages); + to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images); } + previews } /// [`placed_documents`] in `n` and everything in it. -fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap) { +fn to_placed_documents( + n: &mut Node, + pages: &std::collections::HashMap, + eps: &std::collections::HashMap, + images: &mut std::collections::BTreeMap, +) { + if let Some(eps) = eps.get(&n.id) + && let NodeKind::Image(im) = &n.kind + && im.link.is_some() + { + images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone()); + n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone())); + } // A box too small to take the image's pixels to (its transform not finite) keeps the linked image. if let Some(page) = pages.get(&n.id) && let NodeKind::Image(im) = &n.kind @@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap>], doc: &Document, placed: &[(N } /// Where the placed files that show in `nodes` are: the linked images the editing data's reader -/// makes of them. +/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes. fn placed_files(nodes: &[Arc], out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { match &n.kind { NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()), + NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()), _ => { if let Some(c) = n.children() { placed_files(c, out); diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 4cae36ac52..2cbcde3551 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -56,6 +56,19 @@ fn tree(nodes: &[Arc]) -> String { nodes.iter().map(one).collect::>().join(" ") } +/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its +/// bounding box (the engine registers the app's own loader). +fn draw_placed_eps() { + fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> { + let mut doc = import(bytes).ok()?.document; + let frame = doc.artboards.first()?.rect; + let layers = std::mem::take(&mut doc.layers); + let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect(); + Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame)) + } + vectorcraft_doc::placed_document::set_loader(load); +} + fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec) { let r = import(&ai(header, ugroup, body)).unwrap(); (tree(r.document.layers[0].children().unwrap()), r.warnings) @@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar } /// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file -/// included whole: the layers come in, the placed file as the art the page draws in its box. +/// included whole: the layers come in, the placed file as a placed document of its bytes in its box. #[test] fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { + draw_placed_eps(); // `` ` `` takes the file's user space into the page's (`concat`); `~` restores it. let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; @@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); assert_eq!(names, ["Back"], "{:?}", r.warnings); let art = r.document.layers[0].children().unwrap(); - assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings); + let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) }; + assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes"); + assert_eq!(p.link.path, "art.eps"); // The file's box, moved by the matrix: 20 40 60 70 on the page, y up. let bounds = art[1].geometric_bounds().unwrap(); assert!( (bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01, "{bounds:?}" ); - assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed +/// file's, so the layers come in with it as a placed document. +#[test] +fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() { + draw_placed_eps(); + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ + /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + /Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\n%%EOF\n"; + let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10)); + let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog")); + let r = import(file.as_bytes()).unwrap(); + let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Back"], "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings); } /// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 0d69d248e5..e55d2fe4da 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8358,6 +8358,119 @@ fn a_placed_pdf_page_bound_to_an_image_variable_stays_a_linked_image() { assert_eq!(d.variables.objects_of("v_file"), [n.id], "{notes:?}"); } +/// An included EPS keeps its linked preview and binding when an image variable binds it. +#[test] +fn a_placed_eps_with_a_preview_preserves_its_image_variable_binding() { + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node}; + let declared = vec![xml_node( + 1, + "variable", + XmlValue::Str(""), + &[("trait", XmlValue::Str("fileref")), ("varName", XmlValue::Unicode("v_file")), ("docRef", XmlValue::Raw("/XMLUIDREF : (eps) ;"))], + &[], + )]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n\ + %AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n\ + %_/ArtDictionary :\n%_/XMLUID : (eps) ; (AI10_ArtUID) ,\n%_;\n%_\n", + "\x7f\0\0\0".repeat(4) + ); + let art = layer("Jig", true, &place); + let (bound, notes) = crate::ai_alone(&private(&native(&(library + &art)))).unwrap(); + let n = &bound.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + assert_eq!(bound.images[&im.key].mime, "image/png"); + assert!(bound.images.values().all(|b| b.mime != "application/postscript")); + assert_eq!(bound.variables.objects_of("v_file"), [n.id], "{notes:?}"); + assert!(!notes.iter().any(|n| n.contains("variable bindings")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "the preview it shows is noted: {notes:?}"); + let (unbound, notes) = crate::ai_alone(&private(&native(&art))).unwrap(); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "it draws its bytes: {notes:?}"); + let converted = &unbound.layers[0].children().unwrap()[0]; + assert_eq!(converted.id, n.id); + let NodeKind::PlacedDocument(p) = &converted.kind else { panic!("{:?} {notes:?}", converted.kind) }; + assert_eq!(&*unbound.images[&p.key].bytes, eps.as_bytes()); + assert!(unbound.images[&p.key].proxy.is_none()); +} + +/// What reading an included EPS file warns of, such as art left out, is in the open result. +#[test] +fn a_placed_eps_read_in_part_warns_of_what_it_leaves_out() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 30 30 rectfill\n0 0 60 60 nosuchoperator\n%%EOF\n"; + let own = crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).unwrap().warnings; + assert!(!own.is_empty(), "the file read alone warns"); + for place in [placed_eps_with_preview(eps), placed_eps_with_preview(eps).replace(&placed_eps_preview(), "")] { + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::PlacedDocument(_)), "{:?} {notes:?}", n.kind); + for w in &own { + assert!(notes.contains(&format!("a placed EPS file: {w}")), "{w}: {notes:?}"); + } + } +} + +/// An unreadable included EPS keeps the preview that the linked image can show. +#[test] +fn a_placed_eps_with_an_unreadable_program_keeps_its_preview() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).is_err()); + let place = placed_eps_with_preview(eps); + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + let preview = &d.images[&im.key]; + assert_eq!(preview.mime, "image/png"); + assert_eq!(preview.proxy.as_deref(), Some(&*preview.bytes)); + assert!(d.images.values().all(|b| b.mime != "application/postscript")); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A pattern's included EPS keeps its bytes without waiting for image variable binding. +#[test] +fn a_placed_eps_with_a_preview_in_a_pattern_keeps_its_bytes() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = placed_eps_with_preview(eps); + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{place}E\n%AI3_EndPattern\n"); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert_eq!(art.len(), 1, "{art:?} {notes:?}"); + let NodeKind::PlacedDocument(p) = &art[0].kind else { panic!("{art:?} {notes:?}") }; + assert_eq!(&*d.images[&p.key].bytes, eps.as_bytes()); + assert_eq!(d.images[&p.key].mime, "application/postscript"); + assert!(d.images[&p.key].proxy.is_none()); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); + + // One whose bytes can't be read keeps its preview there too. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 nosuchoperator\n%%EOF\n"; + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{}E\n%AI3_EndPattern\n", placed_eps_with_preview(broken)); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert!(matches!(&art[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.is_some())), "{art:?} {notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A placed EPS file at `/files/shape.eps` whose bytes `eps` the data includes, with a 2 × 2 preview. +fn placed_eps_with_preview(eps: &str) -> String { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n{}~\n%AI5_EndPlace\n", + placed_eps_preview() + ) +} + +/// The 2 × 2 preview of [`placed_eps_with_preview`]. +fn placed_eps_preview() -> String { + format!("%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n", "\x7f\0\0\0".repeat(4)) +} + #[test] fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() { // A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 6f5ff3d7a2..1abfd0210e 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -61,6 +61,18 @@ pub use print::{PrintFonts, PrintJob, PrintPage, print}; use vectorcraft_doc::Document; use vectorcraft_geom::{Point, Rect}; +#[cfg(any(test, feature = "work-count"))] +std::thread_local! { + /// Included EPS files parsed by open checks on this thread. + pub(crate) static INCLUDED_EPS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Included EPS files parsed by open checks on this thread, for tests that count work instead of timing it. +#[cfg(any(test, feature = "work-count"))] +pub fn included_eps_reads() -> usize { + INCLUDED_EPS_READS.with(std::cell::Cell::get) +} + /// The PostScript language level the file needs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub enum Level { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8f9868203d..bc7a0f541a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,6 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 7d5794d0e4f88c72893605c90dabc2e2dbe80b29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:29:20 -0800 Subject: [PATCH 05/13] .ai import: envelopes and warped art spend a difference budget on each page Live envelopes, warped type and warped images were held to one shared difference budget measured only on the first artboard. A file whose PDF part shows a later artboard, a page cropped to the art, or more than one artboard could then take more difference on that page than the page check allows, and open from its PDF part instead of its layers. Each page the art may be compared with (every artboard, and the art's bounding box when it is not one of them) now has its own half share of the page check's allowance. An envelope on a later artboard that draws away from its drawn art over that artboard's page keeps its drawn art, where before it opened live. Art on no such page is not held to a page. Repeated pages are held once, the page list is worked out once per change of artboards, and an import makes at most 1,024 comparisons with pages; art that needs more keeps its drawn art. --- crates/eps/src/import/ai/envelope.rs | 119 ++++++++++++++------ crates/eps/src/import/ai/read.rs | 7 ++ crates/eps/src/import/ai/read/containers.rs | 6 +- crates/eps/src/import/ai/read/document.rs | 41 +++++-- crates/eps/src/import/ai/read/ops.rs | 11 +- crates/eps/src/import/ai/tests.rs | 101 +++++++++++++++-- 6 files changed, 228 insertions(+), 57 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index d9a14a0239..6ff37bec92 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -59,6 +59,9 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str { pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. pub(crate) const MAX_CHECKED: usize = 256; +/// The most comparisons with pages those checks make in one import, one for each page an object +/// is on ([`drawn_alike`]); an object that needs more keeps its drawn art. +pub(crate) const MAX_PAGE_COMPARISONS: usize = 4 * MAX_CHECKED; /// The most strokes with dashes aligned to corners one import draws to check against their drawn /// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks. pub(crate) const MAX_DASH_CHECKS: usize = 256; @@ -664,13 +667,31 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt } /// The differences from their drawn art that the live envelopes and warped type of one import may -/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows -/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part -/// instead. +/// add up to on each page the art may be compared with, as shares of that page drawn as the page +/// check draws it: half of what that check allows ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), +/// so they never make the file open from its PDF part instead. Each page has its own share. #[derive(Debug, Default)] pub(crate) struct Spent { - pub(super) any: f64, - pub(super) solid: f64, + /// Each page with the shares of it spent so far: of pixels that differ at all, and of those + /// whose neighbors all differ too. + pub(super) pages: Vec<(Rect, f64, f64)>, + /// How many comparisons with pages have been made ([`MAX_PAGE_COMPARISONS`]). + pub(super) compared: usize, +} + +impl Spent { + /// The shares of `page` spent so far. + pub(super) fn on(&self, page: Rect) -> (f64, f64) { + self.pages.iter().find(|(p, ..)| *p == page).map_or((0.0, 0.0), |&(_, any, solid)| (any, solid)) + } + + /// Set the shares of `page` spent so far. + fn set(&mut self, page: Rect, any: f64, solid: f64) { + match self.pages.iter_mut().find(|(p, ..)| *p == page) { + Some(spent) => *spent = (page, any, solid), + None => self.pages.push((page, any, solid)), + } + } } /// A text object read with a Warp. @@ -738,7 +759,8 @@ pub struct WarpedType { pub(super) envelopes: Vec, pub(super) checks: usize, pub(super) spent: Spent, - pub(super) page: Option, + /// The pages the art may be compared with, each with its own share of the budget ([`Spent`]). + pub(super) pages: Vec, /// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too. pub(super) type_clips: HashMap, /// The envelopes of type that may open live in layers built without a page, by their place @@ -884,7 +906,7 @@ impl WarpedType { let (id, layer) = (doc.alloc_id(), doc.alloc_id()); let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page.filter(|_| shown.contains(&drawn)); + let pages: Vec = if shown.contains(&drawn) { self.pages.clone() } else { vec![] }; let mut alike = None; // In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again // moved onto that art ([`moved_onto`]), after every other way. @@ -917,7 +939,7 @@ impl WarpedType { let shared = Shared { patterns: &doc.patterns, images: &doc.images }; let mut live_one = envelope.clone(); (live_one.visible, live_one.opacity) = (true, 1.0); - if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + if drawn_alike(&live_one, &plain, layer, &shared, &pages, &mut self.spent) { alike = Some(envelope); break; } @@ -942,7 +964,8 @@ impl WarpedType { /// budget has no check left for) with that look: `made` gives the text object a slot became. A /// frame in `threaded` stays type, since the frames of a thread share one story. A replaced /// object's box goes back into the comparisons with the page (out of `restyled`), and only what - /// `doc` shows counts against the page's share of the budget. Returns how many were replaced. + /// `doc` shows counts against the share of the budget of each page it is on. Returns how many + /// were replaced. pub(crate) fn settle( self, doc: &mut Document, @@ -950,7 +973,7 @@ impl WarpedType { threaded: &BTreeSet, restyled: &mut Vec, ) -> usize { - let Self { looks, mut checks, mut spent, page, .. } = self; + let Self { looks, mut checks, mut spent, pages, .. } = self; let mut shown_ids = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids)); let mut replaced = 0; @@ -965,7 +988,8 @@ impl WarpedType { let (mut shown, mut plain) = (text.clone(), look.clone()); (shown.visible, shown.opacity) = (true, 1.0); (plain.visible, plain.opacity) = (true, 1.0); - alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent); + let on: &[Rect] = if shown_ids.contains(&id) { &pages } else { &[] }; + alike = warped_alike(&shown, &plain, layer, &shared, on, &mut spent); } if alike { continue; @@ -1032,23 +1056,24 @@ pub(super) fn warps(appearance: &Appearance) -> bool { } /// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the -/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the -/// file has one), they differ little enough that with the differences in `spent` the page check -/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a -/// layer id no other node has. -pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { - alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) +/// pixels either inks differ and fewer still where a whole patch differs, and, on each of `pages` +/// they are on (the pages the art may be compared with), they differ little enough that with the +/// differences `spent` holds for that page the page check still takes the layers' art (they are +/// added to `spent` when they do on every one). Both are drawn on `layer`, a layer id no other node +/// has. +pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { + alike_within(live, drawn, live.visual_bounds(), layer, shared, pages, spent) } /// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach /// past its own box. -pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live); - alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent) + alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, pages, spent) } /// [`drawn_alike`], with `live` measured as `reach`. -fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { // Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted): // both draw nothing, so they draw alike and add nothing to what the page check sees. Their // shapes aren't compared. Art that paints, however faintly, is compared as before. @@ -1069,21 +1094,31 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s if share(solid) > MAX_SOLID || share(any) > MAX_ANY { return false; } - let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true }; - // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the - // page's longer side). - let on_page = region.intersect(page); - let scale = compare_scale(page); - if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { - return true; + let mut added = vec![]; + for &page in pages.iter().filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) { + // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along + // the page's longer side). + let on_page = region.intersect(page); + let scale = compare_scale(page); + if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { + continue; + } + if spent.compared >= MAX_PAGE_COMPARISONS { + return false; + } + spent.compared += 1; + let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; + let pixels = (page.width() * scale * page.height() * scale).max(1.0); + let (was_any, was_solid) = spent.on(page); + let (any, solid) = (was_any + any as f64 / pixels, was_solid + solid as f64 / pixels); + if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { + return false; + } + added.push((page, any, solid)); } - let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; - let pixels = (page.width() * scale * page.height() * scale).max(1.0); - let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels); - if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { - return false; + for (page, any, solid) in added { + spent.set(page, any, solid); } - *spent = Spent { any, solid }; true } @@ -1161,7 +1196,7 @@ mod tests { #[test] fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() { let shared = Shared { patterns: &[], images: &BTreeMap::new() }; - let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default()); + let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, &[], &mut Spent::default()); let (none, other_none) = (square_node(1, None), square_node(2, None)); assert!(alike(&none, &other_none)); let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02))); @@ -1169,6 +1204,22 @@ mod tests { assert!(!alike(&none, &square_node(2, Some(1.0)))); } + /// Each page an object is on takes one of the import's comparisons with pages. With none left, + /// art on a page keeps its drawn art, and art on no page needs none. + #[test] + fn comparisons_with_pages_stop_at_their_limit() { + let shared = Shared { patterns: &[], images: &BTreeMap::new() }; + let (live, drawn) = (square_node(1, Some(1.0)), square_node(2, Some(1.0))); + let (page, other) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 60.0, 60.0)); + let mut spent = Spent { compared: MAX_PAGE_COMPARISONS - 2, ..Default::default() }; + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[page, other], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + assert!(!drawn_alike(&live, &drawn, NodeId(999), &shared, &[page], &mut spent)); + let off = Rect::new(500.0, 500.0, 600.0, 600.0); + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[off], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + } + /// "AVA" at 40 points, at (10, 60). fn type_node(id: u64, style: CharStyle) -> Node { Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..3bb571df07 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -472,6 +472,10 @@ struct BrushesKept { bending: HashMap, } +/// What the pages the art may be compared with are worked out from: the move into the document, +/// the number of artboards, the first artboard and the art's bounding box. +type PageSources = (Option, usize, Option, Option); + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -604,6 +608,8 @@ struct Reader<'a> { envelope_checks: usize, /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). envelope_spent: super::envelope::Spent, + /// [`Self::pages_in_doc`] as last worked out, with what it was worked out from. + page_cache: Option<(PageSources, Arc<[Rect]>)>, /// How many more strokes with dashes aligned to corners this import may draw to check /// ([`super::MAX_DASH_CHECKS`]). dash_checks: usize, @@ -877,6 +883,7 @@ impl<'a> Reader<'a> { envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), + page_cache: None, dash_checks: super::MAX_DASH_CHECKS, defs_only: false, warped_type: Vec::new(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 2a14ce1c24..ad97b7b47b 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -917,6 +917,7 @@ impl<'a> Reader<'a> { } let Some(p) = self.envelopes.pop() else { return }; let scale = self.space_scale(); + let pages = self.pages_in_doc(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -959,8 +960,7 @@ impl<'a> Reader<'a> { (shown.visible, shown.opacity) = (true, 1.0); let mut plain = drawn.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page_in_doc(); - let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); // In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked // again moved onto that art. if !alike @@ -969,7 +969,7 @@ impl<'a> Reader<'a> { { self.envelope_checks -= 1; (envelope.kind, shown.kind) = (kind.clone(), kind); - alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); } if !alike { self.warn(crate::import::ai::envelope::DRAWN); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 8492cca6f0..544c6725cc 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -55,6 +55,22 @@ impl AiArtboard { } } +/// The pages the art may be compared with in the document's space, art space being moved there by +/// `to_doc` (none before the art starts): each of `artboards` (else `first`, the first artboard), +/// then `art_box`, the art's bounding box. A page that is an earlier one to half a point is left out. +fn pages_of(to_doc: Option, artboards: &[AiArtboard], first: Option, art_box: Option) -> Vec { + let Some(to_doc) = to_doc else { return vec![] }; + let boards: Vec = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() }; + let mut pages: Vec = vec![]; + for page in boards.into_iter().chain(art_box).map(|r| to_doc.transform_rect_bbox(r)) { + let same = |p: &Rect| [p.x0 - page.x0, p.y0 - page.y0, p.x1 - page.x1, p.y1 - page.y1].iter().all(|d| d.abs() <= 0.5); + if !pages.iter().any(same) { + pages.push(page); + } + } + pages +} + /// The number of entry `key` in `o` when it is written as one finite number of the type `ty` /// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`. fn typed(o: &Obj, key: &str, ty: &str) -> Option { @@ -923,10 +939,21 @@ impl<'a> Reader<'a> { self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board()) } - /// The page the art is compared with in the document's space, once the art has started. - pub(super) fn page_in_doc(&self) -> Option { - let board = self.first_board().or_else(|| self.bbox_board())?; - Some(self.to_doc?.transform_rect_bbox(board)) + /// Every page the art may be compared with, in the document's space, once the art has started: + /// each artboard (else the first artboard [`Self::first_board`] gives), since a page of a file's + /// PDF part can show any of them, and the art's bounding box ([`Self::bbox_board`]), which a page + /// cropped to the art and the page of the legacy format show ([`pages_of`]). Worked out again + /// only when the artboards, the art's box or the move into the document have changed. + pub(super) fn pages_in_doc(&mut self) -> Arc<[Rect]> { + let sources = (self.to_doc, self.artboards.len(), self.first_board(), self.bbox_board()); + if let Some((from, pages)) = &self.page_cache + && *from == sources + { + return pages.clone(); + } + let pages: Arc<[Rect]> = pages_of(sources.0, &self.artboards, sources.2, sources.3).into(); + self.page_cache = Some((sources, pages.clone())); + pages } /// The page of a file that says nothing of its artboard (the legacy format as other apps write @@ -1239,8 +1266,8 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); - // Before the artboards are taken below: the page is the first artboard's. - let page = self.page_in_doc(); + // Before the artboards are taken below: the pages are the artboards' and the art's box. + let pages = self.pages_in_doc(); self.check_symbols(); self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); @@ -1447,7 +1474,7 @@ impl<'a> Reader<'a> { envelopes: self.typed_envelopes, checks: self.envelope_checks, spent: self.envelope_spent, - page, + pages: pages.to_vec(), alone: None, type_clips: self.type_clips, }, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index fcdffd4580..362425ec72 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -787,7 +787,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); - let page = self.page_in_doc(); + let pages = self.pages_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -873,7 +873,8 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let shown = !hidden && object.visible && look.visible; - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + let on: &[Rect] = if shown { &pages } else { &[] }; + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, on, &mut self.envelope_spent) }; alike.then_some(ap) } @@ -885,7 +886,7 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let mut spent = crate::import::ai::envelope::Spent::default(); - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent) + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, &[], &mut spent) }; alike.then_some(ap) } @@ -1314,7 +1315,7 @@ fn look_alike( hidden: bool, layer: NodeId, shared: &crate::import::ai::envelope::Shared<'_>, - page: Option, + pages: &[Rect], spent: &mut crate::import::ai::envelope::Spent, ) -> bool { let mut live = object.clone(); @@ -1329,7 +1330,7 @@ fn look_alike( for n in [&mut live, &mut plain] { (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); } - crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, pages, spent) } /// Does `appearance` stroke with dashes aligned to corners and path ends? diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..9ea967b927 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -9395,24 +9395,35 @@ fn warped_type_gets_what_the_envelopes_left_of_the_budget() { let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)))); let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0)); let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside))); + let page = Rect::new(0.0, 0.0, 200.0, 100.0); for r in [&exact, &shifted] { assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1); - assert!(r.warped_type.page.is_some()); + assert_eq!(r.warped_type.pages, [page]); } live_envelope(&art(&shifted.doc)[0]); - assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any); + assert!(shifted.warped_type.spent.on(page).0 > exact.warped_type.spent.on(page).0); } -/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks. +/// In a file with an artboard list, warped type is held to every artboard, not to the crop marks. #[test] -fn warped_type_is_held_to_the_first_artboard() { +fn warped_type_is_held_to_every_artboard() { let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\ %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))))); assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0)); - assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0))); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(400.0, 200.0, 600.0, 350.0)]); +} + +/// Artboards that are an earlier one to half a point, and an art box that is one of them, add no +/// page of their own. +#[test] +fn pages_that_repeat_an_artboard_are_held_once() { + let boards = boards_at(&[[0.0, 0.0, 200.0, 100.0], [0.2, 0.0, 200.0, 100.3], [0.0, 0.0, 200.0, 100.0], [300.0, 0.0, 400.0, 100.0]]); + let data = format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0)))); + let r = read(stream_with_header("%%HiResBoundingBox: 300 0 400 100.4\n", &data).as_bytes()).unwrap(); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)]); } /// Type whose Warp is hidden draws no warp, so it stays type even with no check left. @@ -9454,17 +9465,39 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]); } let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; - let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); + let page = Rect::new(0.0, 60.0, 60.0, 100.0); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, pages: vec![page], ..Default::default() }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; - let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; + let spent = || super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; assert_eq!(settle(&looks[1], Default::default()), 0); assert_eq!(settle(&looks[1], spent()), 1); assert_eq!(settle(&looks[0], spent()), 0); } +/// Each page the art may be compared with has its own share of the budget: warped type on the +/// second page spends that page's share, whatever is left of the first page's. +#[test] +fn warped_type_on_a_later_page_spends_that_pages_share_of_the_budget() { + use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE}; + let (doc, mut looks) = warped_type_doc(2); + // The second object shows. Its look draws a little more than it. + let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6)))); + let mark = art(&mark.doc)[0].clone(); + let w = looks.remove(1); + let look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10), vec![Arc::new(w.look.clone()), mark]); + let (first, second) = (Rect::new(200.0, 0.0, 260.0, 40.0), Rect::new(0.0, 60.0, 60.0, 100.0)); + let settle = |spent| { + let looks = vec![super::envelope::WarpedLook { slot: w.slot, look: look.clone(), left_out: None }]; + let warped = super::envelope::WarpedType { looks, checks: 1, spent, pages: vec![first, second], ..Default::default() }; + warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) + }; + let full = |page| super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; + assert_eq!(settle(full(first)), 0); + assert_eq!(settle(full(second)), 1); +} + /// An envelope that comes out close to its drawn art, but with more of the page differing than the /// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100 /// page), keeps the drawn art, so the file still opens from its layers. @@ -9479,6 +9512,58 @@ fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() { assert_eq!(r.warnings, [super::envelope::DRAWN]); } +/// The document data of artboards in art space, each `[x0, y0, x1, y1]`. +fn boards_at(boards: &[[f64; 4]]) -> String { + let boards: String = boards + .iter() + .map(|[x0, y0, x1, y1]| { + format!("%_/Dictionary :\n%_{x0} {y1} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{x1} {y0} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n") + }) + .collect(); + format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n") +} + +/// The envelope of [`an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it`] on the +/// second artboard, the first a strip along the top that it doesn't reach: a page of the second +/// artboard can be compared with the layers, so it is held to that page and keeps its drawn art. +/// One that draws as its drawn art opens live there. +#[test] +fn an_envelope_on_a_later_artboard_that_differs_over_its_page_keeps_its_drawn_art() { + let boards = boards_at(&[[0.0, 98.0, 20.0, 100.0], [0.0, 0.0, 200.0, 100.0]]); + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let r = read_ok(&format!("{boards}{}", layer(&body))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)); + let r = read_ok(&format!("{boards}{}", layer(&body))); + live_envelope(&art(&r.doc)[0]); +} + +/// The same envelope on no artboard, inside the art's bounding box: a page cropped to the art +/// shows it, so it is held to that page too. +#[test] +fn an_envelope_off_the_artboards_that_differs_over_the_arts_box_keeps_its_drawn_art() { + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let data = format!("{}{}", boards_at(&[[0.0, 98.0, 20.0, 100.0]]), layer(&body)); + let r = read(stream_with_header("%%HiResBoundingBox: 0 0 200 100\n", &data).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); +} + /// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which /// the page's art replaces. #[test] From 06d977439b420b9876cf650c56afdd592c1aea23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:43:17 -0800 Subject: [PATCH 06/13] Tests: ui-egui tests that change the proof view hold the default proof view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit View › Proof Colors, Overprint Preview and Separations Preview are one view for the whole process, and the canvas draws through it. Canvas tests hold `testing::DefaultProofView` to keep it fixed while they compare frames, and `testing.rs` asks every test that sets the view to hold it too. Three tests changed it without holding it: - `panels::actions::tests_edits::every_listed_menu_item_runs_from_the_menu_what_its_step_holds` and `shortcut_editor::tests::listed_commands_run_from_a_key_without_a_missing_param` run every listed command, the View menu's proof commands included. - `dialogs::new_document::tests::new_document_choice_enter_commits_before_create` creates a document with Preview Mode set to Overprint, which turns on Overprint Preview and leaves it on. When one of them ran between two frames of a canvas test in the same test process, the render options of the next frame no longer matched the frame shown. An edit then rendered the whole frame instead of drawing its part, and `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render` failed with "rendered whole about STILL_SECS after the view stopped: 1 frames". Turning Overprint Preview on between two of its frames gives that failure every time. --- crates/ui-egui/src/dialogs/new_document.rs | 2 ++ crates/ui-egui/src/panels/actions/tests_edits.rs | 2 ++ crates/ui-egui/src/shortcut_editor.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index bf048d3e28..8ec5e10ba1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -907,6 +907,8 @@ mod tests { #[test] fn new_document_choice_enter_commits_before_create() { + // Preview Mode's last choice, Overprint, turns on the whole process's Overprint Preview. + let _view = crate::testing::DefaultProofView::new(); let mut panel = actual_preset_dialog(); panel.click("Advanced Options"); for (label, key) in [ diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index d83e306f05..1fe2f13711 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -925,6 +925,8 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { /// artboard to both. #[test] fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { + // The View menu's proof items change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { let (mut app, _) = app_with_three_moves(); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a96f77c18a..3c8c5cc986 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2437,6 +2437,8 @@ mod tests { #[test] fn listed_commands_run_from_a_key_without_a_missing_param() { use vectorcraft_testkit::fixtures::Fixture; + // The View menu's proof commands change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); // These need a state the fixtures lack: text being edited, a pattern being edited, an // object linked to a graphic style, a plug-ins folder. let context = ["text.insertInline", "pattern.options", "graphicStyle.redefine", "plugin.reload"]; From d19a3305a46b4cb6b3258d30d36d9487359ff098 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:10:58 -0800 Subject: [PATCH 07/13] EPS import: complexity tests count the work done instead of timing it Four EPS import tests asserted elapsed time (5 s, 20 s, a 20 s receive timeout, and 1,000 copies against 5 times one copy). A busy test runner could fail them, and a slower run that was still bounded could pass them. Each now reads a test-only counter on its own thread: - `]` without its `[`: the operand stack slots that `[` and `]` look at. 200,000 brackets look at no more than 4 slots each. - The outline check: the point-to-segment distances it works out. A look drawn 5,000 times works out no more than `MAX_OUTLINE_PAIRS`. - Objects on a path: the paths and objects the records measure. A thousand copies of a record measure as many as one copy. - File fonts: the glyphs `fits` compares. A string of 250,000 of one character makes fewer comparisons than it has glyphs. Outside tests the counters do nothing. --- crates/eps/src/import/ai/read.rs | 4 ++ crates/eps/src/import/ai/read/on_path.rs | 16 ++++++++ crates/eps/src/import/ai/read/ops.rs | 52 +++++++++++++++++++++--- crates/eps/src/import/ai/tests.rs | 32 +++++++-------- crates/eps/src/import/file_fonts.rs | 27 ++++++++---- 5 files changed, 100 insertions(+), 31 deletions(-) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..cf7c5e1159 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,6 +155,10 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; +#[cfg(test)] +pub(crate) use on_path::on_path_measured; +#[cfg(test)] +pub(crate) use ops::array_slots; pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 1e33e09a1b..682739c27d 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -123,6 +123,18 @@ impl Reader<'_> { } } +#[cfg(test)] +thread_local! { + /// How many paths and objects the records on this thread have measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn on_path_measured() -> u64 { + MEASURED.get() +} + /// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record. pub(super) fn apply(doc: &mut Document, found: &OnPath) { if found.records.is_empty() { @@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap if !tried.insert(g.id) { return None; } + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); attachable_path(children.iter().find(|c| c.id == path)?)?; let mut members = Vec::with_capacity(placed.len()); for (id, place, angle) in placed { // The frame the object is drawn in: turned by its angle (the document's y points down) // about the center of its bounds. + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); let center = doc.node_at(place)?.geometric_bounds()?.center(); members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index fcdffd4580..1bf190817c 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -9,6 +9,29 @@ use super::{ use vectorcraft_doc::{ArrowAlign, Arrowhead}; use vectorcraft_geom::PathData; +#[cfg(test)] +thread_local! { + /// The operand stack slots that `[` and `]` have looked at on this thread, to find the open + /// `[` or to take an array's items: their work. + static ARRAY_SLOTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The point-to-segment distances [`draws_look_outline`] has worked out on this thread. + static OUTLINE_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`ARRAY_SLOTS`] of this thread. +#[cfg(test)] +pub(crate) fn array_slots() -> u64 { + ARRAY_SLOTS.get() +} + +/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests. +fn array_slots_looked_at(slots: usize) { + #[cfg(test)] + ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX))); + #[cfg(not(test))] + let _ = slots; +} + impl<'a> Reader<'a> { // ---- operators ------------------------------------------------------------------------- @@ -16,11 +39,13 @@ impl<'a> Reader<'a> { // The innermost `[` still on the stack (the stack is cut back by operators). let mut at = self.stack.len(); while let Some(m) = self.marks.pop() { + array_slots_looked_at(1); if matches!(self.stack.get(m), Some(V::Mark)) { at = m; break; } } + array_slots_looked_at(self.stack.len() - at); let items: Vec = self.stack.split_off(at).into_iter().skip(1).collect(); self.push(V::Arr(items)) } @@ -172,6 +197,7 @@ impl<'a> Reader<'a> { "[" => { // Drop marks that operators have taken off, so `marks` is the open nesting. while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + array_slots_looked_at(1); self.marks.pop(); } // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. @@ -1635,7 +1661,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo /// projection onto it) is taken from `budget`: `false` once that runs out. fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool { use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; - let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT); + let close = |p: kurbo::Point| { + b.iter().any(|t| { + #[cfg(test)] + OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1); + t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT + }) + }; for s in a { let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil(); let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 }; @@ -2019,7 +2051,8 @@ mod tests { /// The outline check works from one budget for the object: a look of the outline drawn twice /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn - /// look instead of comparing every copy. + /// look instead of comparing every copy, having worked out no more distances than the budget + /// holds. #[test] fn the_outline_check_has_one_budget_for_the_object() { let zig = vectorcraft_doc::Effect { @@ -2035,10 +2068,17 @@ mod tests { let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect(); Node::group(NodeId(2), drawn) }; - assert!(draws_look_outline(&object, &appearance, &look(2))); - let started = std::time::Instant::now(); - assert!(!draws_look_outline(&object, &appearance, &look(5_000))); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // Whether the object draws `look`, and how many distances the check worked out. + let check = |look: &Node| { + let before = OUTLINE_PAIRS.get(); + let drawn = draws_look_outline(&object, &appearance, look); + (drawn, OUTLINE_PAIRS.get() - before) + }; + let (drawn, two) = check(&look(2)); + assert!(drawn); + let (drawn, many) = check(&look(5_000)); + assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}"); + assert!(!drawn); } /// The outline check reshapes the object as it is drawn, its effects working from its bounds diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..57d402f1f4 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6440,13 +6440,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { } } +/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds +/// of thousands of them look at no more than four slots each. #[test] fn closing_brackets_without_their_opening_dont_rescan_the_stack() { let n = 200_000; let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n)); - let started = std::time::Instant::now(); + let before = read::array_slots(); let _ = read(stream(&layer(&body)).as_bytes()); - assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); + let slots = read::array_slots() - before; + assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots"); } #[test] @@ -10833,9 +10836,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() { } /// The path and objects of a group are measured once however many records name it: a thousand -/// copies of a record open about as fast as one copy followed by 999 records whose path id is -/// missing, when the group opens live, when its long path has no length, and when its first object -/// is a group of many paths and its last object has no bounds. +/// copies of a record measure as many paths and objects as one copy followed by 999 records whose +/// path id is missing, when the group opens live, when its long path has no length, and when its +/// first object is a group of many paths and its last object has no bounds. #[test] fn repeated_objects_on_path_records_dont_measure_the_objects_again() { use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; @@ -10860,23 +10863,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() { let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); - let time = |data: &str| { - let started = std::time::Instant::now(); + let measure = |data: &str| { + let before = read::on_path_measured(); let doc = read_ok(&format!("{data}{}", layer(&group))).doc; - let elapsed = started.elapsed(); + let measured = read::on_path_measured() - before; let g = art(&doc)[0].clone(); assert_eq!(g.children().unwrap().len(), n, "{why}"); assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); - elapsed + measured }; - // The fastest of three runs each, taken in turn, so that other tests running at the same - // time weigh on both. - let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); - for _ in 0..3 { - fastest_one = fastest_one.min(time(&one)); - fastest_many = fastest_many.min(time(&many)); - } - assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + let (measured_one, measured_many) = (measure(&one), measure(&many)); + assert!(measured_one > 0, "{why}"); + assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}"); } } diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs index 83e51bb7ee..de6f044cd3 100644 --- a/crates/eps/src/import/file_fonts.rs +++ b/crates/eps/src/import/file_fonts.rs @@ -38,6 +38,12 @@ struct Gathered { chars: HashMap, } +#[cfg(test)] +thread_local! { + /// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread. + static COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl FileFontGlyphs { /// The font of `family` and `style` (made with `info` the first time): its index. pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { @@ -59,6 +65,10 @@ impl FileFontGlyphs { let mut new: HashMap = HashMap::new(); for g in glyphs { let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied()); + #[cfg(test)] + if kept.is_some() { + COMPARED.set(COMPARED.get() + 1); + } match kept { Some(k) if k.outline != g.outline || k.advance != g.advance => return false, Some(_) => {} @@ -178,15 +188,16 @@ mod tests { } /// A long string of one character compares each glyph with that character's once, not with - /// every one before it: a quarter of a million of them fit at once. + /// every one before it: a quarter of a million of them fit at once, with fewer comparisons + /// than glyphs. #[test] fn a_long_string_of_one_character_fits_in_linear_time() { - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let mut g = FileFontGlyphs::default(); - let f = g.font("F", "Regular", FileFontInfo::default); - tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok(); - }); - assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true)); + let n = 250_000; + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + let before = COMPARED.get(); + assert!(g.fits(f, &vec![glyph('A'); n])); + let compared = COMPARED.get() - before; + assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons"); } } From 53aa1a148c05698565dfdacd35871514ad90af91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:04:57 -0800 Subject: [PATCH 08/13] Command Palette: leave out commands with no menu item that need a value A command with no menu path whose params name a required field (Close Path needs an `id`, Knife needs `points`) was still listed, and a pick of it always failed with an error such as "missing id". The rule that leaves out commands needing a value now applies to these commands as well as to menu commands, so 232 more engine commands are left out (562 in all, up from 330). Rename Artboards and the Remove Asset, Rename Asset and Set 3D Format commands stay listed: a pick of each opens the Rename dialog or the Asset Export panel. --- crates/ui-egui/src/palette.rs | 38 +++++++++------------------ crates/ui-egui/src/shortcut_editor.rs | 7 ++--- 2 files changed, 17 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 40699f7804..aad5a37d1f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -44,7 +44,8 @@ const WRAPPED: &[(&str, &str)] = &[ /// every preference, Forget Import Matches forgets every saved match, Begin Undo Group and End /// Undo Group begin and end a group, the six Save … Preset commands save a new preset (Save /// Gradient Preset the selection's gradient), Delete Gradient Preset deletes the saved preset the -/// selection's gradient matches, the three Asset Export commands open the Asset Export panel (#4864), New +/// selection's gradient matches, the six Asset Export commands open the Asset Export panel (#4864), +/// Rename Artboards opens the Rename dialog for the selected artboards, New /// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default /// gradient, Define Perspective Grid makes the document's grid, Select Slice deselects the /// slices, and Find Next goes on from the last Find and Replace search or opens its dialog, as @@ -65,8 +66,12 @@ const PICK_RUNS: &[&str] = &[ "gradient.presets.save", "gradient.presets.delete", "assets.export", + "assets.remove", + "assets.rename", "assets.export3D", + "assets.set3DFormat", "assets.settings.set", + "artboard.rename", "symbol.new", "paint.setGradientGeom", "perspective.grid.set", @@ -80,23 +85,11 @@ const PANEL_PATH: &str = "Window › Show Panel"; /// The menu path ([`context`]) a result takes when another result has its name: (id, English /// path), for commands that no item of the menu bar runs and whose id names no parent command. const CONTEXTS: &[(&str, &str)] = &[ - ("addon.pen.close", "Pen"), - ("addon.pen.reshape", "Pen"), - ("addon.pen.togglePoint", "Pen"), - ("charStyle.setAttrs", "Character Styles"), ("file.exportInBackground", "Export"), ("file.openInBackground", "Open"), ("imageTrace.hideRuns", "Image Trace"), ("links.reveal", "Links"), - ("livePaint.fill", "Live Paint"), - ("object.blend.spine.convertAnchor", "Blend"), - ("paraStyle.setAttrs", "Paragraph Styles"), - ("path.close", "Path"), - ("path.convertAnchor", "Path"), - ("path.knife", "Path"), - ("path.reshapeSegment", "Path"), ("plugin.hideRuns", "Plug-ins"), - ("text.editRange", "Text"), ("ui.layersPanelOptions", "Layers"), ("ui.navigatorPanelOptions", "Navigator"), ]; @@ -1563,15 +1556,8 @@ mod tests { ("ui.paraStyleOptions.resetPanel", "Paragraph Style Options › Reset Panel"), ("window.swatchLibrary.other", "Window › Swatch Libraries › Other Library…"), ("window.brushLibrary.other", "Window › Brush Libraries › Other Library…"), - ("tool:knife", "Tools › Knife"), - ("path.knife", "Path › Knife"), - ("addon.pen.close", "Pen › Close Path"), - ("path.close", "Path › Close Path"), ("type.fitHeadline", "Type › Fit Headline (type.fitHeadline)"), ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), - ("shape.ellipse", "Ellipse (shape.ellipse)"), - ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), - ("perspective.editText", "Object › Perspective › Edit Text"), ("ui.action.play", "Play Action (ui.action.play)"), ("ui.action.playAt", "Play Action (ui.action.playAt)"), ("ui.batchDialog", "Batch…"), @@ -1690,7 +1676,8 @@ mod tests { /// Of the engine commands the palette listed before, it leaves out only the ones /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of - /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves + /// the menu bar, and commands that need a value no menu item gives, with a menu path of their own + /// or without one. A pick of each one it leaves /// out (with no document, one object selected or several) changes neither the document, its /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still /// listed. @@ -1706,7 +1693,8 @@ mod tests { let listed: std::collections::HashSet = items().into_iter().map(|(_, id)| id).collect(); let dropped: Vec<&vectorcraft_engine::CommandSpec> = before.iter().copied().filter(|c| !listed.contains(c.id)).collect(); let ids: Vec<&str> = dropped.iter().map(|c| c.id).collect(); - for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set"] { + // Close Path, Set Handle and Knife have no menu path, and each needs an `id`. + for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set", "path.close", "path.setHandle", "path.knife"] { assert!(ids.contains(&id), "{id} is left out: {ids:?}"); } // What a pick can change: the document with its selection, history, revision and layer @@ -1733,8 +1721,8 @@ mod tests { look(&app) != before }) }; - // `layer.setProps {}` records an undo step that changes nothing. - let changed: Vec<&str> = ids.iter().copied().filter(|id| *id != "layer.setProps" && acts(id)).collect(); + // `layer.setProps {}` and `path.moveAnchors {}` record an undo step that changes nothing. + let changed: Vec<&str> = ids.iter().copied().filter(|id| !["layer.setProps", "path.moveAnchors"].contains(id) && acts(id)).collect(); assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); for c in &dropped { assert!(c.shortcut.is_none() && crate::shortcut_editor::menu_bar_path(c.id).is_none(), "{}", c.id); @@ -1767,7 +1755,7 @@ mod tests { for id in PICK_RUNS.iter().filter(|id| !session_only.contains(id)) { assert!(acts(id), "a pick of {id} does something"); } - for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors", "path.close"]) { + for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors"]) { assert!(listed.contains(*id), "{id} stays"); } } diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a96f77c18a..50ce83bf84 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -798,8 +798,9 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu /// bar runs it without params or with one set of params ([`menu_target`]), it opens no dialog when /// run without them (as the Variables panel's commands do), and it is a query, whose answer a key -/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params -/// doc names a field a call must give (File › Document Setup › Units, `{units}`)? +/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a command whose params doc +/// names a field a call must give, with a menu path (File › Document Setup › Units, `{units}`) or +/// without one (Close Path, `{id}`)? pub(crate) fn needs_a_value(key: &str) -> bool { static KEYS: OnceLock> = OnceLock::new(); KEYS.get_or_init(|| { @@ -809,7 +810,7 @@ pub(crate) fn needs_a_value(key: &str) -> bool { c.shortcut.is_none() && !a_menu_bar_item_runs(c.id, c.params) && !crate::dialogs::variables::opens(c.id) - && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || (!c.menu.is_empty() && names_a_required_field(c.params))) + && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || names_a_required_field(c.params)) }) .map(|c| c.id) .collect() From 3315bc4bfd6f2aac706a7e9a61398d12524acaab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:10:15 -0800 Subject: [PATCH 09/13] Docs: limit the Preview-off exception to layers that are not templates A template layer stays in Preview whatever its Preview flag is, so only a layer that is not a template and has Preview off draws placed files by the Outline rules in Preview mode. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bceff53d7b..b356fa923b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -558,7 +558,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | From 27104129d0ae9f83e8a4be5eb62d7d6fa7d55ae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:10:33 -0800 Subject: [PATCH 10/13] Docs: list the placed EPS files the .ai reader leaves as before The progress line now names the cases where a placed EPS file whose bytes the editing data includes stays as on main: DCS bytes, no bounding box of its own, a VectorCraft document, bytes that don't read as EPS, an `.ai` or `.ait` file name, and a previewed file that an image variable binds. --- 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 bc7a0f541a..df6433d0ed 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,7 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). - A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From ebf50139e7f4d888f5a4fc75a63bce8e2c293247 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:18:35 -0800 Subject: [PATCH 11/13] Properties: a live rectangle's Corner menu sets a kind only when it is chosen The Corner menus of a live rectangle's properties (one for all four corners while Corner Radius is linked, one per corner otherwise) read the select's current value, so a kind highlighted with the arrow keys in the open list ran object.setLiveShape at once and recorded an undo step, and Escape left the highlighted kind on the rectangle. The menus now read only the committed pick, as the Corner menu of Direct-Selected corners does since #9728. The rows are shared by the Transform panel, the Properties panel's Transform section and the Contextual Task Bar. --- crates/ui-egui/src/panels.rs | 5 +- crates/ui-egui/src/panels/transform/tests.rs | 66 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 52649d6400..7e18b51179 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -167,9 +167,10 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { } /// A select of the corner kinds named `name`, showing `current` (blank for None), as wide as its -/// widest kind, so it fits beside a corner's radius field. Returns the kind picked. +/// widest kind, so it fits beside a corner's radius field. Returns the kind chosen, not one only +/// highlighted in the open list. fn corner_select(ui: &mut Ui, name: &'static str, current: Option, entries: &[Entry]) -> Option { - Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).value().copied() + Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).events.committed().copied() } /// Set `kind` on corner `corner` (every corner for None) of each selected live rectangle diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index bfad19d09b..a5f37234e1 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -158,6 +158,72 @@ fn a_rectangle_shows_linked_and_unlinked_corner_types() { assert!(!p.shows("Corner") && p.shows("Top Left Corner") && p.shows("Bottom Left Corner")); } +/// Checks a live rectangle's Corner menu `menu` drawn by `draw`, with Corner Radius linked +/// (`single`) or not: a kind highlighted in the open menu leaves the rectangle as it is, Escape +/// closes the menu with the kind and the undo history unchanged, and Enter sets the highlighted +/// kind, on the corners `changed` marks, as one undo step. +fn check_corner_kind_menu(draw: fn(&mut VectorcraftApp, &mut Ui), single: bool, menu: &str, changed: [bool; 4]) { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_geom::shapes::CornerKind; + let mut app = new_app(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap()["id"].as_u64().unwrap(); + set_pref(&mut app, "singleCornerRadius", single); + let mut p = Panel::new(app, draw); + let kinds = |p: &Panel| { + let app = p.app(); + let corners = LiveCorners::of(app.session.active().unwrap().doc.node(NodeId(id)).unwrap()).unwrap(); + [0, 1, 2, 3].map(|k| corners.kind(k)) + }; + let original = p.app().session.active().unwrap().doc.clone(); + assert_eq!(kinds(&p), [CornerKind::ALL[0]; 4]); + let undo = undo_depth(&p.app()); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: highlighting a kind leaves the rectangle as it was"); + p.key(Key::Escape, Modifiers::NONE); + assert!(p.shows(menu), "{menu}: the panel still shows the menu after Escape"); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: Escape leaves the rectangle as it was"); + assert_eq!(undo_depth(&p.app()), undo, "{menu}: Escape records no undo step"); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + let expected = changed.map(|c| if c { CornerKind::ALL[1] } else { CornerKind::ALL[0] }); + assert_eq!(kinds(&p), expected, "{menu}: Enter sets the highlighted kind"); + assert_eq!(undo_depth(&p.app()), undo + 1, "{menu}: the kind is one undo step"); +} + +/// The Transform panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn transform_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, true, "Corner", [true; 4]); +} + +/// The Transform panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn transform_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, false, "Top Right Corner", [false, true, false, false]); +} + +/// The Properties panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn properties_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, true, "Corner", [true; 4]); +} + +/// The Properties panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn properties_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, false, "Top Right Corner", [false, true, false, false]); +} + /// The four corner labels of an unlinked Corner Radius, in the Transform panel and in the /// Properties panel, start at one edge of their column whatever their widths, and the radius /// fields after them line up. From 3d33094d3924abfa1772620daee097e034592d18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:39:57 -0800 Subject: [PATCH 12/13] Direct Selection: hover marks the anchor a press takes across selected groups The selected paths a hover tries were listed group by group in selection order, while a press tries them topmost first across the document. With two selected groups whose anchors fall within reach, hover marked the back group's anchor and a press took the front one. The list is now sorted in paint order, topmost first, with a Shaper Group's original shapes included. --- crates/tools/src/direct.rs | 22 +++++++++++++++++----- crates/tools/src/direct/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 02eb4e2202..4ee67bde6c 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -641,15 +641,14 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { } /// The editable paths of the selected objects and inside them (a selected group's members), with -/// their control bounds: each selected object's paths topmost first, in selection order. The list -/// is made once per document state and selection; a hover measures only the paths whose bounds it -/// is near. +/// their control bounds, topmost first across the whole document: the order [`hit_anchor`] tries +/// them in. The list is made once per document state and selection; a hover measures only the +/// paths whose bounds it is near. fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> { crate::select::selected_part_boxes(cx, || { let editable = cx.doc.editable(); let mut v = vec![]; for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { - let from = v.len(); walk_pickable_from(root, &mut |n| { if editable(n.id) && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) @@ -657,8 +656,21 @@ fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft v.push((n.id, b)); } }); - v[from..].reverse(); } + // The paint order of every node, a Shaper Group's original shapes included (isolation can + // select them); the topmost path comes first. + fn walk_all(n: &Node, order: &mut std::collections::HashMap) { + let i = order.len(); + order.insert(n.id, i); + for c in n.children().into_iter().flatten() { + walk_all(c, order); + } + } + let mut order = std::collections::HashMap::new(); + for l in &cx.doc.layers { + walk_all(l, &mut order); + } + v.sort_by_key(|(id, _)| std::cmp::Reverse(order.get(id).copied())); v.into() }) } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index b4689642fd..ee1d88778f 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -3074,3 +3074,31 @@ fn select_behind_is_measured_once_for_a_point() { assert!(crate::select::selects_behind_at(&c, at)); assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); } + +/// With two selected groups whose anchors sit on the same point, the highlighted anchor is the one +/// a press takes: the front group's, whatever order the groups were selected in. +#[test] +fn the_highlighted_anchor_of_two_selected_groups_is_the_one_a_press_takes() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (back_path, back, front_path, front) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id, x| { + std::sync::Arc::new(vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(x, x, x + 100.0, x + 100.0)), + vectorcraft_doc::Appearance::default_art(), + )) + }; + d.insert(Some(l), 0, vectorcraft_doc::Node::group(back, vec![path(back_path, 100.0)])).unwrap(); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::group(front, vec![path(front_path, 100.0)])).unwrap(); + let p = paint(); + let corner = Point::new(100.0, 100.0); + for order in [[back, front], [front, back]] { + let mut s = Selection::default(); + s.set(order); + let c = cx(&d, &s, &p); + let pressed = hit_anchor(&c, corner, c.point_tol()).map(|(id, ..)| id); + assert_eq!(pressed, Some(front_path), "a press takes the front anchor (selected {order:?})"); + assert_eq!(hovered_anchor(&c, corner), Some((front_path, corner)), "the front anchor is highlighted (selected {order:?})"); + } +} From 1caf734c0f534c25bd1f68e44ca05538de8f7c86 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:42:17 -0800 Subject: [PATCH 13/13] Docs: state the 256 MiB limit on included placed EPS bytes --- 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 df6433d0ed..16f9c83d42 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,7 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). - A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are larger than 256 MiB, are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`).