From 3a711184ec41ec2053fff125c790f04bb5dee9f6 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:53:38 +0430 Subject: [PATCH 01/83] Fix #5239: double-clicking a ruler adds a guide there A double-click on the top ruler adds a vertical guide at the pointer's x, one on the left ruler a horizontal guide at its y, through guide.add (one undo step, shown even with guides hidden, an artboard guide with the Artboard tool as a drag from a ruler makes one). --- crates/engine/src/tooling.rs | 12 +++++-- crates/ui-egui/src/canvas/grid.rs | 21 +++++++++++- crates/ui-egui/src/canvas/tests.rs | 51 ++++++++++++++++++++++++++++++ docs/gaps.md | 4 ++- docs/target-app-parity.md | 4 ++- docs/ui-parity.md | 5 ++- 6 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 4eb1912294..e221f9f00e 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -465,6 +465,14 @@ impl Session { Ok(()) } + /// The artboard a guide made from a ruler belongs to: with the Artboard tool, its active + /// artboard (an artboard guide); with any other tool, none (a canvas guide). + pub fn ruler_guide_artboard(&self) -> Option { + let boards = self.active().map_or(0, |d| d.doc.artboards.len()); + let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten(); + active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards) + } + /// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a /// horizontal one out of the top ruler. `ev` is the pointer in document space (a drag, then the /// release), over the canvas or not (`on_canvas`). The guide shows where the pointer is over @@ -475,9 +483,7 @@ impl Session { let g = match self.ruler_guide.take() { Some(g) => Some(g), None => { - let boards = self.active().map_or(0, |d| d.doc.artboards.len()); - let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten(); - let artboard = active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards); + let artboard = self.ruler_guide_artboard(); self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::NewGuide::new(cx, vertical, artboard))) } }; diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 09749fc12c..06fc2e61f9 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -178,7 +178,10 @@ pub(super) fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] { /// A drag from a ruler onto the canvas makes a guide where the button is released (the engine's /// `Session::ruler_guide`): a horizontal one from the top ruler, a vertical one from the left /// ruler, snapped as a moved guide is (with Shift to the ruler's ticks). Released anywhere else, -/// it makes none. The corner drags the rulers' origin or resets it on a double-click. +/// it makes none. A double-click on a ruler makes a guide at the pointer, across the ruler's +/// axis (a vertical one on the top ruler, a horizontal one on the left), unsnapped, as one +/// `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a +/// double-click. pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf) -> Option { let [top, left, corner] = ruler_rects(full); // Right-click on a ruler or the origin box: the document units, to swap between them as @@ -189,6 +192,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c // (right). Not focusable (`click_and_drag` is): no key acts on a ruler, so Tab skips it. let resp = ui.interact(r, egui::Id::unique(id), Sense::CLICK | Sense::DRAG); resp.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); + if resp.double_clicked_by(egui::PointerButton::Primary) + && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) + { + // The same document point the drag path reads; the guide runs across the other axis + // than the ruler, so it takes the pointer's coordinate along the ruler. + let at = xf.to_doc(p); + let mut params = json!({"vertical": !vertical, "pos": if vertical { at.y } else { at.x }}); + if let Some(ab) = app.session.ruler_guide_artboard() { + params["artboard"] = json!(ab); + } + // The new guide shows even if guides were hidden. + app.ui.view.guides = true; + if let Err(e) = app.run("guide.add", params) { + app.status(e.to_string()); + } + } let kind = if resp.drag_stopped() { PointerKind::Up } else if resp.dragged() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0c9462818e..98123464cd 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8859,3 +8859,54 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra assert_eq!(set_count, 1, "settled frame 10 is uploaded to texture"); assert_eq!(app.canvas.key.as_ref().unwrap().revision, 10, "settled frame 10 is uploaded"); } + +/// #5239: a double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler +/// at its x, a horizontal one on the left ruler at its y, as one undo step, shown even when +/// guides were hidden. The first click of the pair adds nothing. +#[test] +fn double_clicking_a_ruler_adds_a_guide_at_that_position() { + // The ruler to click, the guide's orientation and its position, the pointer at that position. + for (top, vertical, pos) in [(true, true, 120.0), (false, false, 80.0)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let view = app.view_mut().unwrap(); + view.zoom = 2.0; + view.rotation = 0.0; + view.center = Point::new(200.0, 150.0); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let at = if top { + pos2(xf.to_screen(Point::new(pos, 0.0)).x, rect.top() - RULER / 2.0) + } else { + pos2(rect.left() - RULER / 2.0, xf.to_screen(Point::new(0.0, pos)).y) + }; + let guides = |app: &mut VectorcraftApp| { + let list = app.session.execute("guide.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|g| (g["vertical"].as_bool().unwrap(), g["pos"].as_f64().unwrap())).collect::>() + }; + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + let click = |app: &mut VectorcraftApp| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, &ctx, vec![button(true)]); + frame(app, &ctx, vec![button(false)]); + }; + click(&mut app); + assert_eq!(guides(&mut app), vec![], "a single click adds none"); + click(&mut app); + let got = guides(&mut app); + assert_eq!(got.len(), 1, "top ruler: {top}, {got:?}"); + assert!(got[0].0 == vertical && (got[0].1 - pos).abs() < 0.01, "top ruler: {top}, want vertical {vertical} at {pos}: {got:?}"); + assert!(app.ui.view.guides, "the new guide is shown"); + assert_eq!(steps(&app), before + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(guides(&mut app), vec![]); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 8b707fd9f6..040d7d8b30 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: new gradients follow document color mode) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | @@ -597,6 +598,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Selection artwork drag across visible document tabs (400 ms hover); lossless target copy, source/clipboard preservation and cancellation regressions. Cross-window dragging remains separate. +- **Done (#5239):** a double-click on a ruler adds a guide at the pointer (vertical on the top ruler, horizontal on the left one) through `guide.add`, unsnapped and in one undo step; no scored gap or estimate reassessed. - **Done:** custom document ruler origin (#1212): corner drag with preview, double-click reset to the active artboard, relative X/Y inputs and native save/reopen. - **Done:** View › Rulers › Change to Global / Artboard Rulers (`view.globalRulers`, Cmd+Alt+R): artboard rulers, a new document's, count from the active artboard, each artboard with its own zero point; rulers, X/Y fields and guide readouts follow the mode, which is saved with the document. Estimate unchanged. - **Done (#2849):** View › Rulers › Show Video Rulers (`view.videoRulers`): the rulers show and count the active artboard in video pixels from its top-left corner, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); Hide Video Rulers returns them to the General unit and the ruler origin. Shift-snapping a new guide to ruler ticks still uses the General unit's ticks. Estimate unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4370a3a0c..396a9525c4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: new gradients follow document color mode) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -21,6 +21,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | @@ -531,6 +532,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. +- **Ruler double-click (#5239):** a double-click on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y, through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. An egui frame test covers both rulers, a lone click, and Undo. - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26d3dd6790..d7bd60bd42 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | @@ -174,6 +175,7 @@ tools, never checked side by side) isn't captured row by row. | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set; no View › Snapping submenu. Floating-panel parity remains unverified. | | Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | +| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler, exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); the first click of the pair adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | @@ -418,6 +420,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | From a0ccbdbd58f48eb128717a3f1c5d482580f355bd Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:33:24 +0430 Subject: [PATCH 02/83] Fix #5239: a ruler double-click needs both clicks on that ruler and follows a rotated view (review) --- crates/ui-egui/src/canvas/grid.rs | 31 ++++++++-- crates/ui-egui/src/canvas/tests.rs | 94 ++++++++++++++++++++++++++++++ docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 5 files changed, 122 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 06fc2e61f9..7f000ee787 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -178,9 +178,10 @@ pub(super) fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] { /// A drag from a ruler onto the canvas makes a guide where the button is released (the engine's /// `Session::ruler_guide`): a horizontal one from the top ruler, a vertical one from the left /// ruler, snapped as a moved guide is (with Shift to the ruler's ticks). Released anywhere else, -/// it makes none. A double-click on a ruler makes a guide at the pointer, across the ruler's -/// axis (a vertical one on the top ruler, a horizontal one on the left), unsnapped, as one -/// `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a +/// it makes none. A double-click on a ruler (both clicks on that ruler) makes a guide at the +/// pointer, across the ruler's axis (a vertical one on the top ruler, a horizontal one on the +/// left; swapped in a view turned 90°, where the rulers read the other document axis, and the +/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a /// double-click. pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf) -> Option { let [top, left, corner] = ruler_rects(full); @@ -192,13 +193,31 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c // (right). Not focusable (`click_and_drag` is): no key acts on a ruler, so Tab skips it. let resp = ui.interact(r, egui::Id::unique(id), Sense::CLICK | Sense::DRAG); resp.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); + // egui counts a double-click by position and time alone, so a click on the canvas right + // at the ruler and one on the ruler would pass for one: the pair counts only when the + // ruler's own click before it came within the double-click delay. + let last_click = egui::Id::unique(if vertical { "ruler-left-last-click" } else { "ruler-top-last-click" }); + let now = ui.input(|i| i.time); + let first_here = + ui.data(|d| d.get_temp::(last_click)).is_some_and(|t| now - t <= ui.ctx().options(|o| o.input_options.max_double_click_delay)); + if resp.clicked_by(egui::PointerButton::Primary) { + ui.data_mut(|d| d.insert_temp(last_click, now)); + } if resp.double_clicked_by(egui::PointerButton::Primary) + && first_here && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) { - // The same document point the drag path reads; the guide runs across the other axis - // than the ruler, so it takes the pointer's coordinate along the ruler. + // The same document point the drag path reads. A ruler reads the canvas's coordinates + // turned with the view, so the guide is the one whose line crosses the ruler's axis: + // the vertical one when that axis (the screen's x for the top ruler, y for the left, + // in document directions) is nearer the document's x, else the horizontal one. At 0° + // that is a vertical guide from the top ruler; at 90° a horizontal one; between, the + // nearer axis, whose line still runs through the point and never along the ruler. let at = xf.to_doc(p); - let mut params = json!({"vertical": !vertical, "pos": if vertical { at.y } else { at.x }}); + let (sn, cs) = xf.rot.sin_cos(); + let axis = if vertical { (sn, cs) } else { (cs, -sn) }; + let across = axis.0.abs() >= axis.1.abs(); + let mut params = json!({"vertical": across, "pos": if across { at.x } else { at.y }}); if let Some(ab) = app.session.ruler_guide_artboard() { params["artboard"] = json!(ab); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 98123464cd..7c2355cbec 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8910,3 +8910,97 @@ fn double_clicking_a_ruler_adds_a_guide_at_that_position() { assert_eq!(guides(&mut app), vec![]); } } + +/// A fresh app with a 400 x 300 document, rulers on, the view at zoom 2 turned `rotation` degrees, +/// and its first frame drawn. +fn ruler_guide_app(rotation: f64) -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let view = app.view_mut().unwrap(); + view.zoom = 2.0; + view.rotation = rotation; + view.center = Point::new(200.0, 150.0); + frame(&mut app, &ctx, vec![]); + (app, ctx) +} + +/// One primary click at `at`, as three frames (move, press, release). +fn click_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) { + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, ctx, vec![button(true)]); + frame(app, ctx, vec![button(false)]); +} + +/// The ruler guides as (vertical, position). +fn guide_list(app: &mut VectorcraftApp) -> Vec<(bool, f64)> { + let list = app.session.execute("guide.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|g| (g["vertical"].as_bool().unwrap(), g["pos"].as_f64().unwrap())).collect() +} + +/// #5239 review: egui counts a double-click by position and time, not by widget, so a click on +/// the canvas right at a ruler followed at once by a click on the ruler is not a double-click on +/// the ruler. No guide; two clicks on the ruler still make one. +#[test] +fn a_canvas_click_then_a_ruler_click_adds_no_guide() { + for (top, canvas_first) in [(true, true), (false, true), (true, false), (false, false)] { + let (mut app, ctx) = ruler_guide_app(0.0); + let rect = app.canvas_rect.unwrap(); + // Two points less than 6 pt apart, either side of the ruler's inner edge. + let (on_canvas, on_ruler) = if top { + (pos2(rect.center().x, rect.top() + 1.0), pos2(rect.center().x, rect.top() - 1.0)) + } else { + (pos2(rect.left() + 1.0, rect.center().y), pos2(rect.left() - 1.0, rect.center().y)) + }; + click_at(&mut app, &ctx, if canvas_first { on_canvas } else { on_ruler }); + click_at(&mut app, &ctx, on_ruler); + let want = usize::from(!canvas_first); + assert_eq!(guide_list(&mut app).len(), want, "top ruler: {top}, first click on the canvas: {canvas_first}"); + } +} + +/// #5239 review: the rulers read the canvas's coordinates turned with the view, so a guide made +/// by a double-click runs across the ruler's axis in any view: it passes through the clicked +/// point and crosses the ruler's edge at it, never along it. At 90° the top ruler reads the +/// document's y, so its guide is horizontal; the left ruler reads x, so its guide is vertical. +/// A view turned part of the way takes the document axis nearer to the ruler's. +#[test] +fn a_ruler_double_click_follows_a_rotated_view() { + // Rotation (degrees), top ruler's guide is vertical, left ruler's guide is vertical. + for (rotation, top_vertical, left_vertical) in [ + (0.0, true, false), + (90.0, false, true), + (-90.0, false, true), + (180.0, true, false), + (270.0, false, true), + (30.0, true, false), + (60.0, false, true), + ] { + for top in [true, false] { + let (mut app, ctx) = ruler_guide_app(rotation); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let at = + if top { pos2(rect.center().x + 37.0, rect.top() - RULER / 2.0) } else { pos2(rect.left() - RULER / 2.0, rect.center().y + 23.0) }; + click_at(&mut app, &ctx, at); + click_at(&mut app, &ctx, at); + let got = guide_list(&mut app); + let label = format!("rotation {rotation}, top ruler: {top}: {got:?}"); + assert_eq!(got.len(), 1, "{label}"); + let (vertical, pos) = got[0]; + assert_eq!(vertical, if top { top_vertical } else { left_vertical }, "{label}"); + // Through the clicked point. + let doc = xf.to_doc(at); + assert!((pos - if vertical { doc.x } else { doc.y }).abs() < 0.01, "{label}: through {doc:?}"); + // Its direction on screen is not along the ruler: the line crosses the ruler's edge. + let along = if vertical { Point::new(doc.x, doc.y + 1.0) } else { Point::new(doc.x + 1.0, doc.y) }; + let dir = (xf.to_screen(along) - xf.to_screen(doc)).normalized(); + let across = if top { dir.y.abs() } else { dir.x.abs() }; + assert!(across > 0.5, "{label}: the guide runs along the ruler ({dir:?})"); + } + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 040d7d8b30..da2b049699 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -598,7 +598,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Selection artwork drag across visible document tabs (400 ms hover); lossless target copy, source/clipboard preservation and cancellation regressions. Cross-window dragging remains separate. -- **Done (#5239):** a double-click on a ruler adds a guide at the pointer (vertical on the top ruler, horizontal on the left one) through `guide.add`, unsnapped and in one undo step; no scored gap or estimate reassessed. +- **Done (#5239):** a double-click on a ruler adds a guide at the pointer (vertical on the top ruler, horizontal on the left one, swapped in a view turned 90°; both clicks on that ruler) through `guide.add`, unsnapped and in one undo step; no scored gap or estimate reassessed. - **Done:** custom document ruler origin (#1212): corner drag with preview, double-click reset to the active artboard, relative X/Y inputs and native save/reopen. - **Done:** View › Rulers › Change to Global / Artboard Rulers (`view.globalRulers`, Cmd+Alt+R): artboard rulers, a new document's, count from the active artboard, each artboard with its own zero point; rulers, X/Y fields and guide readouts follow the mode, which is saved with the document. Estimate unchanged. - **Done (#2849):** View › Rulers › Show Video Rulers (`view.videoRulers`): the rulers show and count the active artboard in video pixels from its top-left corner, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); Hide Video Rulers returns them to the General unit and the ruler origin. Shift-snapping a new guide to ruler ticks still uses the General unit's ticks. Estimate unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 396a9525c4..3647a4240c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -532,7 +532,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. -- **Ruler double-click (#5239):** a double-click on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y, through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. An egui frame test covers both rulers, a lone click, and Undo. +- **Ruler double-click (#5239):** a double-click (both clicks on that ruler) on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. egui frame tests cover both rulers, a lone click, Undo, a canvas click before a ruler click, and rotated views. - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d7bd60bd42..9b62219c1b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -175,7 +175,7 @@ tools, never checked side by side) isn't captured row by row. | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set; no View › Snapping submenu. Floating-panel parity remains unverified. | | Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | -| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler, exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); the first click of the pair adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position` | +| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | From 65238286158c90ec84d2e6abca22ba083bb26d28 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:51:03 +0430 Subject: [PATCH 03/83] docs: restore the status lines damaged by merges (main's line plus this PR's note) --- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index bfded0581c..3608d42980 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: new gradients follow document color mode) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (double-clicking a ruler adds a guide (#5239); Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 84b64806a8..a714e9538a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Type core options status and Kashidas feature revision corrected; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: new gradients follow document color mode) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (double-clicking a ruler adds a guide (#5239); the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bbd649b818..4748858992 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged; Type on a Path Options has a Preview checkbox, #5360; the Action Options row cites the public Actions panel page; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; a double-click on a ruler adds a guide there, #5239; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (double-clicking a ruler adds a guide (#5239); Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence From 397f5b64c8be8c9814099a5265f1d34009d12a7c Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:44:29 +0430 Subject: [PATCH 04/83] Merge fixup: close the Cmd-held bounding box test the merge left open --- crates/ui-egui/src/canvas/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ccd062e663..c4fef86bd2 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -10092,6 +10092,7 @@ fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { assert!(handle_drawn(&mut app, egui::Modifiers::COMMAND), "Cmd held shows the Selection tool's box"); assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "gone once Cmd is released"); assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); +} /// #5239: a double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler /// at its x, a horizontal one on the left ruler at its y, as one undo step, shown even when From c6e29fa22780d339c0c9e1da405e89bd420a0831 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 17:40:14 -0800 Subject: [PATCH 05/83] PDF export: PDF/X-1a, X-3 and 1.3 keep the art under the hidden part of cropped art Flattening for PDF/X-1a, PDF/X-3, PDF 1.3 and EPS rasterized a picture, gradient, pattern, mesh or raster effect over its whole frame when a clipping mask cropped it. The hidden part came out as opaque white and covered the art under it, on the same page and on the next one. - Flattening rasterizes clipped art only where its clipping path shows it, nested clip groups included. - Art in a clipping layer is flattened as the layer's clipping path shows it. A flattened group that also holds art from outside the layer takes the place of that art, so the layer's clipping path no longer cuts it. Documents in which no clip group hides flattened art, and no clipping layer holds it, export the same bytes as before. --- crates/engine/src/cmd/fileio/tests_eps.rs | 22 ++ crates/engine/src/cmd/fileio/tests_pdfx.rs | 315 +++++++++++++++++++++ crates/engine/src/cmd/flatten.rs | 4 +- crates/engine/src/cmd/flatten/apply.rs | 97 ++++++- crates/engine/src/cmd/flatten/commands.rs | 2 +- crates/engine/src/cmd/flatten/compose.rs | 26 +- docs/mcp.md | 2 + docs/target-app-parity.md | 1 + 8 files changed, 459 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index af918d33ee..8e2c1d429a 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -170,6 +170,28 @@ fn transparency_is_flattened_with_the_flattener_preset() { assert!(e.contains("preset"), "{e}"); } +/// A picture cropped by a clipping path, in a clip group at 80%, over a square that only the +/// hidden part of the picture covers: the file prints the square, and its image is as large as +/// the crop, with the default preset (a rectangle of image) and with High Resolution (an image +/// clipped to its regions). +#[test] +fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() { + use super::tests_pdfx::{Art, CROP, cropped, drawn, lost, shown_image_sizes}; + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + for preset in ["medium", "high"] { + let (mut s, _) = cropped("rgb", 400.0, Art::Image { see_through: false }); + s.execute("transparency.set", &json!({"opacity": 80})).unwrap(); + let canvas = drawn(&s.doc().unwrap().doc); + let opts = json!({"artboards": [0], "flattenerPreset": preset, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.exportEps", &opts).unwrap(); + // What the file prints, not the document it carries. + let back = vectorcraft_eps::import_with(&b64(&r), false).unwrap().document; + assert_eq!(lost(&canvas, &drawn(&back)), 0, "{preset}: art went missing"); + let sizes = shown_image_sizes(&back); + assert!(!sizes.is_empty() && sizes.iter().all(|(w, h)| *w <= CROP[2] + 1.0 && *h <= CROP[3] + 1.0), "{preset}: the images show {sizes:?}"); + } +} + #[test] fn overprints_are_kept_or_discarded() { let mut s = session(100.0, 100.0, 1); diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index abd1bbe4a3..4063e090d6 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -186,3 +186,318 @@ fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() { let ink = image_inks_at(&back, vectorcraft_geom::Point::new(88.0, 50.0)).expect("a CMYK image behind the see-through pixels"); assert!(ink.iter().zip(teal).all(|(a, b)| (a - b).abs() <= 1.5 / 255.0), "{ink:?} is not {teal:?}"); } + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The art a clip group crops in [`cropped`]. +#[derive(Clone, Copy)] +pub(super) enum Art { + /// A 240 × 160 image, with see-through pixels or without. + Image { see_through: bool }, + /// A rectangle with a gradient fill. + Gradient, + /// A rectangle with a drop shadow. + Shadow, +} + +/// Where [`cropped`] puts the cropped art, [x, y, width, height]. +const FRAME: [f64; 4] = [40.0, 40.0, 240.0, 160.0]; +/// The part of [`FRAME`] the clipping path of [`cropped`] shows. +pub(super) const CROP: [f64; 4] = [50.0, 50.0, 80.0, 60.0]; + +/// A `mode` document whose first artboard is `width` wide, with a dark square and, over it, `art` +/// filling [`FRAME`] in a clip group that shows [`CROP`] of it. The square lies inside the frame +/// and outside the crop: only the hidden part of the art covers it. → the session with the clip +/// group selected, and the group's id. +pub(super) fn cropped(mode: &str, width: f64, art: Art) -> (Session, u64) { + cropped_by(mode, width, art, false) +} + +/// [`cropped`], with the art and its clipping path in a clipping layer above the square's layer +/// when `layer`. → the session and the clip group's or the layer's id. +fn cropped_by(mode: &str, width: f64, art: Art, layer: bool) -> (Session, u64) { + let [x, y, w, h] = FRAME; + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": width, "height": 300, "colorMode": mode})); + run(&mut s, "shape.rectangle", json!({"x": 180, "y": 90, "width": 60, "height": 60})); + run(&mut s, "paint.setFill", json!({"color": "#203040"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let layer = layer.then(|| run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + let art = match art { + Art::Image { see_through } => { + let mut png = vec![]; + image::RgbaImage::from_fn(240, 160, |x, y| { + image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }]) + }) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let placed = + run(&mut s, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME})); + placed["ids"][0].clone() + } + Art::Gradient | Art::Shadow => { + let id = run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone(); + run(&mut s, "paint.setStroke", json!({"none": true})); + if matches!(art, Art::Gradient) { + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + run(&mut s, "paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}})); + } else { + run(&mut s, "paint.setFill", json!({"color": "#c04020"})); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [id]})); + } + id + } + }; + let [x, y, w, h] = CROP; + let clip = run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone(); + if let Some(layer) = layer { + run(&mut s, "layer.clippingMask.toggle", json!({"id": layer})); + run(&mut s, "select.set", json!({"ids": [art]})); + return (s, layer); + } + run(&mut s, "select.set", json!({"ids": [art, clip]})); + let group = run(&mut s, "object.clippingMask.make", json!({}))["id"].as_u64().unwrap(); + (s, group) +} + +/// `document.exportPdf` with `p`, read back. +fn read_back(s: &mut Session, p: &Value) -> vectorcraft_doc::Document { + let v = run(s, "document.exportPdf", p.clone()); + vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap() +} + +/// `doc`'s artboards drawn on white at 72 ppi. +pub(super) fn drawn(doc: &vectorcraft_doc::Document) -> vectorcraft_render::Rendered { + let pages = doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap(); + vectorcraft_render::Renderer::new().render_region(doc, pages, 1.0, true) +} + +/// How many pixels show art in `reference` and are blank in `variant`. +pub(super) fn lost(reference: &vectorcraft_render::Rendered, variant: &vectorcraft_render::Rendered) -> usize { + assert_eq!((reference.width, reference.height), (variant.width, variant.height)); + let (reference, variant) = (reference.pixels.as_chunks::<4>().0, variant.pixels.as_chunks::<4>().0); + reference.iter().zip(variant).filter(|(r, v)| r[..3].iter().any(|c| *c < 200) && v[..3].iter().all(|c| *c >= 250)).count() +} + +/// The width and height of what each of `doc`'s images shows: its frame inside the clipping +/// paths around it. +pub(super) fn shown_image_sizes(doc: &vectorcraft_doc::Document) -> Vec<(f64, f64)> { + use vectorcraft_geom::Rect; + fn visit(n: &vectorcraft_doc::Node, clip: Option, out: &mut Vec<(f64, f64)>) { + let within = |r: Rect| clip.map_or(r, |c| c.intersect(r)); + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + let frame = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)); + let shown = within(frame); + out.push((shown.width(), shown.height())); + } + let clip = if n.clips() { n.visual_bounds().map(within) } else { clip }; + for c in n.children().into_iter().flatten() { + visit(c, clip, out); + } + } + let mut out = vec![]; + for l in &doc.layers { + visit(l, None, &mut out); + } + out +} + +/// Checks that the PDF/X-1a, PDF/X-3 and PDF 1.3 files of `s` (with `extra` options) show all the +/// art the file with transparency shows, and that no image in them shows more than [`CROP`]. Adds +/// what is wrong to `wrong`. +fn check_flat_files(s: &mut Session, extra: &Value, what: &str, wrong: &mut Vec) { + let reference = drawn(&read_back(s, extra)); + for flat in [json!({"standard": "pdfX1a"}), json!({"standard": "pdfX3"}), json!({"compatibility": "1.3", "preserveEditing": false})] { + let mut p = flat.clone(); + super::pdf::merge(&mut p, extra); + let back = read_back(s, &p); + let lost = lost(&reference, &drawn(&back)); + if lost > 0 { + wrong.push(format!("{what}, {flat}: {lost} pixels of art went missing")); + } + let sizes = shown_image_sizes(&back); + // An image reaches a pixel past its regions, and a group rasterized whole a point past + // its visible bounds. + if sizes.is_empty() || sizes.iter().any(|(w, h)| *w > CROP[2] + 3.0 || *h > CROP[3] + 3.0) { + wrong.push(format!("{what}, {flat}: the images show {sizes:?}")); + } + } +} + +/// Art cropped by a clipping path, in a PDF file without transparency: the part of the art the +/// clipping path hides is not rasterized, so art that lies under the hidden part alone still +/// shows. Each case is one way the cropped art comes to be flattened. +#[test] +fn flattening_cropped_art_for_pdfx_keeps_the_art_under_its_hidden_part() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let opaque = Art::Image { see_through: false }; + type Change = fn(&mut Session, u64); + let cases: [(&str, Art, Change); 9] = [ + ("an image with see-through pixels", Art::Image { see_through: true }, |_, _| {}), + ("a clip group with opacity", opaque, |s, _| { + run(s, "transparency.set", json!({"opacity": 80})); + }), + ("a clip group with a blend mode", opaque, |s, _| { + run(s, "transparency.set", json!({"blendMode": "multiply"})); + }), + ("a see-through object over the crop", opaque, |s, _| { + run(s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 40, "height": 30})); + run(s, "paint.setFill", json!({"color": "#ffffff"})); + run(s, "transparency.set", json!({"opacity": 60})); + }), + ("a gradient", Art::Gradient, |s, _| { + run(s, "transparency.set", json!({"opacity": 80})); + }), + ("a raster effect", Art::Shadow, |_, _| {}), + ("a clip group inside a clip group", Art::Image { see_through: true }, |s, group| { + let outer = run(s, "shape.rectangle", json!({"x": 45, "y": 45, "width": 85, "height": 65}))["id"].clone(); + run(s, "select.set", json!({"ids": [group, outer]})); + run(s, "object.clippingMask.make", json!({})); + }), + ("a clip group inside a group with opacity", opaque, |s, _| { + run(s, "object.group", json!({})); + run(s, "transparency.set", json!({"opacity": 80})); + }), + ("an even-odd compound clipping path", opaque, |s, group| { + run(s, "transparency.set", json!({"opacity": 80})); + let doc = s.doc_mut().unwrap(); + let mut d = (*doc.doc).clone(); + let clip = d.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id; + let mut ring = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(50.0, 50.0, 130.0, 110.0)); + ring.subpaths.extend(vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(70.0, 65.0, 110.0, 95.0)).subpaths); + if let vectorcraft_doc::NodeKind::Path { path, rule, .. } = &mut d.node_mut(clip).unwrap().kind { + (*path, *rule) = (ring, vectorcraft_geom::FillRule::EvenOdd); + } + doc.doc = d.into(); + }), + ]; + let mut wrong = vec![]; + for mode in ["cmyk", "rgb"] { + for (what, art, change) in cases { + let (mut s, group) = cropped(mode, 400.0, art); + change(&mut s, group); + check_flat_files(&mut s, &json!({}), &format!("{mode}: {what}"), &mut wrong); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The same with the Medium and Low Resolution presets, and with a balance of 0, which rasterizes +/// the whole group of the cropped art over the group's visible bounds. +#[test] +fn flattening_cropped_art_for_pdfx_keeps_the_art_under_its_hidden_part_with_each_preset() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut wrong = vec![]; + for extra in [json!({"flattenerPreset": "medium"}), json!({"flattenerPreset": "low"}), json!({"flattener": {"balance": 0}})] { + for (art, name) in [(Art::Image { see_through: true }, "image"), (Art::Gradient, "gradient")] { + let (mut s, _) = cropped("cmyk", 400.0, art); + run(&mut s, "transparency.set", json!({"opacity": 80})); + check_flat_files(&mut s, &extra, &format!("{name}, {extra}"), &mut wrong); + } + } + // A cropped rectangle with a solid fill, rasterized whole. + let (mut s, group) = cropped("cmyk", 400.0, Art::Gradient); + let art = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[1].id.0; + run(&mut s, "paint.setFill", json!({"ids": [art], "color": "#c04020"})); + run(&mut s, "transparency.set", json!({"ids": [group], "opacity": 80})); + check_flat_files(&mut s, &json!({"flattener": {"balance": 0}}), "solid fill, balance 0", &mut wrong); + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The hidden part of cropped art on one artboard lies over the next artboard: that page keeps +/// its art. +#[test] +fn flattening_cropped_art_for_pdfx_keeps_the_next_page_under_its_hidden_part() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + // The crop is on the first artboard, and the square on the second. + let (mut s, _) = cropped("cmyk", 150.0, Art::Image { see_through: true }); + run(&mut s, "artboard.new", json!({"x": 170, "y": 0, "width": 230, "height": 300})); + assert_eq!(read_back(&mut s, &json!({"standard": "pdfX1a"})).artboards.len(), 2); + let mut wrong = vec![]; + check_flat_files(&mut s, &json!({}), "two artboards", &mut wrong); + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Art cropped by a clipping layer, over a square in the layer below: the square keeps showing, +/// also with a second square in that layer under both the crop and the hidden part, or with a +/// see-through rectangle over both in a layer above. +#[test] +fn flattening_art_of_a_clipping_layer_for_pdfx_keeps_the_art_under_its_hidden_part() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + type Change = fn(&mut Session, u64); + let cases: [(&str, Change); 3] = [ + ("alone", |_, _| {}), + ("over a square under the crop's edge", |s, _| { + let below = s.doc().unwrap().doc.layers[0].id.0; + run(s, "layer.setCurrent", json!({"id": below})); + run(s, "shape.rectangle", json!({"x": 110, "y": 60, "width": 50, "height": 30})); + run(s, "paint.setFill", json!({"color": "#406020"})); + }), + ("under a see-through rectangle over the crop's edge", |s, _| { + run(s, "layer.new", json!({})); + run(s, "shape.rectangle", json!({"x": 110, "y": 60, "width": 50, "height": 30})); + run(s, "paint.setFill", json!({"color": "#406020"})); + run(s, "transparency.set", json!({"opacity": 60})); + }), + ]; + let mut wrong = vec![]; + for mode in ["cmyk", "rgb"] { + for art in [Art::Image { see_through: true }, Art::Gradient] { + for (what, change) in cases { + let (mut s, layer) = cropped_by(mode, 400.0, art, true); + run(&mut s, "transparency.set", json!({"opacity": 80})); + change(&mut s, layer); + check_flat_files(&mut s, &json!({}), &format!("{mode}: a clipping layer {what}"), &mut wrong); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Documents in which no clip group hides art export the same bytes as they did when the +/// flattener rasterized hidden art too. +#[test] +fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + use crate::cmd::flatten::with_clips_ignored as before; + // Written at one time, so two files differ only by what they draw. + let bytes = |s: &mut Session, p: &Value| super::pdf::encode_at("document.exportPdf", &s.doc().unwrap().doc, p, Some(1_700_000_000)).unwrap().0; + let files = [ + json!({"standard": "pdfX1a"}), + json!({"standard": "pdfX3"}), + json!({"compatibility": "1.3", "preserveEditing": false}), + json!({"standard": "pdfX1a", "flattener": {"balance": 0}}), + json!({"standard": "pdfX1a", "flattenerPreset": "low"}), + ]; + // Transparency without a clip group. + let mut plain = session(); + // A clip group at 80% whose clipping path is as large as its art, over the edge of a square. + let mut fitted = Session::new(); + run(&mut fitted, "file.new", json!({"width": 400, "height": 300, "colorMode": "cmyk"})); + run(&mut fitted, "shape.rectangle", json!({"x": 180, "y": 90, "width": 160, "height": 160})); + run(&mut fitted, "paint.setFill", json!({"color": "#203040"})); + let mut png = vec![]; + image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let photo = + run(&mut fitted, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}))["ids"][0] + .clone(); + let [x, y, w, h] = FRAME; + let clip = run(&mut fitted, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone(); + run(&mut fitted, "select.set", json!({"ids": [photo, clip]})); + run(&mut fitted, "object.clippingMask.make", json!({})); + run(&mut fitted, "transparency.set", json!({"opacity": 80})); + // Cropped art that is not flattened: nothing on it is see-through. + let (mut opaque, _) = cropped("cmyk", 400.0, Art::Image { see_through: false }); + for (what, s) in [("no clip group", &mut plain), ("a clipping path as large as its art", &mut fitted), ("opaque cropped art", &mut opaque)] { + for p in &files { + assert!(bytes(s, p) == before(|| bytes(s, p)), "{what}, {p}"); + } + } + // Art that a clip group hides is what changes. + let (mut s, _) = cropped("cmyk", 400.0, Art::Image { see_through: true }); + assert!(bytes(&mut s, &files[0]) != before(|| bytes(&mut s, &files[0]))); +} diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 2a12eb9c5e..f950f8c1da 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,9 +49,9 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -#[cfg(test)] -pub(crate) use apply::with_every_region; pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images}; +#[cfg(test)] +pub(crate) use apply::{with_clips_ignored, with_every_region}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index c70f4dca6c..c9459ed76c 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -107,7 +107,9 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let art: Vec = baked.layers[0].children().into_iter().flatten().map(|a| (**a).clone()).collect(); let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() }; let plain: Vec = art.iter().map(|n| sc.plain(n)).collect(); - let reaches: Vec> = plain.iter().map(reach).collect(); + // Each object as its clip groups and clipping layers show it. + let clipped: Vec = plain.iter().zip(roots).map(|(n, id)| clipped_by_ancestors(src, *id, n)).collect(); + let reaches: Vec> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect(); let see_through: Vec = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; @@ -117,7 +119,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: vectorcraft_doc::cancel::check()?; let ids: Vec = g.iter().map(|&i| roots[i]).collect(); let group = g.iter().any(|&i| see_through[i]).then(|| { - let plain: Vec<&Node> = g.iter().map(|&i| &plain[i]).collect(); + let plain: Vec<&Node> = g.iter().map(|&i| &clipped[i]).collect(); flatten_group(&plain, o, cmyk) }); let Some((regions, area)) = group.flatten() else { @@ -126,7 +128,9 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: }; let raster = match area.as_ref().filter(|_| render) { Some(a) => { - let art: Vec = g.iter().map(|&i| art[i].clone()).collect(); + // Drawn as planned: the image can land outside the clip groups and clipping layers + // around its art. + let art: Vec = g.iter().map(|&i| clipped_by_ancestors(src, roots[i], &art[i])).collect(); Some(render_raster(&baked, &art, a.rect, a.ppi, a.clip.clone(), o)?) } None => None, @@ -140,6 +144,39 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: Ok(out) } +/// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and +/// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping +/// path. `plain` itself when nothing around it clips. +fn clipped_by_ancestors(src: &Document, id: NodeId, plain: &Node) -> Node { + let mut out = plain.clone(); + if !clips_count() { + return out; + } + let ancestry = src.ancestry(id).unwrap_or_default(); + for pair in ancestry.windows(2).rev() { + let Some(above) = src.node(pair[0]).filter(|n| n.clips()) else { continue }; + let Some(clip) = above.children().and_then(|c| c.first()) else { continue }; + // The clipping path itself is not clipped art. + if clip.id == pair[1] { + continue; + } + // Its outline, unpainted: the group or layer around the object still paints the path. + // Nothing to clip by hides the clipped art, as in the compositor. + let Some((outline, rule)) = effects::clip_outline(clip) else { + out.visible = false; + return out; + }; + let mut path = Node::path(clip.id, PathData::from_bezpath(&outline), Appearance::default()); + if let NodeKind::Path { rule: r, .. } = &mut path.kind { + *r = rule; + } + let mut g = Node::group(above.id, vec![Arc::new(path), Arc::new(out)]); + g.set_clips(true); + out = g; + } + out +} + /// The regions and the image area replacing one group of overlapping objects (`plain`: the art as /// composited; `cmyk`: in a CMYK document); `None` when it paints nothing. fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Regions, Option)> { @@ -163,8 +200,10 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg let mut complex: Vec = vec![]; let mut gradients_only = !all; for (k, r) in regions.iter().enumerate() { - if all || r.sources.iter().any(|&i| b.kinds[i] != Kind::Vector) { - gradients_only &= r.sources.iter().all(|&i| b.kinds[i] == Kind::Gradient); + // Art outside the clipping path of its clip group draws nothing there. + let shown = |i: &&usize| b.kinds[**i] == Kind::Vector || !(clips_count() && b.hidden(**i, &r.sources)); + if all || r.sources.iter().filter(shown).any(|&i| b.kinds[i] != Kind::Vector) { + gradients_only &= r.sources.iter().filter(shown).all(|&i| b.kinds[i] == Kind::Gradient); complex.push(k); } else if let Some(fill) = region_fill(&elems, &r.sources, o, cmyk) { vector.push((k, fill)); @@ -227,6 +266,35 @@ pub(crate) fn with_every_region(f: impl FnOnce() -> T) -> T { out } +#[cfg(test)] +thread_local! { + /// Groups flattened on this thread rasterize art where its clip group or clipping layer hides + /// it too ([`with_clips_ignored`]). + static CLIPS_IGNORED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether a region outside the clipping path of a clip group or clipping layer leaves out the +/// art it hides there. +#[cfg(test)] +fn clips_count() -> bool { + !CLIPS_IGNORED.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn clips_count() -> bool { + true +} + +/// `f` with every group it flattens rasterizing art where its clip group or clipping layer hides +/// it too. +#[cfg(test)] +pub(crate) fn with_clips_ignored(f: impl FnOnce() -> T) -> T { + CLIPS_IGNORED.with(|e| e.set(true)); + let out = f(); + CLIPS_IGNORED.with(|e| e.set(false)); + out +} + /// The flat colour of a region covered by `sources` (CMYK in a `cmyk` document); `None` where /// nothing paints it. fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool) -> Option { @@ -424,7 +492,7 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan let one_pass = separate(d, &plan.flat.iter().flat_map(|f| f.roots.iter().copied()).collect::>()); for f in plan.flat { // A group always has objects. - let Some(&top) = f.roots.last() else { continue }; + let Some(top) = place_of(d, &f.roots) else { continue }; let mut children = vec![]; // The image goes under the regions, reaching a pixel past its own: their edges then fall on // matching pixels instead of on what is behind the group. @@ -494,6 +562,23 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan Ok((ids, vector, rasterized)) } +/// The object of `roots` (in paint order) whose place their flattened group takes: the topmost one +/// that no clip group or clipping layer clips unless it clips every object of `roots`, else the +/// topmost one. +fn place_of(d: &Document, roots: &[NodeId]) -> Option { + let top = roots.last().copied(); + if !clips_count() || roots.len() < 2 { + return top; + } + let clips = |id: NodeId| -> Vec { + let ancestry = d.ancestry(id).unwrap_or_default(); + ancestry.iter().rev().skip(1).filter(|a| d.node(**a).is_some_and(Node::clips)).copied().collect() + }; + let all: Vec> = roots.iter().map(|r| clips(*r)).collect(); + let shared = |mine: &Vec| mine.iter().all(|c| all.iter().all(|theirs| theirs.contains(c))); + roots.iter().zip(&all).rev().find(|(_, mine)| shared(mine)).map(|(r, _)| *r).or(top) +} + /// An image of `r` (in a clip group when it is clipped). fn raster_node(d: &mut Document, r: Raster) -> Node { let key = unique_key(d, "flattened"); diff --git a/crates/engine/src/cmd/flatten/commands.rs b/crates/engine/src/cmd/flatten/commands.rs index a2edde1f0f..d528e40d8b 100644 --- a/crates/engine/src/cmd/flatten/commands.rs +++ b/crates/engine/src/cmd/flatten/commands.rs @@ -10,7 +10,7 @@ pub fn specs() -> Vec { "Flatten Transparency…", ["Object"], None, - "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach; objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_doc, flatten ), diff --git a/crates/engine/src/cmd/flatten/compose.rs b/crates/engine/src/cmd/flatten/compose.rs index 0598905348..fef23f86ae 100644 --- a/crates/engine/src/cmd/flatten/compose.rs +++ b/crates/engine/src/cmd/flatten/compose.rs @@ -53,6 +53,11 @@ enum Body { pub(super) struct Builder { pub(super) shapes: Vec, pub(super) kinds: Vec, + /// Per shape, the clipping path of the innermost clip group it is in (a clipping path's own + /// entry is the clip group around its group). + pub(super) clip_of: Vec>, + /// The clipping path of the clip group being built. + pub(super) clip: Option, /// Building a CMYK document's art. pub(super) cmyk: bool, } @@ -72,9 +77,24 @@ impl Builder { path.bounds()?; self.shapes.push(po::Shape::new(path, rule, self.shapes.len() as u64)); self.kinds.push(kind); + self.clip_of.push(self.clip); Some(self.shapes.len() - 1) } + /// Whether a clip group hides shape `shape` in the region `sources` cover (ascending): the + /// region lies outside one of the clipping paths around the shape. + pub(super) fn hidden(&self, shape: usize, sources: &[usize]) -> bool { + let around = |shape: usize| self.clip_of.get(shape).copied().flatten(); + let mut clip = around(shape); + while let Some(c) = clip { + if sources.binary_search(&c).is_err() { + return true; + } + clip = around(c); + } + false + } + pub(super) fn elem(&mut self, n: &Node) -> Option { if !n.visible { return None; @@ -93,7 +113,11 @@ impl Builder { } else { (None, &children[..]) }; - Body::Group { clip, children: rest.iter().filter_map(|c| self.elem(c)).collect() } + let outer = self.clip; + self.clip = clip.or(outer); + let children = rest.iter().filter_map(|c| self.elem(c)).collect(); + self.clip = outer; + Body::Group { clip, children } } NodeKind::Path { guide: true, .. } => return None, NodeKind::Path { .. } | NodeKind::Compound { .. } => { diff --git a/docs/mcp.md b/docs/mcp.md index bc20483938..face503682 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3061,6 +3061,8 @@ one undo step. The targets split into groups of overlapping objects; groups with Each other group becomes one group of atomic regions: paths filled with the flat colour the art showed there (over white, which blend modes do not read; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, opacity masks or raster effects reach (clipped to those regions with `clipComplexRegions`, a rectangle without). +The image leaves out the part of such art that the clipping path of a clip group or clipping layer hides, so art under +the hidden part of a cropped picture stays as it is. `preset` is `high`, `medium` (the default) or `low`; option keys (`balance` 0–100, `lineArtPpi`, `gradientPpi`, `textToOutlines`, `strokesToOutlines`, `clipComplexRegions`, `antiAlias`, `preserveAlpha`, `preserveOverprints`) override it, at the top level or in `options`. `balance: 0` rasterizes everything; lower balances rasterize groups diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6bf45e9c82..5e291ded52 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1413,6 +1413,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. + PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). 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`). From 52efba54aa75ccf97c7569daee0b5fadcb5e1881 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 17:46:36 -0800 Subject: [PATCH 06/83] =?UTF-8?q?Scripts:=20File=20=E2=80=BA=20Scripts=20l?= =?UTF-8?q?ists=20the=20Scripts=20folder,=20subfolders=20as=20submenus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Scripts now lists the .js and .jsx files of the Scripts folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script…. The help page describes this listing: https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html Choosing a listed script runs it through script.run without the warning Other Script… shows. script.listInstalled returns the same listing, and ui.runInstalledScript {path} runs one entry. VectorCraft's own rules: the folder is read off the UI thread when the app starts, when its window becomes active and when the File menu of the window's menu bar opens; only names are read; links, junctions, hidden and system entries are left out and checked again before a run; one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms and the menu then notes that some scripts were not listed. Under an automation read root, script.listInstalled and ui.menu.list leave out a folder outside the root. #1183 (LloydNicholson) also proposed a Scripts menu listing a folder. --- apps/vectorcraft-cli/src/main.rs | 5 +- apps/vectorcraft/src/main.rs | 2 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/src/cmd/scripts.rs | 55 ++++ crates/engine/src/lib.rs | 3 + crates/engine/src/script/folder.rs | 287 ++++++++++++++++++++ crates/engine/src/script/mod.rs | 2 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_folder.rs | 323 ++++++++++++++++++++++ crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus/bar.rs | 11 + crates/ui-egui/src/menus/entries.rs | 10 +- crates/ui-egui/src/menus/invoke.rs | 5 +- crates/ui-egui/src/menus/labels.rs | 20 +- crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/tests.rs | 51 ++++ crates/ui-egui/src/menus/tree.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/native_menu.rs | 4 +- crates/ui-egui/src/palette.rs | 5 +- crates/ui-egui/src/scripts_menu.rs | 225 ++++++++++++++++ crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/scripts_menu.rs | 329 +++++++++++++++++++++++ docs/gaps.md | 6 +- docs/mcp.md | 48 ++++ docs/target-app-parity.md | 1 + 55 files changed, 1468 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/script/folder.rs create mode 100644 crates/engine/src/tests/script_folder.rs create mode 100644 crates/ui-egui/src/scripts_menu.rs create mode 100644 crates/ui-egui/src/tests/scripts_menu.rs diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 57b3d41224..fab468c391 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -237,9 +237,10 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders -/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply -/// as they do there. +/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there +/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { + prefs_dir::attach_scripts_dir(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index b97ee681fe..bb94bad1cc 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -463,6 +463,8 @@ fn main() -> std::process::ExitCode { let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag); prefs_dir::attach_plugin_store(&mut session); + // File › Scripts lists the scripts of the Scripts folder next to the preferences. + prefs_dir::attach_scripts_dir(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 063d9b1aa1..96e09f5e78 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -57,6 +57,14 @@ pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { } } +/// Have File › Scripts and `script.listInstalled` list the scripts of the `Scripts` folder. The +/// folder is only read: the user makes it. +pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Scripts") { + session.attach_scripts_dir(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b8b5448817..a80fb2e0ff 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -45,6 +45,15 @@ pub fn specs() -> Vec { always, stop ), + cmd!( + query "script.listInstalled", + "List Installed Scripts", + [], + None, + "{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", + always, + list_installed + ), cmd!( query "script.check", "Check Script", @@ -146,6 +155,52 @@ fn stop(s: &mut Session, _: &Value) -> Result { Ok(json!({"stopped": s.script_request_stop()})) } +/// The error for a script that File › Scripts listed and that [`script::folder::read`] no longer +/// reads. +pub const NOT_LISTED: &str = "the script is no longer in the Scripts folder"; + +impl Session { + /// Have File › Scripts and `script.listInstalled` list the scripts of the folder `dir`. The + /// folder is only read, and never made. + pub fn attach_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.scripts_dir = Some(dir); + } + + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. + pub fn scripts_dir(&self) -> Option<&std::path::Path> { + self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// The text of the script at `path`, which a listing of the Scripts folder gave + /// ([`script::folder::read`]), checked as `script.run` checks a file's. + pub fn installed_script(&self, path: &str) -> Result { + let root = self.scripts_dir().ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?; + crate::file_access::check_read(path).map_err(EngineError::Other)?; + // One byte more than a script may have shows that the file is too large. + let bytes = script::folder::read(root, std::path::Path::new(path), script::MAX_SOURCE_BYTES + 1) + .ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(EngineError::Other(TOO_LARGE.to_string())); + } + script_text(&bytes) + } +} + +fn list_installed(s: &mut Session, _: &Value) -> Result { + let Some(root) = s.scripts_dir() else { + return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})); + }; + let folder = root.to_string_lossy(); + crate::file_access::check_read(&folder).map_err(EngineError::Other)?; + let listing = script::folder::list(root); + let scripts: Vec = listing + .scripts() + .into_iter() + .map(|(folders, label, path)| json!({"path": path.to_string_lossy(), "label": label, "folders": folders})) + .collect(); + Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable})) +} + /// The folder a script is in, which its included files are read from. struct Folder { dir: std::path::PathBuf, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 043158c582..97c4717266 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -168,6 +168,9 @@ pub struct Session { /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, + /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder + /// ([`Session::attach_scripts_dir`]). + scripts_dir: Option, /// The plug-in ids whose grant in the plug-in store should be gone but could not be removed: /// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful /// [`Session::store_grant`] for the id takes it out. diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs new file mode 100644 index 0000000000..4453953d80 --- /dev/null +++ b/crates/engine/src/script/folder.rs @@ -0,0 +1,287 @@ +//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a +//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]). +//! +//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic +//! link or a Windows junction is left out, whether it is a file, a folder or the Scripts folder +//! itself, so a listed script is a plain file in plain folders under the Scripts folder. Names that +//! start with a dot, files and folders Windows marks hidden or system, names that are not Unicode +//! and names longer than [`MAX_NAME_BYTES`] are left out too, and so is a folder with no script in +//! it. +//! +//! The values here are VectorCraft's own limits: [`MAX_ENTRIES`], [`MAX_SCRIPTS`], [`MAX_FOLDERS`], +//! [`MAX_DEPTH`], [`MAX_NAME_BYTES`], [`MAX_LABEL_CHARS`] and [`MAX_SCAN`]. A listing that reaches +//! one of them, or that cannot read a subfolder, keeps what it found and says so +//! ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Component, Path, PathBuf}; +use std::time::Duration; + +use crate::cmd::scripts::runs; + +/// The most folder entries one listing looks at, in the Scripts folder and its subfolders together. +pub const MAX_ENTRIES: usize = 2048; +/// The most scripts one listing holds. +pub const MAX_SCRIPTS: usize = 512; +/// The most subfolders one listing reads. +pub const MAX_FOLDERS: usize = 128; +/// How many levels of subfolders a listing reads below the Scripts folder. +pub const MAX_DEPTH: usize = 4; +/// The longest file or folder name a listing takes, in UTF-8 bytes. +pub const MAX_NAME_BYTES: usize = 255; +/// The most characters of a label; a longer one ends in `…`. +pub const MAX_LABEL_CHARS: usize = 128; +/// How long one listing may take before it stops with what it found. +pub const MAX_SCAN: Duration = Duration::from_millis(250); + +/// The limits of one listing. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub entries: usize, + pub scripts: usize, + pub folders: usize, + pub depth: usize, + pub time: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Limits { entries: MAX_ENTRIES, scripts: MAX_SCRIPTS, folders: MAX_FOLDERS, depth: MAX_DEPTH, time: MAX_SCAN } + } +} + +/// One row of a listing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Entry { + /// A script: its label (the file name without its extension) and the file's path as the folder + /// gave it. + Script { label: String, path: PathBuf }, + /// A subfolder with at least one script in it or below it: its label (the folder's name) and + /// its rows. + Folder { label: String, entries: Vec }, +} + +/// What a Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The rows of the folder itself, sorted ([`list_with`]). + pub entries: Vec, + /// Some scripts may be missing: a limit was reached or a subfolder could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +impl Listing { + /// Every script with the labels of the folders it is in, in menu order. + pub fn scripts(&self) -> Vec<(Vec<&str>, &str, &Path)> { + fn walk<'a>(entries: &'a [Entry], folders: &mut Vec<&'a str>, out: &mut Vec<(Vec<&'a str>, &'a str, &'a Path)>) { + for e in entries { + match e { + Entry::Script { label, path } => out.push((folders.clone(), label, path)), + Entry::Folder { label, entries } => { + folders.push(label); + walk(entries, folders, out); + folders.pop(); + } + } + } + } + let mut out = vec![]; + walk(&self.entries, &mut vec![], &mut out); + out + } +} + +/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives +/// an empty listing. +pub fn list(root: &Path) -> Listing { + let start = std::time::Instant::now(); + list_with(root, &Limits::default(), &mut || start.elapsed()) +} + +/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken. +/// Each level is sorted by label without regard to case, then by label, then by file name, with +/// scripts and subfolders mixed. Two rows of one level never share a label unless both were cut: +/// a script whose label another row has shows its whole file name. +pub fn list_with(root: &Path, limits: &Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + // Paths leave as text (menu params, `script.listInstalled`). + if root.to_str().is_none() { + return unreadable; + } + let mut scan = Scan { limits, elapsed, visited: 0, scripts: 0, folders: 0, truncated: false, stopped: false }; + match scan.level(root, 0) { + Some(entries) => Listing { entries, truncated: scan.truncated, unreadable: false }, + None => unreadable, + } +} + +/// A script or subfolder found in one folder, before the subfolders are read. +struct Found { + name: String, + label: String, + folder: bool, +} + +struct Scan<'a> { + limits: &'a Limits, + elapsed: &'a mut dyn FnMut() -> Duration, + visited: usize, + scripts: usize, + folders: usize, + truncated: bool, + /// The entry or time limit was reached: nothing more is read. + stopped: bool, +} + +impl Scan<'_> { + /// The rows of the folder `dir`, which is `depth` levels below the Scripts folder; `None` when + /// it cannot be read. + fn level(&mut self, dir: &Path, depth: usize) -> Option> { + let mut found: Vec = vec![]; + for entry in std::fs::read_dir(dir).ok()? { + if self.visited >= self.limits.entries || (self.elapsed)() > self.limits.time { + (self.truncated, self.stopped) = (true, true); + break; + } + self.visited += 1; + let Ok(entry) = entry else { + self.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + let Ok(kind) = entry.file_type() else { continue }; + if name.len() > MAX_NAME_BYTES || name.starts_with('.') || kind.is_symlink() || hidden(&entry) { + continue; + } + if kind.is_dir() { + found.push(Found { label: shown(&name), name, folder: true }); + } else if kind.is_file() && runs(&name) { + if self.scripts >= self.limits.scripts { + self.truncated = true; + continue; + } + self.scripts += 1; + let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem); + found.push(Found { label: shown(stem), name, folder: false }); + } + } + // A script whose label another row of this folder has shows its whole file name. + let mut count = std::collections::HashMap::::new(); + for f in &found { + *count.entry(f.label.clone()).or_default() += 1; + } + for f in found.iter_mut().filter(|f| !f.folder) { + if count.get(&f.label).is_some_and(|n| *n > 1) { + f.label = shown(&f.name); + } + } + found.sort_by(|a, b| (a.label.to_lowercase(), &a.label, &a.name).cmp(&(b.label.to_lowercase(), &b.label, &b.name))); + let mut out = Vec::with_capacity(found.len()); + for f in found { + let path = dir.join(&f.name); + if !f.folder { + out.push(Entry::Script { label: f.label, path }); + continue; + } + if self.stopped { + continue; + } + if depth >= self.limits.depth || self.folders >= self.limits.folders { + self.truncated = true; + continue; + } + self.folders += 1; + match self.level(&path, depth + 1) { + Some(entries) if entries.is_empty() => {} + Some(entries) => out.push(Entry::Folder { label: f.label, entries }), + None => self.truncated = true, + } + } + Some(out) + } +} + +/// `name` as a menu shows it: control and bidirectional formatting characters written as escapes, +/// and at most [`MAX_LABEL_CHARS`] characters. +fn shown(name: &str) -> String { + vectorcraft_plugins::permissions::display_text(name, MAX_LABEL_CHARS) +} + +/// Does Windows mark `entry` hidden or system? +fn hidden(entry: &std::fs::DirEntry) -> bool { + entry.metadata().is_ok_and(|m| hidden_meta(&m)) +} + +/// Does Windows mark the file or folder of `m` hidden or system? +#[cfg(windows)] +fn hidden_meta(m: &std::fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt as _; + const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; + m.file_attributes() & HIDDEN_OR_SYSTEM != 0 +} + +/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. +#[cfg(not(windows))] +fn hidden_meta(_: &std::fs::Metadata) -> bool { + false +} + +/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows +/// marks hidden or system, which a listing leaves out. +fn plain(path: &Path, folder: bool, shown: bool) -> bool { + std::fs::symlink_metadata(path) + .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) +} + +/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most +/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there +/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + let Ok(rest) = path.strip_prefix(root) else { return false }; + let names: Option> = rest + .components() + .map(|c| match c { + Component::Normal(name) => name.to_str().filter(|n| !n.starts_with('.') && n.len() <= MAX_NAME_BYTES), + _ => None, + }) + .collect(); + let Some(names) = names else { return false }; + let Some((file, folders)) = names.split_last() else { return false }; + if folders.len() > MAX_DEPTH || !runs(file) || !plain(root, true, false) { + return false; + } + let mut at = root.to_path_buf(); + for folder in folders { + at.push(folder); + if !plain(&at, true, true) { + return false; + } + } + at.push(file); + plain(&at, false, true) +} + +/// The first `max` bytes of the script at `path`, or `None` when [`holds`] does not hold for it +/// before the read and again after it, or it cannot be read. The two checks leave no time in which +/// a link stood in for the file or one of its folders for the whole read; a program that swaps one +/// in and back out between a check and the open can still have another file read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9d0a47fbff..8432d21f50 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -36,6 +36,8 @@ use crate::{ Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit, }; +pub mod folder; + /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; /// The instructions a run may execute when `maxFuel` is left out. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 54d84507c5..bbe368b355 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -86,6 +86,7 @@ impl Session { profile_dir: None, color_settings_file: None, plugin_dir: None, + scripts_dir: None, ignored_plugin_grants: Default::default(), plugin_output: None, plugin_install_approval: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f6e32d719e..3b2240756c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -149,6 +149,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_folder; mod script_run; mod scripts; mod select_ids_first; diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs new file mode 100644 index 0000000000..24ef85ddfd --- /dev/null +++ b/crates/engine/src/tests/script_folder.rs @@ -0,0 +1,323 @@ +//! The Scripts folder: what a listing holds and leaves out, its order and labels, its limits, the +//! read of a listed script, `script.listInstalled` and the automation read root. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::script::folder::{self, Entry, Limits, Listing}; +use crate::*; + +/// A fresh folder for the files of test `name`, holding an empty `Scripts` folder. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-folder-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Scripts")).unwrap(); + dir +} + +/// Writes the empty file `name` (folders included) under `root`. +fn touch(root: &Path, name: &str) -> PathBuf { + let path = root.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "").unwrap(); + path +} + +/// Makes `link` lead to the folder `target`: a symbolic link, or on Windows a junction, which needs +/// no privilege. +fn link_folder(target: &Path, link: &Path) { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).unwrap(); + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap(); + assert!(made.status.success(), "mklink /J: {}", String::from_utf8_lossy(&made.stderr)); + } +} + +/// A listing's rows as text: `label`, or `label/` followed by the folder's rows in brackets. +fn rows(entries: &[Entry]) -> String { + let row = |e: &Entry| match e { + Entry::Script { label, .. } => label.clone(), + Entry::Folder { label, entries } => format!("{label}/[{}]", rows(entries)), + }; + entries.iter().map(row).collect::>().join(", ") +} + +/// A listing within `limits` that takes no time. +fn list(root: &Path, limits: Limits) -> Listing { + folder::list_with(root, &limits, &mut || Duration::ZERO) +} + +#[test] +fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { + let dir = folder("names"); + let root = dir.join("Scripts"); + for name in + ["b.js", "A.JSX", "Dessin (été) #1.jsx", "v1.2 draft.Js", "Zeta/inner.jsx", "Zeta/Deep/x.js", "notes.txt", "x.jsxbin", "lib.jsxinc", "js"] + { + touch(&root, name); + } + std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); + assert!(!listing.truncated && !listing.unreadable); + // Each script keeps the path the folder gave, whatever its label. + let paths: Vec<_> = + listing.scripts().into_iter().map(|(folders, label, path)| (folders.join("/"), label.to_string(), path.to_path_buf())).collect(); + assert_eq!(paths[0], (String::new(), "A".to_string(), root.join("A.JSX"))); + assert_eq!(paths[4], ("Zeta/Deep".to_string(), "x".to_string(), root.join("Zeta").join("Deep").join("x.js"))); + assert_eq!(paths.len(), 6); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { + let dir = folder("same"); + let root = dir.join("Scripts"); + for name in ["tidy.js", "tidy.jsx", "tidy/x.js", "alone.jsx"] { + touch(&root, name); + } + assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.jsx"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() { + let dir = folder("escapes"); + let root = dir.join("Scripts"); + // A right-to-left override, which would show the name backwards. + touch(&root, "a\u{202E}sj.js"); + let long = "n".repeat(200); + touch(&root, &format!("{long}.jsx")); + let listing = folder::list(&root); + let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); + assert_eq!(labels[0], "a\\u{202E}sj"); + assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); + assert!(folder::holds(&root, &root.join(format!("{long}.jsx")))); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn hidden_names_and_links_are_left_out() { + let dir = folder("hidden"); + let root = dir.join("Scripts"); + touch(&root, "shown.js"); + touch(&root, ".hidden.js"); + touch(&root, ".git/hook.js"); + let outside = touch(&dir, "Outside/secret.js"); + // A link out of the folder, and one back to the folder itself. + link_folder(outside.parent().unwrap(), &root.join("Out")); + link_folder(&root, &root.join("Loop")); + #[cfg(unix)] + std::os::unix::fs::symlink(&outside, root.join("linked.js")).unwrap(); + #[cfg(windows)] + { + let marked = touch(&root, "marked.js"); + assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); + } + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "shown"); + assert!(!listing.truncated && !listing.unreadable); + // Nor is a file behind a link read as a listed script. + assert!(folder::read(&root, &root.join("shown.js"), 10).is_some()); + for path in [root.join("Out").join("secret.js"), root.join("Loop").join("shown.js"), root.join(".hidden.js"), root.join("linked.js")] { + assert!(folder::read(&root, &path, 10).is_none(), "{}", path.display()); + } + // A script, or the folder it is in, that Windows marks hidden after a listing is not read. + #[cfg(windows)] + { + assert!(folder::read(&root, &root.join("marked.js"), 10).is_none()); + let inner = touch(&root, "Sub/inner.js"); + assert!(folder::read(&root, &inner, 10).is_some()); + assert!(std::process::Command::new("attrib").arg("+h").arg(root.join("Sub")).status().unwrap().success()); + assert!(folder::read(&root, &inner, 10).is_none()); + } + let _ = std::fs::remove_dir_all(root.join("Out")); + let _ = std::fs::remove_dir_all(root.join("Loop")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreadable() { + let dir = folder("root"); + let root = dir.join("Scripts"); + touch(&root, "a.js"); + assert_eq!(folder::list(&dir.join("None")), Listing::default()); + let file = touch(&dir, "file"); + assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + let link = dir.join("Link"); + link_folder(&root, &link); + assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); + let _ = std::fs::remove_dir_all(&link); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn each_limit_stops_a_listing_with_what_it_found() { + let dir = folder("limits"); + let root = dir.join("Scripts"); + for n in 0..10 { + touch(&root, &format!("s{n}.js")); + } + let all = Limits::default(); + let entries = list(&root, Limits { entries: 4, ..all }); + assert_eq!((entries.scripts().len(), entries.truncated), (4, true)); + let scripts = list(&root, Limits { scripts: 3, ..all }); + assert_eq!((scripts.scripts().len(), scripts.truncated), (3, true)); + // The clock passes the time limit at the third entry. + let mut calls = 0; + let timed = folder::list_with(&root, &all, &mut || { + calls += 1; + if calls > 2 { all.time + Duration::from_millis(1) } else { Duration::ZERO } + }); + assert_eq!((timed.scripts().len(), timed.truncated), (2, true)); + let whole = list(&root, all); + assert_eq!((whole.scripts().len(), whole.truncated), (10, false)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { + let dir = folder("depth"); + let root = dir.join("Scripts"); + touch(&root, "1/2/3/4/kept.js"); + touch(&root, "1/2/3/4/5/deeper.js"); + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); + assert!(listing.truncated); + assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); + assert!(!folder::holds(&root, &root.join("1/2/3/4/5/deeper.js"))); + let two = folder("folders"); + let root = two.join("Scripts"); + touch(&root, "a/x.js"); + touch(&root, "b/y.js"); + let listing = list(&root, Limits { folders: 1, ..Limits::default() }); + assert_eq!(rows(&listing.entries), "a/[x]"); + assert!(listing.truncated); + assert!(!folder::list(&root).truncated); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(two); +} + +#[test] +fn a_folder_with_more_scripts_than_the_limit_lists_that_many() { + let dir = folder("many"); + let root = dir.join("Scripts"); + for n in 0..folder::MAX_SCRIPTS + 40 { + touch(&root, &format!("s{n:04}.js")); + } + let listing = list(&root, Limits::default()); + assert_eq!((listing.scripts().len(), listing.truncated), (folder::MAX_SCRIPTS, true)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_read_takes_only_a_script_that_is_still_a_file_under_the_folder() { + let dir = folder("read"); + let root = dir.join("Scripts"); + let script = touch(&root, "Sub/draw.jsx"); + std::fs::write(&script, "vc.log(1);").unwrap(); + assert_eq!(folder::read(&root, &script, 100).as_deref(), Some(&b"vc.log(1);"[..])); + assert_eq!(folder::read(&root, &script, 4).as_deref(), Some(&b"vc.l"[..])); + let outside = touch(&dir, "outside.js"); + touch(&root, "notes.txt"); + for path in [outside, root.join("Sub").join("..").join("..").join("outside.js"), root.join("notes.txt"), root.join("Sub"), root.join("gone.js")] { + assert!(folder::read(&root, &path, 100).is_none(), "{}", path.display()); + } + // A folder that took the script's place is not a script. + std::fs::remove_file(&script).unwrap(); + std::fs::create_dir(&script).unwrap(); + assert!(folder::read(&root, &script, 100).is_none()); + // Nor is the script read once a link stands in for its folder. + let other = touch(&dir, "Other/draw.jsx"); + std::fs::remove_dir_all(root.join("Sub")).unwrap(); + link_folder(other.parent().unwrap(), &root.join("Sub")); + assert!(folder::read(&root, &root.join("Sub").join("draw.jsx"), 100).is_none()); + let _ = std::fs::remove_dir_all(root.join("Sub")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { + let dir = folder("command"); + let root = dir.join("Scripts"); + touch(&root, "Tidy Layers.jsx"); + touch(&root, "Export/All Artboards.js"); + let mut s = Session::new(); + assert_eq!( + s.execute("script.listInstalled", &json!({})).unwrap(), + json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) + ); + s.attach_scripts_dir(root.clone()); + let text = |p: &Path| p.to_string_lossy().into_owned(); + assert_eq!( + s.execute("script.listInstalled", &json!({})).unwrap(), + json!({ + "folder": text(&root), + "scripts": [ + {"path": text(&root.join("Export").join("All Artboards.js")), "label": "All Artboards", "folders": ["Export"]}, + {"path": text(&root.join("Tidy Layers.jsx")), "label": "Tidy Layers", "folders": []}, + ], + "truncated": false, + "unreadable": false, + }) + ); + assert!(!find_command("script.listInstalled").unwrap().journal); + assert!(s.execute("script.listInstalled", &json!({"folder": "x"})).is_err()); + // A folder that is not there yet lists nothing, and the listing does not make it. + std::fs::remove_dir_all(&root).unwrap(); + assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"], json!([])); + assert!(!root.exists()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_installed_script_is_read_as_script_run_reads_a_file() { + let dir = folder("installed"); + let root = dir.join("Scripts"); + let text = |p: &Path| p.to_string_lossy().into_owned(); + let mut s = Session::new(); + let script = touch(&root, "draw.jsx"); + std::fs::write(&script, "\u{feff}vc.log(1);").unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED, "no folder is attached"); + s.attach_scripts_dir(root.clone()); + assert_eq!(s.installed_script(&text(&script)).unwrap(), "vc.log(1);"); + std::fs::write(&script, "@JSXBIN@ES@2.0@").unwrap(); + assert!(s.installed_script(&text(&script)).unwrap_err().to_string().contains("compiled script")); + std::fs::write(&script, [0xff, 0xfe]).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), "the script is not UTF-8 text"); + std::fs::write(&script, vec![b' '; script::MAX_SOURCE_BYTES + 1]).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::TOO_LARGE); + std::fs::remove_file(&script).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED); + let outside = touch(&dir, "outside.js"); + assert_eq!(s.installed_script(&text(&outside)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { + let dir = folder("roots"); + let root = dir.join("Scripts"); + let script = touch(&root, "draw.js"); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + let mut s = Session::new(); + s.attach_scripts_dir(root.clone()); + let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); + let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); + assert!(e.to_string().contains("outside the read root"), "{e}"); + let e = crate::file_access::confine(Some(&roots), || s.installed_script(&script.to_string_lossy())).unwrap_err(); + assert!(e.to_string().contains("outside the read root"), "{e}"); + // A read root that holds the folder lets both through. + let roots = crate::file_access::AutomationRoots::new(&[&dir], &[]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || { + assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"][0]["label"], "draw"); + assert_eq!(s.installed_script(&script.to_string_lossy()).unwrap(), ""); + }); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0f5152d2bb..03823e7684 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -340,6 +340,7 @@ impl VectorcraftApp { screen_color::poll(self, ctx); self.poll_finished_work(); crate::script_runs::poll(self); + crate::scripts_menu::poll(self, ctx); if self.session.script_running() && !self.session.script_waiting() { ctx.request_repaint(); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 354d811a34..38be0d651b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2277,6 +2277,8 @@ font-technology Variable Променливи Other Layers Други слоеве Other Libraries Други библиотеки Other Library… Друга библиотека… + Some scripts were not listed Някои скриптове не са изброени + The Scripts folder cannot be read Папката Scripts не може да бъде прочетена Other Script… Друг скрипт… Out of Gamut Warning Предупреждение за излизане извън цветовата гама Out of Web Color Warning Предупреждение за цвят извън уеб палитрата diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d1fc0ea540..54924a3657 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -62,6 +62,8 @@ Scripts Skripte Check Script… Provjeri skriptu… Check Script Provjeri skriptu + Some scripts were not listed Neke skripte nisu navedene + The Scripts folder cannot be read Folder Scripts se ne može pročitati Other Script… Druga skripta… Document Setup… Postavke dokumenta… Switch Units Promijeni jedinice diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9e77ecb32f..c06987daff 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5189,6 +5189,9 @@ digits Malayalam Malaiàlam @msg the script is too large to run l'script és massa gran per executar-lo @msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script @msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar +@msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts + Some scripts were not listed Alguns scripts no s'han llistat + The Scripts folder cannot be read No es pot llegir la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat @msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index de1723b906..3c6c124162 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4402,6 +4402,9 @@ imageTrace Outline Obrys @msg the script is too large to run skript je příliš velký na spuštění @msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete @msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat +@msg the script is no longer in the Scripts folder skript už není ve složce Scripts + Some scripts were not listed Některé skripty nebyly uvedeny + The Scripts folder cannot be read Složku Scripts nelze přečíst @msg the script's run is no longer available běh skriptu již není k dispozici @msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven @msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 77687493e5..213897b138 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -55,6 +55,8 @@ Scripts Scripter Check Script… Kontrollér script… Check Script Kontrollér script + Some scripts were not listed Nogle scripter blev ikke vist + The Scripts folder cannot be read Mappen Scripts kan ikke læses Other Script… Andet script… Document Setup… Dokumentopsætning… Switch Units Skift enheder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7e2619386b..fcb3939ff2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4007,6 +4007,9 @@ theme Appearance Erscheinungsbild @msg the script is too large to run das Skript ist zu groß zum Ausführen @msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen @msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann +@msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ + Some scripts were not listed Einige Skripte wurden nicht aufgeführt + The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar @msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten @msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a95d84be33..4b1b05f037 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2250,6 +2250,9 @@ axis Both Και τα δύο @msg the script is too large to run το σενάριο είναι πολύ μεγάλο για εκτέλεση @msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο @msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί +@msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts + Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα + The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη @msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε @msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e0903d19d7..6fd604043c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4092,6 +4092,9 @@ axis Both Ambos @msg the script is too large to run el script es demasiado grande para ejecutarlo @msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script @msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar +@msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts + Some scripts were not listed Algunos scripts no se han incluido en la lista + The Scripts folder cannot be read No se puede leer la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo @msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b593200aa5..4cc9f920d9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4316,6 +4316,9 @@ imageTrace Outline Ääriviiva @msg the script is too large to run komentosarja on liian suuri suoritettavaksi @msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista @msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää +@msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa + Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu + The Scripts folder cannot be read Scripts-kansiota ei voi lukea @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä @msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin @msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6dd4e37a41..81b54808ed 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4081,6 +4081,9 @@ axis Both Les deux @msg the script is too large to run le script est trop volumineux pour être exécuté @msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script @msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé +@msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts + Some scripts were not listed Certains scripts ne sont pas répertoriés + The Scripts folder cannot be read Impossible de lire le dossier Scripts @msg the script's run is no longer available l’exécution du script n’est plus disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté @msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3397e7f347..6500353205 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6179,6 +6179,9 @@ antiAlias Sharp शार्प @msg the script is too large to run स्क्रिप्ट चलाने के लिए बहुत बड़ी है @msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें @msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता +@msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है + Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं + The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है @msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई @msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4b813215e0..099f38f0e4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4887,6 +4887,9 @@ imageTrace Outline Körvonal @msg the script is too large to run a parancsfájl túl nagy a futtatáshoz @msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt @msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg +@msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában + Some scripts were not listed Néhány szkript nem szerepel a listában + The Scripts folder cannot be read A Scripts mappa nem olvasható @msg the script's run is no longer available a parancsfájl futása már nem érhető el @msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt @msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 33d229c85a..c0438e60c3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -55,6 +55,8 @@ Scripts Skrip Check Script… Periksa skrip… Check Script Periksa skrip + Some scripts were not listed Beberapa skrip tidak dicantumkan + The Scripts folder cannot be read Folder Scripts tidak dapat dibaca Other Script… Skrip lain… Document Setup… Pengaturan dokumen… Switch Units Ganti satuan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b5fd752e9b..b2c2514112 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4134,6 +4134,9 @@ axis Both Entrambi @msg the script is too large to run lo script è troppo grande per essere eseguito @msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script @msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato +@msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts + Some scripts were not listed Alcuni script non sono stati elencati + The Scripts folder cannot be read Impossibile leggere la cartella Scripts @msg the script's run is no longer available l'esecuzione dello script non è più disponibile @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto @msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 56fc8a5907..1de7402676 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4849,6 +4849,9 @@ swatch Bright Violet ビビッドバイオレット @msg the script is too large to run スクリプトが大きすぎて実行できません @msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください @msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました +@msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません + Some scripts were not listed 一部のスクリプトは一覧に表示されていません + The Scripts folder cannot be read Scripts フォルダーを読み込めません @msg the script's run is no longer available スクリプトの実行は利用できなくなりました @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました @msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 388dd4a01e..f533f649f3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5164,6 +5164,9 @@ imageTrace Outline კონტური @msg the script is too large to run სკრიპტი გასაშვებად ძალიან დიდია @msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე @msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია +@msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში + Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი + The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი @msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ შეცვალა გაუქმების ნაბიჯები, რომელთა აღდგენა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 03930932a7..57487bbdec 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4776,6 +4776,9 @@ theme Appearance 외관 @msg the script is too large to run 스크립트가 너무 커서 실행할 수 없습니다 @msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 @msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 +@msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 + Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 + The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 @msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 @msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c5151622d4..7dd845a98f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -55,6 +55,8 @@ Scripts Scripts Check Script… Script controleren… Check Script Script controleren + Some scripts were not listed Sommige scripts zijn niet weergegeven + The Scripts folder cannot be read De map Scripts kan niet worden gelezen Other Script… Ander script… Document Setup… Documentinstellingen… Switch Units Eenheden wisselen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 58016a4bd0..06b5409778 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4225,6 +4225,9 @@ imageTrace Outline Kontur @msg the script is too large to run skrypt jest zbyt duży, aby go uruchomić @msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu @msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować +@msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts + Some scripts were not listed Niektóre skrypty nie zostały wyświetlone + The Scripts folder cannot be read Nie można odczytać folderu Scripts @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne @msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany @msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b0d940693f..cbd855bda7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5054,6 +5054,9 @@ axis Both Ambos @msg the script is too large to run o script é grande demais para ser executado @msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script @msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido +@msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts + Some scripts were not listed Alguns scripts não foram listados + The Scripts folder cannot be read Não é possível ler a pasta Scripts @msg the script's run is no longer available a execução do script não está mais disponível @msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido @msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a00325e8b8..b65db8778d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4128,6 +4128,9 @@ axis Both Оба @msg the script is too large to run скрипт слишком велик для выполнения @msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта @msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить +@msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts + Some scripts were not listed Некоторые сценарии не показаны + The Scripts folder cannot be read Не удалось прочитать папку Scripts @msg the script's run is no longer available выполнение скрипта больше недоступно @msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен @msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f2b24e7d08..40ccd57762 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4002,6 +4002,9 @@ axis Both Båda @msg the script is too large to run skriptet är för stort för att köras @msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript @msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas +@msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts + Some scripts were not listed Vissa skript visas inte i listan + The Scripts folder cannot be read Mappen Scripts kan inte läsas @msg the script's run is no longer available skriptets körning är inte längre tillgänglig @msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades @msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 76d73994b5..a16ff1fa9f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3884,6 +3884,9 @@ axis Both Her İkisi @msg the script is too large to run betik çalıştırılamayacak kadar büyük @msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın @msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı +@msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil + Some scripts were not listed Bazı komut dosyaları listelenmedi + The Scripts folder cannot be read Scripts klasörü okunamıyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor @msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu @msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4652ce4ca8..7ea8dc620c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4118,6 +4118,9 @@ axis Both Обидві @msg the script is too large to run скрипт завеликий для виконання @msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта @msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти +@msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts + Some scripts were not listed Деякі сценарії не показано + The Scripts folder cannot be read Не вдалося прочитати папку Scripts @msg the script's run is no longer available виконання скрипта більше не доступне @msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено @msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4c9dac833c..47462bf63a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4536,6 +4536,9 @@ theme Appearance Giao diện @msg the script is too large to run tập lệnh quá lớn để chạy @msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh @msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ +@msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts + Some scripts were not listed Một số tập lệnh không được liệt kê + The Scripts folder cannot be read Không thể đọc thư mục Scripts @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng @msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng @msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c62b176687..438a52bc83 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4556,6 +4556,9 @@ imageTrace Outline 轮廓 @msg the script is too large to run 脚本过大,无法运行 @msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 @msg the script left a document that cannot be kept 脚本留下了无法保留的文档 +@msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 + Some scripts were not listed 部分脚本未列出 + The Scripts folder cannot be read 无法读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 @msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0b3a21250c..37027bd8cf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2393,6 +2393,9 @@ file-filter Templates 範本 @msg the script is too large to run 指令碼過大,無法執行 @msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 @msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 +@msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 + Some scripts were not listed 部分指令碼未列出 + The Scripts folder cannot be read 無法讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 @msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 932520b184..644125b545 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -66,6 +66,7 @@ pub mod recovery; pub mod render_worker; pub mod screen_color; pub mod script_runs; +pub mod scripts_menu; mod scrub; pub mod shortcut_editor; pub mod shortcuts; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index cbc1536fc3..3f34af13a3 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -23,6 +23,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { ctx.data_mut(|d| d.insert_temp::(field_key, field)); } let mut clicked: Option<(String, Value)> = None; + let mut file_open = false; let tree = menu_tree_named(app.session.prefs.font_names_in_english); // No application menu in the window (as in Illustrator): the bar starts at File on every // platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there. @@ -37,11 +38,21 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let text = egui::RichText::new(tl!(title)).size(13.0).color(t.text); let resp = ui.add(egui::Button::new(text)); egui::Popup::menu(&resp).show(|ui| menu_body(app, ui, items, &mut clicked)); + if *title == "File" { + file_open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp)); + } titles.push(resp); } (ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles)) }) .inner; + // The File menu opening reads the Scripts folder again, for File › Scripts. + let file_key = egui::Id::unique("menu-bar-file-open"); + let file_was_open = ctx.data(|d| d.get_temp::(file_key)).unwrap_or(false); + ctx.data_mut(|d| d.insert_temp(file_key, file_open)); + if file_open && !file_was_open { + crate::scripts_menu::refresh(app, Some(&ctx)); + } // Whether a top-level menu is open: the docking renderer lowers the floating panels' OS windows // while one is, or the menu would open under them. ctx.data_mut(|d| d.insert_temp(menu_open_id(), open)); diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 5d203fe875..3c308970d6 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -33,8 +33,11 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { Some(match it { Item::Sep => Entry::Sep, Item::Header(h) => Entry::Header(t(h)), - // A plug-in's submenu shows its name as it is, as its items do. - Item::Sub(label, children) if super::labels::holds_plugin_commands(children) => Entry::Sub(label, children), + // A plug-in's submenu shows its name as it is, as its items do, and so does a subfolder of + // the Scripts folder. + Item::Sub(label, children) if super::labels::holds_plugin_commands(children) || crate::scripts_menu::is_folder(children) => { + Entry::Sub(label, children) + } Item::Sub(label, children) => Entry::Sub(t(label), children), Item::Todo(label, sc) => Entry::Item(Row { command: None, @@ -127,6 +130,9 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve for it in items { match it { Item::Cmd(l, id, p) => { + if *id == crate::scripts_menu::COMMAND && !crate::scripts_menu::readable(p) { + continue; + } let Some((enabled, _)) = shown_state(app, id, p) else { continue }; out.push(MenuEntry { path: path.clone(), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index c37a8268c2..ab530b803c 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -2,11 +2,12 @@ use super::state::{SUBJECT_COMMANDS, enabled, has_subject, waits_for_ime}; use super::{Value, VectorcraftApp, json}; /// What a menu click runs: items whose label ends with "…" and that carry default params open a -/// generic parameter dialog (fields = the defaults) instead of running immediately. +/// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the +/// Scripts folder runs, whatever its name ends with. pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { let dialog = label.ends_with('…') && p.as_object().is_some_and(|o| !o.is_empty()) - && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog"); + && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog" | crate::scripts_menu::COMMAND); if dialog { return ("ui.paramDialog".into(), json!({"command": id, "label": label.trim_end_matches('…'), "params": p})); } diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 148368a279..408e5f077a 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -123,8 +123,8 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a -/// plug-in, an SVG filter? Such names are shown as they are, never translated (a workspace the user calls -/// "Layers" stays "Layers"). +/// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never +/// translated (a workspace the user calls "Layers" stays "Layers"). pub(super) fn shows_a_name(id: &str, label: &str) -> bool { const SLOTS: [&str; 8] = [ "file.openRecent", @@ -138,7 +138,10 @@ pub(super) fn shows_a_name(id: &str, label: &str) -> bool { ]; SLOTS.iter().any(|s| id.starts_with(s)) || saved_selection_slot(id).is_some() - || matches!(id, "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply") + || matches!( + id, + "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply" | crate::scripts_menu::COMMAND + ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) || (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label)) @@ -328,12 +331,12 @@ pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { /// Every English string the menus, the command palette, the panel registry, the toolbar and the /// Preferences dialog can show: what a complete language catalog has to cover. Names that are user -/// data (fonts, recent files, saved views, libraries, installed plug-ins), the point sizes and the -/// view angles are left out. +/// data (fonts, recent files, saved views, libraries, installed plug-ins, the scripts and subfolders +/// of the Scripts folder), the point sizes and the view angles are left out. pub fn menu_strings() -> std::collections::BTreeSet { use std::collections::BTreeSet; fn user_data(id: &str, params: &Value) -> bool { - hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) + hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) || id == crate::scripts_menu::COMMAND } fn walk(items: &[Item], under: &str, out: &mut BTreeSet) { for it in items { @@ -354,8 +357,8 @@ pub fn menu_strings() -> std::collections::BTreeSet { Item::Todo(l, _) | Item::Header(l) => { out.insert(l.to_string()); } - // A plug-in's submenu is named after the plug-in. - Item::Sub(_, children) if holds_plugin_commands(children) => walk(children, under, out), + // A plug-in's submenu is named after the plug-in, and a subfolder's after the folder. + Item::Sub(_, children) if holds_plugin_commands(children) || crate::scripts_menu::is_folder(children) => walk(children, under, out), Item::Sub(l, children) => { out.insert(l.to_string()); // Type › Font lists the installed families: names, not UI text. @@ -375,6 +378,7 @@ pub fn menu_strings() -> std::collections::BTreeSet { out.extend(crate::native_menu::MAC_LABELS.iter().map(|s| s.to_string())); out.extend(DYNAMIC_LABELS.iter().map(|s| s.to_string())); out.extend(CONTEXT_LABELS.iter().map(|s| s.to_string())); + out.extend(crate::scripts_menu::LABELS.iter().map(|s| s.to_string())); out.extend(UI_COMMANDS.iter().map(|c| c.1.to_string())); for c in vectorcraft_engine::cmd::command_specs() { out.insert(c.label.to_string()); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 98d4da9895..6f06beef00 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -974,6 +974,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::trace_runs::hide_all(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), "ui.runScript" => crate::dialogs::script_run::command(app, p), + crate::scripts_menu::COMMAND => crate::scripts_menu::run(app, p), "ui.perspectiveGridDialog" => crate::dialogs::perspective_grid::open(app), "ui.perspectivePresetsDialog" => { crate::dialogs::perspective_presets::open(app, s("selected").as_deref()); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index a0e4935610..bcb51b133a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -130,6 +130,57 @@ fn hovering_another_title_switches_the_open_menu() { assert_eq!(open_titles(&ctx, &t), vec![0], "a still pointer leaves the open menu alone"); } +#[test] +fn opening_the_file_menu_reads_the_scripts_folder_again() { + let dir = std::env::temp_dir().join(format!("vc-menu-bar-scripts-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = vectorcraft_engine::Session::new(); + session.attach_scripts_dir(dir.clone()); + let mut app = VectorcraftApp::new(session, crate::Services::default()); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + // The scripts File › Scripts lists. + let listed = || { + let (_, file) = menu_tree().into_iter().find(|(title, _)| *title == "File").unwrap(); + let scripts = file.iter().find_map(|item| match item { + Item::Sub("Scripts", items) => Some(items.clone()), + _ => None, + }); + scripts + .unwrap() + .iter() + .filter_map(|item| if let Item::Cmd(label, crate::scripts_menu::COMMAND, _) = item { Some(*label) } else { None }) + .collect::>() + }; + // One frame of the bar, then the listing a read it started gave. + let frame = |app: &mut VectorcraftApp| { + let titles = bar_frame(app, &ctx, vec![]); + crate::scripts_menu::wait(); + titles + }; + std::fs::write(dir.join("a.js"), "").unwrap(); + frame(&mut app); + let titles = frame(&mut app); + assert!(listed().is_empty(), "the bar reads nothing while its menus are closed"); + egui::Popup::open_id(&ctx, titles[0].1); + frame(&mut app); + assert_eq!(listed(), ["a"]); + // While File stays open the folder is not read again. + std::fs::write(dir.join("b.js"), "").unwrap(); + frame(&mut app); + assert_eq!(listed(), ["a"]); + // Nor when another menu opens; the next time File opens it is. + egui::Popup::open_id(&ctx, titles[1].1); + let t = frame(&mut app); + assert_eq!((open_titles(&ctx, &t), listed()), (vec![1], vec!["a"])); + egui::Popup::open_id(&ctx, titles[0].1); + frame(&mut app); + assert_eq!(listed(), ["a", "b"]); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_popup_covering_a_title_does_not_switch_menus() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 97651d0740..0624623072 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -62,7 +62,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Export Selection…", "file.exportSelection"), Sep, c("Package…", "ui.packageDialog"), - sub("Scripts", vec![c("Check Script…", "ui.checkScript"), c("Other Script…", "ui.runScript")]), + sub("Scripts", crate::scripts_menu::items()), Sep, c("Document Setup…", "file.documentSetup"), sub( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fb78fc2075..9ba2fa2dcb 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1526,6 +1526,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+F12", "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), + ( + crate::scripts_menu::COMMAND, + "Run Script", + "", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with the file's text, under the file's name), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or one of its listed subfolders, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + ), ( "ui.checkScript", "Check Script…", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 8d1b7ee083..56baee51aa 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -590,7 +590,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, /// its revision (edits, selection and view changes), history and clipboard, the language, -/// shortcuts, plug-ins, an open file dialog and the fonts (Type › Font lists the loaded fonts +/// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts /// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or /// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's @@ -608,7 +608,7 @@ fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); app.file_dialog_open().hash(&mut h); - (crate::i18n::current().code(), menus::plugin_revision()).hash(&mut h); + (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision()).hash(&mut h); crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed).hash(&mut h); let fonts = vectorcraft_text::FontDb::global(); (fonts.generation(), fonts.installed_fonts_ready()).hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index e895bef6c6..d5bf7b6098 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -17,8 +17,9 @@ pub fn items() -> Vec<(String, String, String)> { let label = if path.is_empty() { c.label.to_string() } else { format!("{path} › {}", c.label) }; items.push((label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("").to_string())); } - // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. - for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog") { + // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of + // the Scripts folder runs from File › Scripts, by its path. + for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND) { items.push((c.1.to_string(), c.0.to_string(), menus::shortcut_of(c.0).unwrap_or("").to_string())); } for tool in vectorcraft_tools::catalog::all_tools() { diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs new file mode 100644 index 0000000000..bac2d11211 --- /dev/null +++ b/crates/ui-egui/src/scripts_menu.rs @@ -0,0 +1,225 @@ +//! File › Scripts: the scripts of the Scripts folder next to the settings +//! ([`vectorcraft_engine::Session::attach_scripts_dir`]), each `.js` or `.jsx` file by its name +//! without the extension and each subfolder as a submenu, above Check Script… and Other Script…. +//! +//! The folder is read on another thread ([`vectorcraft_engine::script::folder::list`]: names only, +//! within its limits), one read at a time: when the app starts, each time its window becomes the +//! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished +//! listing ([`items`]), so a script added to the folder is listed without a restart. +//! +//! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other +//! Script… shows: the file was put in the folder to be run from the menu. The path is one a +//! listing gave; a file that is no longer a plain script under the folder is not run. + +use std::path::Path; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use serde_json::{Value, json}; +use vectorcraft_engine::script::folder::{Entry, Listing}; + +use crate::VectorcraftApp; +use crate::menus::Item; + +/// The command a listed script's menu item runs. +pub const COMMAND: &str = "ui.runInstalledScript"; +/// The menu's note under a listing that may lack scripts. +pub const TRUNCATED: &str = "Some scripts were not listed"; +/// The menu's note when the folder is there and cannot be read. +pub const UNREADABLE: &str = "The Scripts folder cannot be read"; +/// The notes, for the catalogs ([`crate::menus::menu_strings`]). +pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE]; + +#[derive(Default)] +struct State { + /// The last finished listing. + listing: Arc, + /// How many finished listings differed from the one before. + revision: u64, + /// The listing being read on another thread. + reading: Option>, + /// A first read was asked for. + started: bool, + /// The window was the active one at the last [`poll`]. + focused: bool, +} + +/// The listing the menus show. One per process in the app; one per thread in unit tests, which run +/// in parallel threads, each with its own folder. +fn state() -> MutexGuard<'static, State> { + #[cfg(not(test))] + let state: &'static Mutex = { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) + }; + #[cfg(test)] + let state: &'static Mutex = { + thread_local!(static S: &'static Mutex = Box::leak(Box::default())); + S.with(|s| *s) + }; + state.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The most different names the menu shows in one session. Each is kept for the rest of the +/// session (menu items hold `&'static str` labels), at most 128 characters each. +pub const MAX_NAMES: usize = 16_384; + +/// Leak-once interning of the names the menu shows; `None` for a new name once [`MAX_NAMES`] are +/// kept, so renaming scripts over and over keeps the memory bounded. +pub(crate) fn intern(s: &str) -> Option<&'static str> { + #[cfg(not(test))] + let set: &'static Mutex> = { + static SET: std::sync::OnceLock>> = std::sync::OnceLock::new(); + SET.get_or_init(Default::default) + }; + #[cfg(test)] + let set: &'static Mutex> = { + thread_local!(static SET: &'static Mutex> = Box::leak(Box::default())); + SET.with(|s| *s) + }; + let mut set = set.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(v) = set.get(s) { + return Some(v); + } + if set.len() >= MAX_NAMES { + return None; + } + let v: &'static str = Box::leak(s.to_string().into_boxed_str()); + set.insert(v); + Some(v) +} + +/// Changes whenever the menus' listing changes (the macOS menu bar follows it). +pub fn revision() -> u64 { + state().revision +} + +/// Read the Scripts folder again on another thread, unless a read is under way or the session has +/// no folder (the web, and a run without preferences). `ctx` is asked to draw when the read ends. +pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { + let Some(root) = app.session.scripts_dir().map(Path::to_path_buf) else { return }; + let mut state = state(); + if state.reading.is_some() { + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.cloned(); + let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { + // The app's own folder, read for the person at the keyboard. + let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); + if tx.send(listing).is_ok() + && let Some(ctx) = ctx + { + ctx.request_repaint(); + } + }); + if spawned.is_ok() { + state.reading = Some(rx); + } +} + +/// Once per iteration: start a read on the first one and when the window becomes the active one, +/// and take in a read that ended. +pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { + let focused = ctx.input(|i| i.focused); + let start = { + let mut state = state(); + let start = !state.started || (focused && !state.focused); + (state.started, state.focused) = (true, focused); + start + }; + if start { + refresh(app, Some(ctx)); + } + take(false); +} + +/// Take in the read under way: when it has ended, or with `wait` once it ends. +fn take(wait: bool) { + let mut state = state(); + let Some(reading) = &state.reading else { return }; + let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; + match listing { + Ok(listing) => { + if *state.listing != listing { + state.listing = Arc::new(listing); + state.revision += 1; + } + state.reading = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => state.reading = None, + } +} + +/// Wait for the read under way and take it in. +#[cfg(test)] +pub(crate) fn wait() { + take(true); +} + +/// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or +/// the folder cannot be read, then Check Script… and Other Script…. +pub fn items() -> Vec { + // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). + fn level(entries: &[Entry], dropped: &mut bool) -> Vec { + let mut items = Vec::with_capacity(entries.len()); + for e in entries { + let item = match e { + Entry::Script { label, path } => intern(label).map(|l| Item::Cmd(l, COMMAND, json!({ "path": path.to_string_lossy() }))), + Entry::Folder { label, entries } => { + let inner = level(entries, dropped); + intern(label).filter(|_| !inner.is_empty()).map(|l| Item::Sub(l, inner)) + } + }; + match item { + Some(item) => items.push(item), + None => *dropped = true, + } + } + items + } + let listing = state().listing.clone(); + let mut dropped = false; + let mut items = level(&listing.entries, &mut dropped); + if listing.truncated || dropped { + items.push(Item::Header(TRUNCATED)); + } + if listing.unreadable { + items.push(Item::Header(UNREADABLE)); + } + if !items.is_empty() { + items.push(Item::Sep); + } + items.extend([Item::Cmd("Check Script…", "ui.checkScript", Value::Null), Item::Cmd("Other Script…", "ui.runScript", Value::Null)]); + items +} + +/// Is `children` a subfolder's submenu, named after the folder? Its first item is a listed script +/// or another subfolder, and it has no Other Script…, which only File › Scripts itself has. +pub fn is_folder(children: &[Item]) -> bool { + let listed = match children.first() { + Some(Item::Cmd(_, id, _)) => *id == COMMAND, + Some(Item::Sub(_, inner)) => is_folder(inner), + _ => false, + }; + listed && !children.iter().any(|c| matches!(c, Item::Cmd(_, "ui.runScript", _))) +} + +/// May the request being served read the listed script `p` names? Under an automation read root +/// (a control client's request), a script outside the root is left out of `ui.menu.list`, as +/// `script.listInstalled` refuses to list the folder there. +pub fn readable(p: &Value) -> bool { + p.get("path").and_then(Value::as_str).is_some_and(|path| vectorcraft_engine::file_access::check_read(path).is_ok()) +} + +/// `ui.runInstalledScript {path}`: run the listed script at `path`. A script that is no longer in +/// the folder is not run, and the folder is read again. +pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; + let source = app.session.installed_script(path).map_err(|e| { + refresh(app, None); + e.to_string() + })?; + app.run("script.run", json!({"source": source, "name": vectorcraft_engine::cmd::fileio::file_name(path)})) +} diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 261a250542..c8e60c14f3 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod screenmode; mod screenshots; mod script_check; mod script_run; +mod scripts_menu; mod scrub; mod selectall; mod selectescape; diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs new file mode 100644 index 0000000000..1cfb462871 --- /dev/null +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -0,0 +1,329 @@ +//! File › Scripts lists the Scripts folder: its scripts and subfolders above Check Script… and +//! Other Script…, names shown as they are, a listed script run without the warning, a script that +//! is gone, the notes, the macOS menu bar and the reads of the folder. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::menus::{self, Entry, Item}; +use crate::native_menu::{self, Node}; +use crate::{VectorcraftApp, script_runs, scripts_menu}; + +/// A fresh folder for test `name`, holding an empty `Scripts` folder. +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-scripts-menu-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Scripts")).unwrap(); + dir +} + +/// An app with a document whose Scripts folder is `dir`'s. +fn app(dir: &std::path::Path) -> VectorcraftApp { + let mut session = Session::new(); + session.attach_scripts_dir(dir.join("Scripts")); + let mut app = VectorcraftApp::new(session, crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +/// Reads the folder again and waits for the listing. +fn read(app: &VectorcraftApp) { + scripts_menu::refresh(app, None); + scripts_menu::wait(); +} + +/// Writes the script `name` (`/` between its folders) in `dir`'s Scripts folder; returns its path +/// as a listing gives it. +fn write(dir: &std::path::Path, name: &str, text: &str) -> String { + let path = name.split('/').fold(dir.join("Scripts"), |path, part| path.join(part)); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path.to_string_lossy().into_owned() +} + +/// File › Scripts' items. +fn scripts() -> Vec { + let (_, file) = menus::menu_tree().into_iter().find(|(title, _)| *title == "File").unwrap(); + file.into_iter() + .find_map(|item| match item { + Item::Sub("Scripts", items) => Some(items), + _ => None, + }) + .unwrap() +} + +/// Menu items as text: a command's label, `label/[…]` for a submenu, `(text)` for a note and `-` +/// for a separator. +fn shape(items: &[Item]) -> String { + let one = |item: &Item| match item { + Item::Cmd(label, ..) | Item::Todo(label, _) => label.to_string(), + Item::Sub(label, items) => format!("{label}/[{}]", shape(items)), + Item::Header(text) => format!("({text})"), + Item::Sep => "-".to_string(), + }; + items.iter().map(one).collect::>().join(", ") +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn finish(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; + +#[test] +fn the_folders_scripts_are_listed_above_check_script_and_other_script() { + let dir = folder("listed"); + let app = app(&dir); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "before the first listing"); + read(&app); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "an empty folder"); + let draw = write(&dir, "Draw Two.jsx", DRAW); + write(&dir, "Export/All Artboards.js", ""); + write(&dir, "notes.txt", ""); + read(&app); + let items = scripts(); + assert_eq!(shape(&items), "Draw Two, Export/[All Artboards], -, Check Script…, Other Script…"); + assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); + // A script added to the folder is listed by the next read, with no restart. + write(&dir, "Added.js", ""); + assert!(shape(&scripts()).starts_with("Draw Two"), "the menus keep the last listing"); + read(&app); + assert!(shape(&scripts()).starts_with("Added, Draw Two")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_listed_script_runs_without_the_warning_as_one_undo_step() { + let dir = folder("run"); + let mut app = app(&dir); + write(&dir, "Dessin (été) #1.JSX", DRAW); + read(&app); + let items = scripts(); + let Item::Cmd(label, id, p) = &items[0] else { panic!("{:?}", items[0]) }; + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(app.session.prefs.show_external_script_warning); + let (id, p) = menus::click_target(label, id, p); + menus::invoke(&mut app, &id, p); + assert!(app.ui.dialog.is_none(), "no warning for a script of the folder"); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 2); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(app.ui.status, "Ran Dessin (été) #1.JSX"); + assert!(app.session.prefs.show_external_script_warning, "Other Script… still warns"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_runs_its_own_file_whatever_its_name_ends_with() { + let dir = folder("names"); + let mut app = app(&dir); + // A label that ends like a menu item that asks for its parameters first. + let dots = write(&dir, "Draw….js", DRAW); + write(&dir, "Draw.js", "vc.run('shape.rectangle', {x:0,y:0,width:1,height:1});"); + read(&app); + let items = scripts(); + assert_eq!(shape(&items[..2]), "Draw, Draw…"); + let Item::Cmd(label, id, p) = &items[1] else { panic!("{:?}", items[1]) }; + assert_eq!(menus::click_target(label, id, p), (scripts_menu::COMMAND.to_string(), json!({ "path": dots }))); + menus::run_ui_command(&mut app, id, p).unwrap().unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 2, "the file the item names ran, not its neighbor"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn script_and_folder_names_are_shown_as_they_are_in_every_language() { + let dir = folder("language"); + let app = app(&dir); + write(&dir, "Layers.js", ""); + write(&dir, "Export/Layers.jsx", ""); + read(&app); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert!(crate::i18n::tr(de, "Layers") != "Layers" && crate::i18n::tr(de, "Export") != "Export", "German translates both words"); + crate::i18n::set_current(de); + let items = scripts(); + let labels: Vec = items + .iter() + .filter_map(|item| match menus::entry(&app, item)? { + Entry::Sub(label, _) => Some(label.to_string()), + Entry::Item(row) => Some(row.label.to_string()), + _ => None, + }) + .collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(labels[..2], ["Export", "Layers"]); + assert_ne!(labels[2], "Check Script…", "the fixed items are translated"); + // The catalogs hold the notes, and no file or folder name. + let strings = menus::menu_strings(); + assert!(scripts_menu::LABELS.iter().all(|note| strings.contains(*note))); + assert!(strings.contains("Layers") && !strings.contains("All Artboards")); + write(&dir, "Zed/All Artboards.js", ""); + read(&app); + assert!(!menus::menu_strings().contains("All Artboards") && !menus::menu_strings().contains("Zed")); + assert!(!crate::palette::items().iter().any(|(_, id, _)| id == scripts_menu::COMMAND), "a script runs from its menu item"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { + let dir = folder("gone"); + let mut app = app(&dir); + let gone = write(&dir, "gone.js", DRAW); + write(&dir, "kept.js", ""); + read(&app); + std::fs::remove_file(&gone).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(!app.session.script_running()); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), "kept, -, Check Script…, Other Script…"); + // A file outside the folder is not one of its scripts, and a call needs a path. + let outside = dir.join("outside.js"); + std::fs::write(&outside, DRAW).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": outside.to_string_lossy() })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({})).unwrap().is_err()); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": 3 })).unwrap().is_err()); + finish(&mut app); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { + let dir = folder("notes"); + let app = app(&dir); + for n in 0..vectorcraft_engine::script::folder::MAX_SCRIPTS + 1 { + write(&dir, &format!("s{n:04}.js"), ""); + } + read(&app); + let items = scripts(); + assert_eq!(items.len(), vectorcraft_engine::script::folder::MAX_SCRIPTS + 4); + assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + // A file where the folder should be. + std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); + std::fs::write(dir.join("Scripts"), "").unwrap(); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, Check Script…, Other Script…", scripts_menu::UNREADABLE)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + let dir = folder("read-root"); + let app = app(&dir); + let path = write(&dir, "Export/All Artboards.js", ""); + read(&app); + let scripts = || menus::menu_entries(&app).into_iter().filter(|e| e.command.as_deref() == Some(scripts_menu::COMMAND)).collect::>(); + let listed = scripts(); + assert_eq!(listed.len(), 1); + assert_eq!( + (&listed[0].path, &listed[0].label, &listed[0].params), + (&vec!["File".to_string(), "Scripts".into(), "Export".into()], &"All Artboards".to_string(), &json!({ "path": path })) + ); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + let outside = AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); + assert!(confine(Some(&outside), scripts).is_empty()); + let inside = AutomationRoots::new(&[&dir], &[]).unwrap().unwrap(); + assert_eq!(confine(Some(&inside), scripts).len(), 1); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn names_past_the_session_limit_are_left_out_with_the_note() { + let dir = folder("names-limit"); + let app = app(&dir); + write(&dir, "Kept.js", ""); + read(&app); + assert_eq!(shape(&scripts()), "Kept, -, Check Script…, Other Script…"); + // Names other listings showed fill what one session keeps. + for n in 0..scripts_menu::MAX_NAMES { + if scripts_menu::intern(&format!("renamed {n}")).is_none() { + break; + } + } + write(&dir, "New.js", ""); + write(&dir, "Folder/Inside.js", ""); + read(&app); + assert_eq!(shape(&scripts()), format!("Kept, ({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { + let dir = folder("native"); + let app = app(&dir); + let path = write(&dir, "Export/All Artboards.js", ""); + let before = scripts_menu::revision(); + read(&app); + assert_eq!(scripts_menu::revision(), before + 1); + let bar = native_menu::from_tree(&app, &menus::menu_tree()); + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children), + _ => None, + }); + let Some([Node::Submenu { label, children }, Node::Separator, Node::Item(check), Node::Item(other)]) = scripts.map(Vec::as_slice) else { + panic!("{scripts:?}") + }; + assert_eq!((label.as_str(), check.command, other.command), ("Export", Some("ui.checkScript"), Some("ui.runScript"))); + let [Node::Item(script)] = children.as_slice() else { panic!("{children:?}") }; + assert_eq!((script.label.as_str(), script.command, &script.params), ("All Artboards", Some(scripts_menu::COMMAND), &json!({ "path": path }))); + assert!(script.enabled && script.shortcut.is_none()); + // A read that finds the same scripts changes nothing the menu bar would rebuild for. + read(&app); + assert_eq!(scripts_menu::revision(), before + 1); + write(&dir, "More.jsx", ""); + read(&app); + assert_eq!(scripts_menu::revision(), before + 2); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_folder_is_read_at_the_first_frame_and_when_the_window_becomes_active() { + let dir = folder("focus"); + let app = app(&dir); + write(&dir, "first.js", ""); + let ctx = egui::Context::default(); + let frame = |focused: bool| { + let mut out = ctx.run_ui(egui::RawInput { focused, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); + out.textures_delta.clear(); + scripts_menu::wait(); + }; + let listed = || shape(&scripts()); + frame(true); + assert!(listed().starts_with("first, -"), "{}", listed()); + // While the window stays active, or stays in the background, the folder is left alone. + write(&dir, "second.js", ""); + frame(true); + frame(false); + frame(false); + assert!(listed().starts_with("first, -"), "{}", listed()); + frame(true); + assert!(listed().starts_with("first, second, -"), "{}", listed()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + read(&app); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…"); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": "draw.js" })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert_eq!(menus::UI_COMMANDS.iter().filter(|c| c.0 == scripts_menu::COMMAND).count(), 1); + let _: Value = app.run("script.listInstalled", json!({})).unwrap(); +} diff --git a/docs/gaps.md b/docs/gaps.md index ddc02a2d00..decd352595 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -689,9 +689,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts, a script console, the Scripts folder and script - directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the - command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and +- **Missing:** the document object model for scripts, a script console and script directives (#1183 is + open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, and + File › Scripts lists the scripts of the Scripts folder. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index 23d12e76b1..d32f3d524d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1604,6 +1604,54 @@ In the app the reply is `{running: true, name}`, and the report appears later as vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' ``` +File › Scripts lists the scripts of the `Scripts` folder next to the preferences: `~/Library/Application +Support/VectorCraft/Scripts` on macOS, `%APPDATA%\VectorCraft\Scripts` on Windows, and +`$XDG_CONFIG_HOME/vectorcraft/Scripts` or `~/.config/vectorcraft/Scripts` on Linux and BSD. VectorCraft does not make +the folder: create it, and put `.js` or `.jsx` files in it. Each file is a menu item named after the file without its +extension, and each subfolder is a submenu that holds the scripts in it. The help page +https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html and +the page https://ai-scripting.docsforadobe.dev/introduction/executingScripts/ describe a Scripts folder listed this +way. The listed scripts come first in the menu, above Check Script… and Other Script…. Choosing one runs the file as +`script.run` runs a file, without the warning that Other Script… shows. + +The rest of this section is VectorCraft's own rules: + +- The folder is read when the app starts, each time its window becomes the active one, and, where the menus are in + the window (Windows and Linux), each time the File menu opens. A script added while VectorCraft runs is listed + after the next of these. A read takes names only, never a script's text, and runs off the UI thread, one read at a + time. +- Each level is sorted by label without regard to case, with scripts and subfolders mixed. A script whose label + another row of its folder has (`Tidy.js` beside `Tidy.jsx`, or beside a subfolder `Tidy`) shows its whole file name. +- A symbolic link or a Windows junction is never followed: a linked file or subfolder is left out, and a `Scripts` + folder that is itself a link is not read. Names that start with a dot, files and folders Windows marks hidden or + system, names that are not Unicode, names longer than 255 bytes and subfolders without a script are left out too, + and a listed script that is marked hidden or system, or lies in a folder marked so, by the time it is chosen does + not run. +- One read looks at 2,048 folder entries at most, lists 512 scripts and reads 128 subfolders, 4 levels deep, for at + most 250 ms. A label longer than 128 characters is cut, and control and bidirectional formatting characters in a + name are shown as `\u{…}` escapes. When a read stops at a limit or cannot read a subfolder, the menu keeps what it + found and shows `Some scripts were not listed`. The menu also shows that note, and leaves the rows out, when a + read finds new names after the menus have shown 16,384 different script and folder names since VectorCraft started. + When the folder is there and cannot be read, the menu shows + `The Scripts folder cannot be read`. +- A listed file is checked again when it is chosen. A file that is gone, is no longer a `.js` or `.jsx` file under + the folder, or is or lies behind a link ends with `the script is no longer in the Scripts folder`, and nothing runs. +- The web build has no Scripts folder, and neither has a run with `VECTORCRAFT_NO_PREFS` set. + +`script.listInstalled {}` returns the same listing: `{folder, scripts: [{path, label, folders}], truncated, +unreadable}`, with the scripts in menu order and `folders` the labels of the subfolders a script is in. `folder` is +`null` without a Scripts folder. `ui.runInstalledScript {path}` runs one of them by the `path` the listing gave, as +its menu item does. Under `--automation-read-root`, both read the folder only when it lies inside a read root, and +`ui.menu.list` leaves out the listed scripts outside the read roots. + +```json +{"name":"run_command","arguments":{"command":"script.listInstalled","params":{}}} +``` + +```sh +vectorcraft-cli run --cmd script.listInstalled --params '{}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8d10fc0b8..b92ae00710 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -722,6 +722,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). From f78d715fee81efed7dce26ff6505403744a69a2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 18:23:33 -0800 Subject: [PATCH 07/83] Scripts: a Scripts folder read asked for during another starts when that one ends A File menu opening or a failed ui.runInstalledScript while a read of the Scripts folder was under way was dropped, so a script added after that read passed the folder stayed unlisted until the next window activation or File menu opening. The request is now kept and the next frame starts the read once the running one is taken in. --- crates/ui-egui/src/scripts_menu.rs | 34 +++++++++++++++++++++--- crates/ui-egui/src/tests/scripts_menu.rs | 23 ++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index bac2d11211..58be7b7b89 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -38,6 +38,8 @@ struct State { revision: u64, /// The listing being read on another thread. reading: Option>, + /// Another read was asked for while one was under way; [`poll`] starts it when that one ends. + pending: bool, /// A first read was asked for. started: bool, /// The window was the active one at the last [`poll`]. @@ -94,12 +96,14 @@ pub fn revision() -> u64 { state().revision } -/// Read the Scripts folder again on another thread, unless a read is under way or the session has -/// no folder (the web, and a run without preferences). `ctx` is asked to draw when the read ends. +/// Read the Scripts folder again on another thread, unless the session has no folder (the web, and +/// a run without preferences). While a read is under way, another read starts when it ends +/// ([`poll`]). `ctx` is asked to draw when the read ends. pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { let Some(root) = app.session.scripts_dir().map(Path::to_path_buf) else { return }; let mut state = state(); if state.reading.is_some() { + state.pending = true; return; } let (tx, rx) = std::sync::mpsc::channel(); @@ -119,7 +123,7 @@ pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { } /// Once per iteration: start a read on the first one and when the window becomes the active one, -/// and take in a read that ended. +/// take in a read that ended, and then start a read asked for while it was under way. pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { let focused = ctx.input(|i| i.focused); let start = { @@ -132,6 +136,17 @@ pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { refresh(app, Some(ctx)); } take(false); + let again = { + let mut state = state(); + let again = state.pending && state.reading.is_none(); + if again { + state.pending = false; + } + again + }; + if again { + refresh(app, Some(ctx)); + } } /// Take in the read under way: when it has ended, or with `wait` once it ends. @@ -158,6 +173,19 @@ pub(crate) fn wait() { take(true); } +/// Wait for the read under way to end and leave its listing to be taken in, so the read is under +/// way until the next [`poll`]. +#[cfg(test)] +pub(crate) fn end_untaken() { + let mut state = state(); + let Some(reading) = &state.reading else { return }; + let (tx, rx) = std::sync::mpsc::channel(); + if let Ok(listing) = reading.recv() { + let _ = tx.send(listing); + } + state.reading = Some(rx); +} + /// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or /// the folder cannot be read, then Check Script… and Other Script…. pub fn items() -> Vec { diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 1cfb462871..f18b60f633 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -317,6 +317,29 @@ fn the_folder_is_read_at_the_first_frame_and_when_the_window_becomes_active() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_read_asked_for_during_another_runs_when_that_one_ends() { + let dir = folder("pending"); + let app = app(&dir); + write(&dir, "first.js", ""); + let ctx = egui::Context::default(); + let frame = || { + let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); + out.textures_delta.clear(); + }; + frame(); + scripts_menu::wait(); + // A read that has passed the folder when a script is added, and the File menu opening then. + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + write(&dir, "added.js", ""); + scripts_menu::refresh(&app, None); + frame(); + scripts_menu::wait(); + assert!(shape(&scripts()).starts_with("added, first, -"), "{}", shape(&scripts())); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); From a06ab459110d78d72e09c01625d236c5176c17db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 18:48:59 -0800 Subject: [PATCH 08/83] Scripts: every script label in a Scripts folder level stays distinct A script renamed to its whole file name could take the label another script kept, as with tidy.js, tidy.jsx and tidy.js.js in one folder. The rename now repeats until no label is shared. A folder entry whose type cannot be read now marks the listing as incomplete. --- crates/engine/src/script/folder.rs | 37 +++++++++++++++++------- crates/engine/src/tests/script_folder.rs | 5 ++-- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index 4453953d80..d071195df6 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -10,8 +10,8 @@ //! //! The values here are VectorCraft's own limits: [`MAX_ENTRIES`], [`MAX_SCRIPTS`], [`MAX_FOLDERS`], //! [`MAX_DEPTH`], [`MAX_NAME_BYTES`], [`MAX_LABEL_CHARS`] and [`MAX_SCAN`]. A listing that reaches -//! one of them, or that cannot read a subfolder, keeps what it found and says so -//! ([`Listing::truncated`]). +//! one of them, or that cannot read a subfolder or an entry of a folder, keeps what it found and +//! says so ([`Listing::truncated`]). use std::io::Read; use std::path::{Component, Path, PathBuf}; @@ -157,7 +157,10 @@ impl Scan<'_> { continue; }; let Ok(name) = entry.file_name().into_string() else { continue }; - let Ok(kind) = entry.file_type() else { continue }; + let Ok(kind) = entry.file_type() else { + self.truncated = true; + continue; + }; if name.len() > MAX_NAME_BYTES || name.starts_with('.') || kind.is_symlink() || hidden(&entry) { continue; } @@ -173,14 +176,26 @@ impl Scan<'_> { found.push(Found { label: shown(stem), name, folder: false }); } } - // A script whose label another row of this folder has shows its whole file name. - let mut count = std::collections::HashMap::::new(); - for f in &found { - *count.entry(f.label.clone()).or_default() += 1; - } - for f in found.iter_mut().filter(|f| !f.folder) { - if count.get(&f.label).is_some_and(|n| *n > 1) { - f.label = shown(&f.name); + // A script whose label another row of this folder has shows its whole file name, until no + // label is shared. Each pass gives at least one more script its whole file name, and names + // are unique within a folder, so this ends within `found.len()` passes. + loop { + let mut count = std::collections::HashMap::::new(); + for f in &found { + *count.entry(f.label.clone()).or_default() += 1; + } + let mut renamed = false; + for f in found.iter_mut().filter(|f| !f.folder) { + if count.get(&f.label).is_some_and(|n| *n > 1) { + let whole = shown(&f.name); + if f.label != whole { + f.label = whole; + renamed = true; + } + } + } + if !renamed { + break; } } found.sort_by(|a, b| (a.label.to_lowercase(), &a.label, &a.name).cmp(&(b.label.to_lowercase(), &b.label, &b.name))); diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 24ef85ddfd..b176b4f143 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -77,10 +77,11 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { let dir = folder("same"); let root = dir.join("Scripts"); - for name in ["tidy.js", "tidy.jsx", "tidy/x.js", "alone.jsx"] { + for name in ["tidy.js", "tidy.jsx", "tidy.js.js", "tidy/x.js", "alone.jsx"] { touch(&root, name); } - assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.jsx"); + // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. + assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); let _ = std::fs::remove_dir_all(dir); } From 37f140925e408ada8eb7f39bf0034fb3ff8ac091 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 18:58:54 -0800 Subject: [PATCH 09/83] Scripts: Run Script's params text names the four-level limit on subfolders ui.runInstalledScript runs a .js or .jsx file in the Scripts folder or in a subfolder at most 4 levels below it, whether or not a capped listing read that subfolder. The params text now says so instead of naming only listed subfolders. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 9ba2fa2dcb..5d132fbde7 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1530,7 +1530,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with the file's text, under the file's name), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or one of its listed subfolders, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with the file's text, under the file's name), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", From d7a89d32433c6f6bb4571975419702aab38e428a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:24:35 -0800 Subject: [PATCH 10/83] Scripts: the read after a script left the folder asks for a frame when it ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When File › Scripts runs a listed script that is no longer in the Scripts folder, the folder is read again on a thread. That read now has the window's context, so it asks for a frame when it ends and an idle window takes in the new listing (and the macOS menu bar follows it) without waiting for the next input event. --- crates/ui-egui/src/scripts_menu.rs | 3 ++- crates/ui-egui/src/tests/scripts_menu.rs | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index 58be7b7b89..e62a5d8874 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -246,7 +246,8 @@ pub fn readable(p: &Value) -> bool { pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; let source = app.session.installed_script(path).map_err(|e| { - refresh(app, None); + let ctx = app.ui_ctx.clone(); + refresh(app, ctx.as_ref()); e.to_string() })?; app.run("script.run", json!({"source": source, "name": vectorcraft_engine::cmd::fileio::file_name(path)})) diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index f18b60f633..3dc66acca2 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -200,6 +200,28 @@ fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn the_read_after_a_script_that_left_the_folder_asks_for_a_frame() { + let dir = folder("gone-frame"); + let mut app = app(&dir); + let gone = write(&dir, "gone.js", DRAW); + read(&app); + std::fs::remove_file(&gone).unwrap(); + let ctx = egui::Context::default(); + let (tx, frames) = std::sync::mpsc::channel(); + ctx.set_request_repaint_callback(move |_| { + let _ = tx.send(()); + }); + app.ui_ctx = Some(ctx); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().is_err()); + // With the app's copy of the context dropped, only the read's thread can still ask for a + // frame; the channel closes without one when that thread ends without asking. + app.ui_ctx = None; + assert_eq!(frames.recv(), Ok(()), "the finished read asks for a frame so an idle window takes it in"); + scripts_menu::wait(); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { let dir = folder("notes"); From beef32b8a30720e7146ea6f689d790304e44e953 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:37:17 -0800 Subject: [PATCH 11/83] Artboards: an artboard's guide label colors its own guides Each artboard can carry a guide label: one of the layer colors or a custom RGB. Guides that belong to an artboard draw in its label color, and guides without an artboard, or on an artboard without a label, keep the guide color from the preferences. Selected guides still draw in the selection color. - Artboard Options has a Guide Label row (None, the layer colors with swatches, or Custom with a color swatch). - artboard.new and artboard.setProps take guideLabel: null, a layer color's name, or #rrggbb. Any other value is an error. The inspect summary lists guideLabel when one is set. - The native format saves the label and skips it when unset; a preset index outside the layer colors reads as no label. - artboard.setProps no longer adds an undo step when nothing changes. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/artboard.rs | 14 +- crates/doc/src/document.rs | 1 + crates/doc/src/node/ids.rs | 26 ++++ crates/doc/src/tests.rs | 47 +++++++ .../src/cmd/fileio/affinity/document.rs | 1 + crates/engine/src/cmd/fileio/encode.rs | 1 + crates/engine/src/cmd/layer.rs | 50 ++++++- crates/engine/src/cmd/menucmds.rs | 1 + crates/engine/src/cmd/newdoc.rs | 1 + crates/engine/src/inspect.rs | 6 +- crates/engine/src/tests/panelcmds.rs | 124 +++++++++++++++++- crates/eps/src/import/ai/read/document.rs | 2 + crates/pdf/src/import/entry.rs | 1 + crates/pdf/src/tests.rs | 4 + crates/pdf/src/tests/print.rs | 1 + crates/pdf/src/tests/webview.rs | 1 + crates/svg/src/import/layers.rs | 1 + crates/tools/src/rulerguide/tests.rs | 2 + crates/ui-egui/src/canvas.rs | 19 ++- crates/ui-egui/src/canvas/tests.rs | 67 ++++++++++ .../ui-egui/src/dialogs/artboard_options.rs | 75 ++++++++++- crates/ui-egui/src/dialogs/form.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 58 ++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 16 ++- docs/target-app-parity.md | 1 + 52 files changed, 557 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index d7bfcafca5..ac5db48c76 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -1,4 +1,4 @@ -use super::{Arc, Deserialize, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip}; +use super::{Arc, Deserialize, LayerColor, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Artboard { @@ -39,6 +39,18 @@ pub struct Artboard { /// it behind the art ([`super::Document::with_artboard_fills`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, + /// Guide label (Artboard Options): the color the canvas draws the artboard's own ruler guides + /// in (a guide whose [`super::Guide::artboard`] is this artboard's id), a [`LayerColor`] preset + /// or a custom RGB. None (No label) draws them in the guide color preference, as canvas guides + /// are. Only the canvas uses it: the paper, exports and print don't. Written only when set; a + /// file's preset outside [`super::LAYER_COLORS`] reads as no label. + #[serde(default, deserialize_with = "label_within_palette", skip_serializing_if = "Option::is_none")] + pub guide_label: Option, +} + +/// A file's guide label: a preset index outside [`super::LAYER_COLORS`] reads as no label. +fn label_within_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + Ok(Option::::deserialize(d)?.filter(|c| !matches!(c, LayerColor::Preset(i) if usize::from(*i) >= super::LAYER_COLORS.len()))) } /// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 2a2f8a8d7a..f3f159e531 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -208,6 +208,7 @@ impl Document { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }], layers: vec![], swatches: swatches.into(), diff --git a/crates/doc/src/node/ids.rs b/crates/doc/src/node/ids.rs index 9e09a47a95..58915eb663 100644 --- a/crates/doc/src/node/ids.rs +++ b/crates/doc/src/node/ids.rs @@ -56,4 +56,30 @@ impl LayerColor { LayerColor::Custom(c) => c, } } + + /// The color as text: a preset's name from [`LAYER_COLORS`], else `#rrggbb` (lowercase). + pub fn label_text(self) -> String { + let preset = match self { + LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(i)), + LayerColor::Custom(_) => None, + }; + preset.map_or_else( + || { + let [r, g, b] = self.rgb(); + format!("#{r:02x}{g:02x}{b:02x}") + }, + |(name, _)| (*name).to_string(), + ) + } + + /// The color [`LayerColor::label_text`] names: a preset's name exactly as [`LAYER_COLORS`] + /// spells it, or `#rrggbb` with six hex digits. None for anything else. + pub fn from_label_text(s: &str) -> Option { + if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| *name == s) { + return u8::try_from(i).ok().map(LayerColor::Preset); + } + let hex = s.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?; + let byte = |k: usize| u8::from_str_radix(&hex[k..k + 2], 16).ok(); + Some(LayerColor::Custom([byte(0)?, byte(2)?, byte(4)?])) + } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 4b75b01497..21fe8d7ce9 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -5,6 +5,52 @@ mod lookups; mod slices; mod units; +/// A guide label's text is a layer color's name or `#rrggbb`, and reads back as the same color; +/// other spellings, an alpha part and a short form are not labels. +#[test] +fn guide_label_text_names_a_layer_color_or_rgb() { + for (i, (name, _)) in LAYER_COLORS.iter().enumerate() { + let c = LayerColor::Preset(u8::try_from(i).unwrap()); + assert_eq!(c.label_text(), *name); + assert_eq!(LayerColor::from_label_text(name), Some(c)); + } + let custom = LayerColor::Custom([0x0a, 0xbc, 0xff]); + assert_eq!(custom.label_text(), "#0abcff"); + assert_eq!(LayerColor::from_label_text("#0ABCff"), Some(custom)); + // A preset past the layer colors has no name: its text is the color it draws in. + let [r, g, b] = LayerColor::Preset(200).rgb(); + assert_eq!(LayerColor::Preset(200).label_text(), format!("#{r:02x}{g:02x}{b:02x}")); + for bad in ["red", "Red ", "", "#", "#fff", "#0abcff00", "0abcff", "#0abcfg", "#0abcff"] { + assert_eq!(LayerColor::from_label_text(bad), None, "{bad:?}"); + } +} + +/// An artboard's guide label: none unless set, left out of the JSON when none, and a preset past +/// the layer colors reading as none. +#[test] +fn artboard_guide_label_defaults_and_skips_in_json() { + let mut a = Document::new(100.0, 100.0).artboards[0].clone(); + assert_eq!(a.guide_label, None); + let plain = serde_json::to_value(&a).unwrap(); + assert!(plain.get("guide_label").is_none(), "{plain}"); + a.guide_label = Some(LayerColor::Custom([1, 2, 3])); + let v = serde_json::to_value(&a).unwrap(); + assert_eq!(v["guide_label"], serde_json::json!({"Custom": [1, 2, 3]})); + assert_eq!(serde_json::from_value::(v).unwrap(), a); + let read = |label: serde_json::Value| { + let mut v = plain.clone(); + v["guide_label"] = label; + serde_json::from_value::(v).map(|a| a.guide_label) + }; + assert_eq!(read(serde_json::json!({"Preset": 26})).unwrap(), Some(LayerColor::Preset(26))); + assert_eq!(read(serde_json::json!({"Preset": 27})).unwrap(), None); + assert_eq!(read(serde_json::json!({"Preset": 255})).unwrap(), None); + assert_eq!(read(serde_json::Value::Null).unwrap(), None); + assert!(read(serde_json::json!({"Preset": -1})).is_err()); + assert!(read(serde_json::json!({"Tint": 1})).is_err()); + assert_eq!(serde_json::from_value::(plain).unwrap().guide_label, None, "older files have none"); +} + /// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch /// are binary fractions now, and the minor ticks between them stay binary too; every other /// unit is still read in tenths. @@ -146,6 +192,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let rect = |d: &mut Document, r: Rect, appearance: Appearance| { let id = d.alloc_id(); diff --git a/crates/engine/src/cmd/fileio/affinity/document.rs b/crates/engine/src/cmd/fileio/affinity/document.rs index e87e9ac0f0..9114e9a40f 100644 --- a/crates/engine/src/cmd/fileio/affinity/document.rs +++ b/crates/engine/src/cmd/fileio/affinity/document.rs @@ -88,6 +88,7 @@ impl Builder { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); if self.doc.artboards.is_empty() { diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1108d3e2ca..84188c313a 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -373,6 +373,7 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }]; d } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 25201db87e..07571ad320 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "New Artboard", ["Window", "Artboards"], None, - "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", + "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), guideLabel?: name | \"#rrggbb\" | null (its guide label, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", has_doc, artboard_new ), @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", + "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", has_doc, artboard_set ), @@ -859,6 +859,22 @@ fn artboard_color(p: &Value, cmd: &str) -> Result Result>> { + match p.get("guideLabel") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v) => v + .as_str() + .and_then(LayerColor::from_label_text) + .map(|c| Some(Some(c))) + .ok_or_else(|| bad(cmd, "`guideLabel` is null, a layer color's name or #rrggbb")), + } +} + /// An artboard command's text param `key`: None when absent or null, else the string. Any other /// value, such as 5, is an error: "`{key}` must be a string". fn artboard_str<'a>(p: &'a Value, key: &str, cmd: &str) -> Result> { @@ -898,6 +914,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { let last = d0.artboards.last().map(|a| a.rect).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0)); let def = Rect::new(last.x1 + 20.0, last.y0, last.x1 + 20.0 + last.width(), last.y1); let color = artboard_color(p, "artboard.new")?.flatten(); + let guide_label = artboard_guide_label(p, "artboard.new")?.flatten(); check_switches(p, &["showCenterMark", "showCrossHairs", "showVideoSafeAreas"], "artboard.new")?; check_numbers(p, &["x", "y", "width", "height"], "artboard.new")?; let r = match artboard_side(p, "artboard.new")? { @@ -932,6 +949,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { show_video_safe_areas, video_ruler_pixel_aspect_ratio, color, + guide_label, }); Ok(d.artboards.len() - 1) })?; @@ -1001,6 +1019,7 @@ struct ArtboardEdit<'a> { now: Rect, name: Option<&'a str>, color: Option>, + guide_label: Option>, lock: Option, center_mark: Option, cross_hairs: Option, @@ -1013,6 +1032,23 @@ struct ArtboardEdit<'a> { art: Vec, } +impl ArtboardEdit<'_> { + /// Does the edit change artboard `a` (the one at its index) or the art and guides on it? + fn changes(&self, a: &Artboard) -> bool { + let name = self.name.map(|n| if n.is_empty() { format!("Artboard {}", self.index + 1) } else { n.to_string() }); + self.now != a.rect + || self.transform.is_some() + || name.is_some_and(|n| n != a.name) + || self.color.is_some_and(|c| c != a.color) + || self.guide_label.is_some_and(|c| c != a.guide_label) + || self.lock.is_some_and(|l| l != a.locked) + || self.center_mark.is_some_and(|m| m != a.show_center_mark) + || self.cross_hairs.is_some_and(|c| c != a.show_cross_hairs) + || self.safe_areas.is_some_and(|v| v != a.show_video_safe_areas) + || self.pixel_aspect.is_some_and(|r| r != a.video_ruler_pixel_aspect_ratio) + } +} + fn artboard_set(s: &mut Session, p: &Value) -> Result { // One artboard (`index` and its fields), or several (`artboards`, each with its own fields). let entries: Vec<&Value> = match p.get("artboards") { @@ -1044,6 +1080,8 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { let was = d.artboards.get(index).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; // The background color: a color sets it, null clears it, absent leaves it as it is. let color = artboard_color(q, "artboard.setProps")?; + // The guide label likewise; a locked artboard's can change, as its name can. + let guide_label = artboard_guide_label(q, "artboard.setProps")?; let now = rect_from(q, was); let lock = q.get("locked").and_then(Value::as_bool); let (center_mark, cross_hairs) = (q.get("showCenterMark").and_then(Value::as_bool), q.get("showCrossHairs").and_then(Value::as_bool)); @@ -1070,6 +1108,7 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { now, name: artboard_str(q, "name", "artboard.setProps")?.map(str::trim), color, + guide_label, lock, center_mark, cross_hairs, @@ -1082,6 +1121,10 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { art, }); } + // Nothing to change: no undo step. + if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) { + return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() }; + } // Noted in the journal when art goes along, so a replay transforms the same objects whatever // the preference is then. if edits.iter().any(|e| e.transform.is_some()) { @@ -1102,6 +1145,9 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { if let Some(c) = e.color { a.color = c; } + if let Some(c) = e.guide_label { + a.guide_label = c; + } if let Some(l) = e.lock { a.locked = l; } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 0a4c93dc5e..ed17677790 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1319,6 +1319,7 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); converted.push(id); } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index d8f0681cc0..20dc187ab5 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -344,6 +344,7 @@ impl DocSettings { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); d diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14df8529d7..c474e25756 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -133,7 +133,8 @@ pub fn document(s: &Session) -> Value { document_opts(s, SummaryOpts::default()) } -/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one, +/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one, its guide +/// label (a layer color's name or `#rrggbb`) when it has one, /// `locked: true` when it is locked, `showCenterMark: true`, `showCrossHairs: true` and /// `showVideoSafeAreas: true` when it shows them, and `videoRulerPixelAspectRatio` when it isn't 1. fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value { @@ -141,6 +142,9 @@ fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value { if let Some(c) = a.color { v["color"] = json!(c.to_hex()); } + if let Some(c) = a.guide_label { + v["guideLabel"] = json!(c.label_text()); + } for (key, on) in [ ("locked", a.locked), ("showCenterMark", a.show_center_mark), diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 239d6bee7b..4d549c31ef 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_color::{Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, NodeKind}; +use vectorcraft_doc::{AppearanceItem, LayerColor, NodeKind}; use crate::*; @@ -1387,6 +1387,128 @@ fn artboard_video_display_options_are_set_in_one_undo_step() { assert_eq!(video(&s, 1), (false, 10.0), "10 is in range"); } +/// Artboard Options' guide label: `artboard.setProps {guideLabel}` takes a layer color's name or +/// `#rrggbb` and null clears it, each change one undo step, also on a locked artboard (whose +/// rectangle stays locked) and for several artboards in one list; a value equal to the artboard's +/// adds no undo step. `artboard.new` takes it, a duplicate and an undone delete keep it, and +/// `inspect_document` reports it. A bad value anywhere in a list changes nothing. +#[test] +fn artboard_guide_labels_are_set_and_cleared_in_one_undo_step() { + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + let label = |s: &Session, i: usize| s.doc().unwrap().doc.artboards[i].guide_label; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, None), "no label by default"); + let u0 = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, Some(LayerColor::Preset(1))), "only that artboard"); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "#12aBcd"})).unwrap(); + assert_eq!(label(&s, 1), Some(LayerColor::Custom([0x12, 0xab, 0xcd]))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert_eq!(label(&s, 1), None, "null clears it"); + assert_eq!(undo(&s), u0 + 3, "one undo step each"); + for was in [Some(LayerColor::Custom([0x12, 0xab, 0xcd])), Some(LayerColor::Preset(1)), None] { + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, 1), was); + } + s.execute("edit.redo", &json!({})).unwrap(); + // The same label again, or a list that changes nothing: no undo step. + let u = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": "Red"}]})).unwrap(); + assert_eq!(undo(&s), u, "nothing changed, no undo step"); + // A locked artboard takes a label; its rectangle stays locked. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let rect0 = s.doc().unwrap().doc.artboards[0].rect; + s.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Gold"})).unwrap(); + assert_eq!(label(&s, 0), Some(LayerColor::Preset(15))); + assert!(s.execute("artboard.setProps", &json!({"index": 0, "x": 999, "guideLabel": "Teal"})).is_err()); + assert_eq!((s.doc().unwrap().doc.artboards[0].rect, label(&s, 0)), (rect0, Some(LayerColor::Preset(15)))); + let u = undo(&s); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Teal"}, {"index": 1, "guideLabel": "#000000"}]})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (Some(LayerColor::Preset(11)), Some(LayerColor::Custom([0, 0, 0]))), "each its own"); + assert_eq!(undo(&s), u + 1, "in one undo step"); + let doc = crate::inspect::document(&s); + assert_eq!((doc["artboards"][0]["guideLabel"].clone(), doc["artboards"][1]["guideLabel"].clone()), (json!("Teal"), json!("#000000"))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert!(crate::inspect::document(&s)["artboards"][1].get("guideLabel").is_none(), "no label isn't reported"); + let copy = s.execute("artboard.duplicate", &json!({"index": 0})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, copy), Some(LayerColor::Preset(11)), "a duplicate keeps it"); + let made = s.execute("artboard.new", &json!({"guideLabel": "Violet"})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "a new artboard takes it"); + let plain = s.execute("artboard.new", &json!({})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, plain), None); + s.execute("artboard.delete", &json!({"index": made})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "undoing a delete brings it back"); + let before = s.doc().unwrap().doc.clone(); + let bads = [ + json!("red"), + json!(" Red"), + json!("#12345"), + json!("#1234567"), + json!("#12345678"), + json!("#fff"), + json!("#gg0000"), + json!(1), + json!([1, 2, 3]), + json!({"Preset": 1}), + json!(true), + ]; + for bad in bads { + assert!(s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": bad})).is_err(), "{bad}"); + assert!(s.execute("artboard.new", &json!({"guideLabel": bad})).is_err(), "{bad}"); + assert!( + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Red"}, {"index": 1, "guideLabel": bad}]})).is_err(), + "{bad}" + ); + } + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 1, "guideLabel": "Red"}]})).is_err()); + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 99, "guideLabel": "Red"}]})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *before, "a bad value changes nothing"); +} + +/// The native format keeps the guide label, as `{"Preset": n}` or `{"Custom": [r, g, b]}`. An +/// artboard without one is written as before labels could be set, and a preset outside the layer +/// colors in a file reads as no label. Exports leave the label out. +#[test] +fn artboard_guide_labels_round_trip_through_the_native_format() { + let mut s = session(); + rect(&mut s); + s.execute("artboard.new", &json!({})).unwrap(); + let save = |s: &Session| vectorcraft_format::save(&s.doc().unwrap().doc, false); + let before = save(&s); + let plain = (*s.doc().unwrap().doc).clone(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Green"}, {"index": 1, "guideLabel": "#102030"}]})).unwrap(); + let bytes = save(&s); + let saved: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let ab = |i: usize| saved["document"]["artboards"][i]["guide_label"].clone(); + assert_eq!((ab(0), ab(1)), (json!({"Preset": 2}), json!({"Custom": [16, 32, 48]}))); + let back = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(back.artboards, s.doc().unwrap().doc.artboards); + // Screen-only: SVG and PDF exports are the same as without the labels. + let on = (*s.doc().unwrap().doc).clone(); + assert_eq!(vectorcraft_svg::export(&on, &Default::default()), vectorcraft_svg::export(&plain, &Default::default())); + let options = vectorcraft_pdf::PdfOptions { created: Some(0), ..Default::default() }; + assert_eq!(crate::export_pdf(&on, &options).unwrap(), crate::export_pdf(&plain, &options).unwrap()); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": null}]})).unwrap(); + assert_eq!(save(&s), before, "without labels, the file is as it was"); + // A file's labels as another writer might put them: a preset past the layer colors reads as + // none, and a label that isn't a layer color at all is refused. + let mut edited = saved.clone(); + edited["document"]["artboards"][0]["guide_label"] = json!({"Preset": 27}); + edited["document"]["artboards"][1]["guide_label"] = json!({"Preset": 26}); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!((back.artboards[0].guide_label, back.artboards[1].guide_label), (None, Some(LayerColor::Preset(26)))); + for bad in [json!({"Preset": 256}), json!({"Custom": [1, 2]}), json!("Red"), json!({"Custom": [1, 2, 300]})] { + edited["document"]["artboards"][0]["guide_label"] = bad.clone(); + assert!(vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).is_err(), "{bad}"); + } + edited["document"]["artboards"][0]["guide_label"] = json!(null); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!(back.artboards[0].guide_label, None); +} + /// The native format keeps Show Video Safe Areas and the Video Ruler Pixel Aspect Ratio. A /// document whose artboards hide the safe areas and have square pixels is written byte for byte as /// before they could be set, a file written without the two keys opens with the safe areas off diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 63e9f3df77..0e1ca67676 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1209,6 +1209,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: b.safe_areas, video_ruler_pixel_aspect_ratio: b.par, color: None, + guide_label: None, }) .collect(); if doc.artboards.is_empty() { @@ -1223,6 +1224,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }]; } doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 687fcb1566..38f22689a8 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -375,6 +375,7 @@ fn read_opened( show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let page_layer = |b: &mut Builder<'_>, art: Vec>, shown: bool| { let name = if shown { format!("Page {}", number + 1) } else { format!("Page {} (unsorted)", number + 1) }; diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 365b653890..af744437d5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -131,6 +131,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.artboards.push(Artboard { id: 3, @@ -142,6 +143,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions::default()).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -162,6 +164,7 @@ fn artboard_range_and_bad_index() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions { artboards: Some(vec![1]), ..Default::default() }).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -893,6 +896,7 @@ fn import_max_pages_and_multi_page() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); add(&mut d, rect_node(Rect::new(10.0, 10.0, 50.0, 50.0), Color::BLACK)); add(&mut d, rect_node(Rect::new(310.0, 10.0, 350.0, 50.0), Color::BLACK)); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index daf2bab071..2f59563e70 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -33,6 +33,7 @@ fn artboard(id: u32, x: f64) -> Artboard { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, } } diff --git a/crates/pdf/src/tests/webview.rs b/crates/pdf/src/tests/webview.rs index 9a4659ddce..a40db425e7 100644 --- a/crates/pdf/src/tests/webview.rs +++ b/crates/pdf/src/tests/webview.rs @@ -31,6 +31,7 @@ fn doc(n: usize, image: bool, on_first: bool) -> Document { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); } let mut png = vec![]; diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index 04e3887945..15a77e37f0 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -146,6 +146,7 @@ pub(super) fn inkscape_pages(xml: &roxmltree::Document, user: Affine) -> Option< show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); (!pages.is_empty()).then_some(pages) diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index a4a91d24c5..4b4f1be72c 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -289,6 +289,7 @@ fn an_artboard_guide_is_picked_and_snapped_to_across_its_artboard_only() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.guides = vec![Guide { artboard: Some(id), ..Guide::new(false, 150.0) }]; let (s, p) = (Selection::default(), paint()); @@ -604,6 +605,7 @@ fn ruler_guide_readouts_count_from_the_active_artboard_with_artboard_rulers() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); doc.ruler_origin = Point::new(5.0, 5.0); let (paint, selection) = (paint(), Selection::default()); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c25acd07a6..63be246dac 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1087,11 +1087,14 @@ fn guide_lines(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egu } } -/// The ruler guides of document `st`, its selected guides in the selection colour. +/// The ruler guides of document `st`, its selected guides in the selection colour. An artboard +/// guide of an artboard with a guide label ([`vectorcraft_doc::Artboard::guide_label`]) is drawn in +/// the label's color, in the guide preference's style; the others in the guide preference's color. fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, xf, t): (&egui::Painter, &Xf, &Tokens), rect: egui::Rect) { let doc = &st.doc; let look = LineLook::guides(&app.session.prefs, t); let picked = LineLook { color: t.selection, ..look }; + let labels = guide_labels(doc); let selected: &[usize] = &st.selection.guides; let key = st.selection.key_guide; let view = view_bounds(xf); @@ -1108,7 +1111,8 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, ends } }; - if selected.contains(&i) { picked } else { look }.guide(painter, a, b); + let own = g.artboard.and_then(|id| labels.get(&id)).map_or(look, |&color| LineLook { color, ..look }); + if selected.contains(&i) { picked } else { own }.guide(painter, a, b); // The key guide (Align to Key Object, #2143): thicker, as a key object's outline is. if key == Some(i) { painter.line_segment([a, b], Stroke::new(KEY_OUTLINE, picked.color)); @@ -1116,6 +1120,17 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, } } +/// The guide label colors of `doc`'s artboards that have one, by artboard id. +pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections::HashMap { + doc.artboards + .iter() + .filter_map(|a| { + let [r, g, b] = a.guide_label?.rgb(); + Some((a.id, Color32::from_rgb(r, g, b))) + }) + .collect() +} + /// The selection's visuals and the tools' overlays, to be drawn. fn selection_visuals( app: &mut VectorcraftApp, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b76599a4bc..a9ef2c228d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1208,6 +1208,73 @@ fn a_drag_from_a_ruler_onto_the_canvas_makes_a_guide() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the tool drew nothing"); } +/// An artboard's guide label colors its own guides only: a canvas guide, a guide of an artboard +/// without a label and a guide of a deleted artboard keep the guide color preference, and a +/// selected labeled guide takes the selection color. Hide Guides hides labeled guides too. +#[test] +fn artboard_guide_label_colors_only_its_own_guides() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Red"})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": "#00ff00"})).unwrap(); + // Vertical guides at x 100 (artboard 1, Red), 520 (artboard 2, no label) and 940 (artboard + // 3, whose artboard is then deleted), and a horizontal canvas guide at y 150. + for (pos, artboard) in [(100, json!(0)), (520, json!(1)), (940, json!(2))] { + app.session.execute("guide.add", &json!({"vertical": true, "pos": pos, "artboard": artboard})).unwrap(); + } + app.session.execute("guide.add", &json!({"vertical": false, "pos": 150})).unwrap(); + // Deleting artboard 3 deletes its guide; a guide still naming its id (as a file might) is an + // orphan, drawn across the canvas. + let gone = app.session.active().unwrap().doc.artboards[2].id; + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": null})).unwrap(); + app.session.execute("artboard.delete", &json!({"index": 2})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + { + let st = app.session.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let last = doc.guides.len() - 1; + doc.guides[last].artboard = Some(gone); + } + app.ui.view.guides = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let t = Tokens::get(&ctx); + let pref = LineLook::guides(&app.session.prefs, &t).color; + let colors = |app: &mut VectorcraftApp, at: f64, vertical: bool| -> Vec { + shapes(app, &ctx) + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, stroke } => { + let (a, b) = (xf.to_doc(points[0]), xf.to_doc(points[1])); + let (u, v) = if vertical { (a.x, b.x) } else { (a.y, b.y) }; + ((u - at).abs() < 0.01 && (v - at).abs() < 0.01).then_some(stroke.color) + } + _ => None, + }) + .collect() + }; + let red = Color32::from_rgb(0xff, 0x4f, 0x4f); + assert_eq!(colors(&mut app, 100.0, true), [red], "the labeled artboard's guide"); + assert_eq!(colors(&mut app, 520.0, true), [pref], "an artboard without a label"); + assert_eq!(colors(&mut app, 150.0, false), [pref], "a canvas guide"); + assert!(colors(&mut app, 940.0, true).is_empty(), "deleted with its artboard"); + assert_eq!(colors(&mut app, 300.0, true), [pref], "a guide whose artboard is gone"); + assert_ne!(red, pref); + // Selected, it is drawn in the selection color; deselected, in the label's again. + app.session.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [t.selection], "selected"); + app.session.execute("guide.select", &json!({"indexes": []})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [red], "deselected"); + // A new label shows on the next frame. + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Black"})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [Color32::BLACK]); + app.ui.view.guides = false; + assert!(colors(&mut app, 100.0, true).is_empty(), "Hide Guides hides it"); +} + /// #4646: a guide dragged out of a ruler shows as a line across the canvas while it is dragged, /// also with Preferences › Performance › Real-time Drawing and Editing off (only its position /// label showed then). diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 0ce0de9350..1854eba4b9 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -1,7 +1,8 @@ //! Artboard Options (double-click with the Artboard tool, double-click the tool, or the Artboards //! panel's options icon or menu): the artboard's fields, sizes parsed with units, its position //! from a reference point, its background color (`color`: a color as the paint commands take -//! it, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, +//! it, or null for none), its guide label (`guideLabel`: the color its own guides are drawn in, a +//! layer color's name or `#rrggbb`, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, //! `showCrossHairs`), the display marks the canvas draws on the artboard //! (https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html), //! and its video display options, Show Video Safe Areas and Video Ruler Pixel Aspect Ratio @@ -15,7 +16,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; -use vectorcraft_doc::Unit; +use vectorcraft_doc::{LAYER_COLORS, LayerColor, Unit}; use vectorcraft_engine::cmd::color_value; use vectorcraft_geom::{Point, Rect}; @@ -32,7 +33,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, // A new artboard's dialog opens without these; its swatch, checkboxes and Video Ruler Pixel // Aspect Ratio field add them. The Global checkboxes' fields come from the preferences. - inputs: |_| &["color", "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], + inputs: |_| &["color", GUIDE_LABEL, "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], ..DialogSpec::FORM }; @@ -49,7 +50,7 @@ fn placed(d: &Dialog) -> Rect { /// as the Transform panel and the Control bar show an artboard's. A new Width or Height keeps the /// reference point where it was, as their sizes do. /// Then Background Color: the Fill list (None, White, Black; Custom for another color) and a swatch -/// that picks a color of its own, the Show Center Mark, Show Cross Hairs and Show Video Safe Areas +/// that picks a color of its own, the Guide Label row ([`guide_label_row`]), the Show Center Mark, Show Cross Hairs and Show Video Safe Areas /// checkboxes, and the Video Ruler Pixel Aspect Ratio field. Last, under Global, the Fade Region /// Outside Artboard and Update While Dragging checkboxes. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -116,6 +117,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Some(c) = set { d.fields.insert("color".into(), c.as_ref().map_or(Value::Null, crate::panels::color_json)); } + guide_label_row(ui, d); ui.add_space(8.0); form::check(ui, d, "showCenterMark", tl!("Show Center Mark")); form::check(ui, d, "showCrossHairs", tl!("Show Cross Hairs")); @@ -137,6 +139,64 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// The field of the guide label, as `artboard.setProps` and `artboard.new` take it: a layer +/// color's name, `#rrggbb`, or null for none. +pub(super) const GUIDE_LABEL: &str = "guideLabel"; + +/// The size of the color chip before each name in the Guide Label list. +const CHIP: egui::Vec2 = egui::vec2(16.0, 10.0); + +/// The Guide Label row: a list of None, the layer colors (each after a chip of its color) and +/// Custom, and, while the artboard has a label, a swatch that picks a color of its own. Custom +/// keeps the label's color as a `#rrggbb` value. +fn guide_label_row(ui: &mut egui::Ui, d: &mut Dialog) { + let now = d.fields.get(GUIDE_LABEL).and_then(Value::as_str).and_then(LayerColor::from_label_text); + let shown = match now { + None => "None", + Some(LayerColor::Preset(i)) => LAYER_COLORS.get(usize::from(i)).map_or("Custom", |(n, _)| *n), + Some(LayerColor::Custom(_)) => "Custom", + }; + let mut set = None; + ui.horizontal(|ui| { + let row = form::row_label(ui, tl!("Guide Label:")); + ui.label_inputs_by(row.id, |ui| { + let border = crate::theme::Tokens::get(ui.ctx()).input_border; + let rows = std::iter::once(("None", None)).chain(LAYER_COLORS.iter().map(|(n, c)| (*n, Some(*c)))).chain([("Custom", None)]); + let picked = crate::widgets::combo(ui, "ab-options-guide-label", tl!(shown), 140.0, |ui| { + let mut chosen = None; + for (i, (name, rgb)) in rows.enumerate() { + let chip = egui::IdSalt::new(("ab-guide-label-chip", i)); + let r = egui::Button::selectable(name == shown, (egui::Atom::custom(chip, CHIP), tl!(name))).atom_ui(ui); + if let (Some(rect), Some([cr, cg, cb])) = (r.rect(chip), rgb) { + ui.painter().rect_filled(rect, 1.0, egui::Color32::from_rgb(cr, cg, cb)); + ui.painter().rect_stroke(rect, 1.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + } + if r.response.clicked() { + chosen = Some(i); + } + } + chosen + }); + match picked { + Some(0) => set = Some(None), + Some(i) if i <= LAYER_COLORS.len() => set = u8::try_from(i - 1).ok().map(|i| Some(LayerColor::Preset(i))), + Some(_) => set = Some(Some(LayerColor::Custom(now.map_or(LAYER_COLORS[0].1, LayerColor::rgb)))), + None => {} + } + if let Some(c) = now { + let mut rgb = c.rgb(); + let swatch_name = format!("{} {}", tl!("Guide Label:"), tl!("Swatches")); + if ui.name_inputs(swatch_name, |ui| ui.color_edit_button_srgb(&mut rgb)).changed() { + set = Some(Some(LayerColor::Custom(rgb))); + } + } + }); + }); + if let Some(c) = set { + d.fields.insert(GUIDE_LABEL.into(), c.map_or(Value::Null, |c| json!(c.label_text()))); + } +} + /// The preference and field of Fade Region Outside Artboard: while the Artboard tool is active, /// the canvas draws everything outside the artboards darker. const FADE: &str = "fadeRegionOutsideArtboard"; @@ -292,8 +352,10 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let a = st.doc.artboards.get(index).ok_or("no artboard")?; let r = a.rect; let color = a.color.as_ref().map(crate::panels::color_json); + let guide_label = a.guide_label.map(LayerColor::label_text); let fields = json!({ "index": index, "name": a.name, "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "color": color, + GUIDE_LABEL: guide_label, "showCenterMark": a.show_center_mark, "showCrossHairs": a.show_cross_hairs, "showVideoSafeAreas": a.show_video_safe_areas, PIXEL_ASPECT: a.video_ruler_pixel_aspect_ratio, }); @@ -374,7 +436,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { } /// OK for a new artboard: `artboard.new` with the fields (an empty name gives the default one), -/// the background color picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio +/// the background color and guide label picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio /// typed, and the new artboard becomes the active one. fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = json!({}); @@ -388,6 +450,9 @@ fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(c) = d.fields.get("color") { p["color"] = c.clone(); } + if let Some(c) = d.fields.get(GUIDE_LABEL).filter(|c| !c.is_null()) { + p[GUIDE_LABEL] = c.clone(); + } for k in ["showCenterMark", "showCrossHairs", "showVideoSafeAreas"] { if d.bool(k) { p[k] = json!(true); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index c87cfb7e63..bbddd222f5 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -120,7 +120,7 @@ fn suffix(kind: &str, key: &str) -> Option<&'static str> { /// The fields of the form dialogs ([`grid`]) that the dialog's own body draws, by dialog kind. fn own_rows(kind: &str) -> &'static [&'static str] { match kind { - "artboardOptions" => &["color", super::artboard_options::PIXEL_ASPECT], + "artboardOptions" => &["color", super::artboard_options::GUIDE_LABEL, super::artboard_options::PIXEL_ASPECT], // The grids' Reference Point is their 9-point locator. "rectangularGrid" | "polarGrid" => &["reference"], _ => &[], diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c5bdfea5c8..2ad8bdf213 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1755,6 +1755,64 @@ fn new_artboard_options_give_the_new_artboard_its_background_color() { } } +/// Artboard Options shows the artboard's guide label on its Guide Label: row (None, a layer color's +/// name, or Custom). OK sets a label picked there in one undo step, keeps it while another field +/// changes, and a null `guideLabel` clears it; Cancel leaves it. OK with nothing changed adds no +/// undo step, and a new artboard's Artboard Options gives it the label picked. +#[test] +fn artboard_options_shows_sets_and_clears_the_guide_label() { + let mut app = app(); + let label = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[0].guide_label.map(vectorcraft_doc::LayerColor::label_text); + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let lines = |app: &mut VectorcraftApp| { + let text = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + text.lines().map(str::trim).map(str::to_string).collect::>() + }; + crate::dialogs::artboard_options::open(&mut app).unwrap(); + let shown = lines(&mut app); + assert!(shown.iter().any(|l| l == "Guide Label:"), "{shown:?}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!(null)); + let u = undo(&app); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app), undo(&app)), (None, u), "OK with nothing changed"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("Orange")); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app).as_deref(), undo(&app)), (Some("Orange"), u + 1)); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!("Orange")); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + cancel(&mut app); + assert_eq!(label(&app).as_deref(), Some("Orange"), "Cancel leaves it"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + super::confirm(&mut app).unwrap(); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Custom")); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Card")); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app).as_deref(), Some("#123456"), "kept while another field changes"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("purple")); + assert!(super::confirm(&mut app).is_err(), "a name in other letter case is refused"); + assert_eq!(label(&app).as_deref(), Some("#123456")); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!(null)); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app), None); + for (picked, want) in [(Some(json!("Teal")), Some("Teal")), (None, None)] { + app.run("ui.newArtboard", json!({})).unwrap(); + if let Some(c) = picked { + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), c); + } + super::confirm(&mut app).unwrap(); + let ab = app.session.doc().unwrap().doc.artboards.last().cloned().unwrap(); + assert_eq!(ab.guide_label.map(vectorcraft_doc::LayerColor::label_text).as_deref(), want); + } +} + /// Artboard Options shows Show Center Mark and Show Cross Hairs, ticked as the artboard has them /// whether it opens from the Artboards panel or from a double-click with the Artboard tool. OK /// sets them in one undo step, and a new artboard's Artboard Options gives it the ones ticked. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2738281c30..1f8fa29f75 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -276,6 +276,7 @@ font-technology Variable Променливи Average… Усредняване… Axis: Ос: Background Color: Цвят на фона: + Guide Label: Етикет на водачите: Show Center Mark Показване на централен знак Show Cross Hairs Показване на кръстосани линии Show Video Safe Areas Показване на безопасните видеозони diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f6d0fe0771..cb38ec15bf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2623,6 +2623,7 @@ digits Malayalam Malajalam File Dimensions Dimenzije datoteke Transforms Transformacije Background Color: Boja pozadine: + Guide Label: Oznaka vodilica: Show Center Mark Prikaži oznaku centra Show Cross Hairs Prikaži končanicu Show Video Safe Areas Prikaži sigurne oblasti za video diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 017a0c4498..fb3a68880e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -428,6 +428,7 @@ antiAlias Sharp Nítid B5 B5 Back Enrere Background Color: Color de fons: + Guide Label: Etiqueta de les guies: Background Contents Contingut del fons Background Level Nivell de fons Background: Fons: @@ -5129,6 +5130,7 @@ digits Malayalam Malaiàlam @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis ha de ser "vertical", "horizontal" o un angle en graus, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fons {other}: transparent, blanc, negre o un color com "#ff8800" @msg bad color {v} color incorrecte {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` és null, el nom d’un color de capa o #rrggbb @msg bad colour `{hex}` (#rrggbb) color incorrecte `{hex}` (#rrggbb) @msg bad page tree arbre de pàgines incorrecte @msg bad shortcut drecera incorrecta diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 28f70f1f2b..6f9190d3b0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2654,6 +2654,7 @@ digits Malayalam Malajálamské File Dimensions Rozměry souboru Transforms Transformace Background Color: Barva pozadí: + Guide Label: Štítek vodítek: Show Center Mark Zobrazit středovou značku Show Cross Hairs Zobrazit nitkový kříž Show Video Safe Areas Zobrazit bezpečné oblasti videa @@ -4594,6 +4595,7 @@ imageTrace Outline Obrys @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musí být "vertical", "horizontal" nebo úhel ve stupních, ne `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" pozadí {other}: transparent, white, black nebo barva jako "#ff8800" @msg bad color {v} chybná barva {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` je null, název barvy vrstvy nebo #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musí být číslo od 0,1 do 10 @msg the Color Picker is not open Výběr barvy není otevřený @msg the Simplify slider is not open Posuvník Zjednodušit není otevřený diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index dc580db9ea..160219a825 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2442,6 +2442,7 @@ digits Malayalam Malayalam File Dimensions Fildimensioner Transforms Transformationer Background Color: Baggrundsfarve: + Guide Label: Hjælpelinjeetiket: Show Center Mark Vis midtermærke Show Cross Hairs Vis trådkors Show Video Safe Areas Vis sikre videoområder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1ca7293eab..3bffaab6cc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -264,6 +264,7 @@ font-technology Variable Variabel Average… Durchschnitt berechnen… Axis: Achse: Background Color: Hintergrundfarbe: + Guide Label: Farbmarkierung der Hilfslinien: Show Center Mark Mittelpunktmarke einblenden Show Cross Hairs Fadenkreuz einblenden Show Video Safe Areas Videosichere Bereiche einblenden @@ -4201,6 +4202,7 @@ theme Appearance Erscheinungsbild @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis muss "vertical", "horizontal" oder ein Winkel in Grad sein, nicht `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black oder eine Farbe wie "#ff8800" @msg bad color {v} ungültige Farbe {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` ist null, der Name einer Ebenenfarbe oder #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio muss eine Zahl von 0,1 bis 10 sein @msg the Color Picker is not open der Farbwähler ist nicht geöffnet @msg the Simplify slider is not open der Regler „Vereinfachen“ ist nicht geöffnet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 13081c2248..adfd536b32 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -267,6 +267,7 @@ font-technology Variable Μεταβλητές Average… Μέσος όρος… Axis: Άξονας: Background Color: Χρώμα φόντου: + Guide Label: Ετικέτα οδηγών: Show Center Mark Εμφάνιση σημαδιού κέντρου Show Cross Hairs Εμφάνιση σταυρονήματος Show Video Safe Areas Εμφάνιση ασφαλών περιοχών βίντεο @@ -4245,6 +4246,7 @@ digits Malayalam Μαλαγιάλαμ @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` το axis πρέπει να είναι "vertical", "horizontal" ή γωνία σε μοίρες, όχι `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" φόντο {other}: transparent, white, black ή χρώμα όπως "#ff8800" @msg bad color {v} μη έγκυρο χρώμα {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb το `guideLabel` είναι null, όνομα χρώματος επιπέδου ή #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 Το videoRulerPixelAspectRatio πρέπει να είναι αριθμός από 0,1 έως 10 @msg bad colour `{hex}` (#rrggbb) μη έγκυρο χρώμα `{hex}` (#rrggbb) @msg bad page tree μη έγκυρο δέντρο σελίδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 820daa8a60..7d889acf26 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -289,6 +289,7 @@ font-technology Variable Variables Average… Promediar… Axis: Eje: Background Color: Color de fondo: + Guide Label: Etiqueta de las guías: Show Center Mark Mostrar marca central Show Cross Hairs Mostrar líneas en cruz Show Video Safe Areas Mostrar áreas seguras de video @@ -4285,6 +4286,7 @@ axis Both Ambos @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis debe ser "vertical", "horizontal" o un ángulo en grados, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fondo {other}: transparent, white, black o un color como "#ff8800" @msg bad color {v} color no válido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` es null, el nombre de un color de capa o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio debe ser un número de 0,1 a 10 @msg the Color Picker is not open el Selector de color no está abierto @msg the Simplify slider is not open el regulador de Simplificar no está abierto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 986f29ca7b..3109ac7248 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2598,6 +2598,7 @@ digits Malayalam Malajalam File Dimensions Tiedoston mitat Transforms Muunnokset Background Color: Taustaväri: + Guide Label: Apuviivojen tunniste: Show Center Mark Näytä keskimerkki Show Cross Hairs Näytä hiusristikko Show Video Safe Areas Näytä videon turva-alueet @@ -4507,6 +4508,7 @@ imageTrace Outline Ääriviiva @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis-arvon on oltava "vertical", "horizontal" tai kulma asteina, ei `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tausta {other}: transparent, white, black tai väri, kuten "#ff8800" @msg bad color {v} virheellinen väri {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` on null, tasovärin nimi tai #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio on oltava luku väliltä 0,1–10 @msg bad colour `{hex}` (#rrggbb) virheellinen väri `{hex}` (#rrggbb) @msg bad page tree virheellinen sivupuu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ac86d58038..6707f941bc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -290,6 +290,7 @@ font-technology Variable Variables Average… Alignement… Axis: Axe : Background Color: Couleur d’arrière-plan : + Guide Label: Étiquette des repères : Show Center Mark Afficher le repère central Show Cross Hairs Afficher le réticule Show Video Safe Areas Afficher les zones de sécurité vidéo @@ -4274,6 +4275,7 @@ axis Both Les deux @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis doit être "vertical", "horizontal" ou un angle en degrés, pas `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" arrière-plan {other} : transparent, white, black ou une couleur comme "#ff8800" @msg bad color {v} couleur non valide {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` est null, le nom d’une couleur de calque ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio doit être un nombre de 0,1 à 10 @msg the Color Picker is not open le Sélecteur de couleurs n’est pas ouvert @msg the Simplify slider is not open le curseur Simplifier n’est pas ouvert diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1c8e722d9c..e74242c255 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -497,6 +497,7 @@ antiAlias Sharp शार्प B5 B5 Back वापस Background Color: बैकग्राउंड रंग: + Guide Label: गाइड लेबल: Background Contents बैकग्राउंड सामग्री Background Level बैकग्राउंड स्तर Background: बैकग्राउंड: @@ -6040,6 +6041,7 @@ antiAlias Sharp शार्प @msg bad base64 बुरा आधार64 @msg bad color {c} बुरा रंग {c} @msg bad color {v} बुरा रंग {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, किसी लेयर रंग का नाम या #rrggbb होता है @msg bad colour बुरा रंग @msg bad colour {v} बुरा रंग {v} @msg bad colour {v} in groupColors groupColors में अमान्य रंग {v} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2777645b2c..19af5e3a32 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -385,6 +385,7 @@ font-technology Variable Változó B4 B4 B5 B5 Background Color: Háttérszín: + Guide Label: Segédvonalak címkéje: Show Center Mark Középjel megjelenítése Show Cross Hairs Szálkereszt megjelenítése Show Video Safe Areas Biztonságos videoterületek megjelenítése @@ -4833,6 +4834,7 @@ imageTrace Outline Körvonal @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` az axis értéke "vertical", "horizontal" vagy fokban megadott szög lehet, ez nem az: `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black vagy egy szín, például "#ff8800" @msg bad color {v} hibás szín: {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb a `guideLabel` értéke null, egy rétegszín neve vagy #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio: 0,1 és 10 közötti szám kell @msg the Color Picker is not open a Színválasztó nincs megnyitva @msg the Simplify slider is not open az Egyszerűsítés csúszka nincs megnyitva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bfa91456ba..0e1328833f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2442,6 +2442,7 @@ digits Malayalam Malayalam File Dimensions Dimensi file Transforms Transformasi Background Color: Warna latar belakang: + Guide Label: Label panduan: Show Center Mark Tampilkan tanda tengah Show Cross Hairs Tampilkan garis silang Show Video Safe Areas Tampilkan area aman video diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 00e9cbeb69..fc8de1649d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -289,6 +289,7 @@ font-technology Variable Variabili Average… Media… Axis: Asse: Background Color: Colore di sfondo: + Guide Label: Etichetta delle guide: Show Center Mark Mostra segno centrale Show Cross Hairs Mostra mirino Show Video Safe Areas Mostra aree sicure video @@ -4328,6 +4329,7 @@ axis Both Entrambi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve essere "vertical", "horizontal" o un angolo in gradi, non `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" sfondo {other}: transparent, white, black o un colore come "#ff8800" @msg bad color {v} colore non valido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` è null, il nome di un colore di livello o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve essere un numero da 0,1 a 10 @msg the Color Picker is not open il Selettore colore non è aperto @msg the Simplify slider is not open il cursore Semplifica non è aperto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2b2802a196..a3e7d44284 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1077,6 +1077,7 @@ antiAlias Sharp シャープ Average 平均 BLANK DOCUMENT PRESETS 空白のドキュメントプリセット Background Color: 背景色: + Guide Label: ガイドのラベル: Show Center Mark 中心マークを表示 Show Cross Hairs 十字線を表示 Show Video Safe Areas ビデオセーフエリアを表示 @@ -4684,6 +4685,7 @@ swatch Bright Violet ビビッドバイオレット @msg {label}… {label}… @msg no blend options ブレンドオプションがありません @msg bad color {v} カラー {v} が正しくありません +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` は null、レイヤーカラーの名前、または #rrggbb です @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio には 0.1 〜 10 の数値を指定してください @msg the Color Picker is not open カラーピッカーが開いていません @msg the Simplify slider is not open 単純化スライダーが開いていません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d7981d59f8..a9fd7ec120 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2343,6 +2343,7 @@ digits Malayalam მალაიალამური File Dimensions ფაილის ზომები Transforms გარდაქმნები Background Color: ფონის ფერი: + Guide Label: დამხმარე ხაზების იარლიყი: Show Center Mark ცენტრის ნიშნის ჩვენება Show Cross Hairs ჯვარედინი ხაზების ჩვენება Show Video Safe Areas ვიდეოს უსაფრთხო არეების ჩვენება @@ -4042,6 +4043,7 @@ font-technology Variable ცვლადი @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis უნდა იყოს "vertical", "horizontal" ან კუთხე გრადუსებში და არა `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" ფონი {other}: transparent, white, black ან ფერი, მაგალითად "#ff8800" @msg bad color {v} არასწორი ფერი {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` არის null, ფენის ფერის სახელი ან #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio უნდა იყოს რიცხვი 0,1-დან 10-მდე @msg bad colour `{hex}` (#rrggbb) არასწორი ფერი `{hex}` (#rrggbb) @msg bad page tree გვერდების არასწორი ხე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a25ffe1814..c7530e505f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1067,6 +1067,7 @@ antiAlias Sharp 날카롭게 Average 평균 BLANK DOCUMENT PRESETS 빈 문서 프리셋 Background Color: 배경색: + Guide Label: 안내선 레이블: Show Center Mark 중심 표시 보기 Show Cross Hairs 십자선 보기 Show Video Safe Areas 비디오 안전 영역 보기 @@ -4611,6 +4612,7 @@ theme Appearance 외관 @msg {label}… {label}… @msg no blend options 혼합 옵션이 없습니다 @msg bad color {v} 잘못된 색상 {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel`은 null, 레이어 색상 이름 또는 #rrggbb입니다 @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio은(는) 0.1에서 10 사이의 숫자여야 합니다 @msg the Color Picker is not open 색상 피커가 열려 있지 않습니다 @msg the Simplify slider is not open 단순화 슬라이더가 열려 있지 않습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3d3cc43619..40c9ce61c8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2456,6 +2456,7 @@ digits Malayalam Malayalam File Dimensions Bestandsafmetingen Transforms Transformaties Background Color: Achtergrondkleur: + Guide Label: Hulplijnlabel: Show Center Mark Middenmarkering tonen Show Cross Hairs Dradenkruis tonen Show Video Safe Areas Veilige videogebieden tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 26fe2d4ac1..16bf528970 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2567,6 +2567,7 @@ digits Malayalam Malajalam File Dimensions Wymiary pliku Transforms Przekształcenia Background Color: Kolor tła: + Guide Label: Etykieta linii pomocniczych: Show Center Mark Pokaż znacznik środka Show Cross Hairs Pokaż krzyż nitkowy Show Video Safe Areas Pokaż bezpieczne obszary wideo @@ -4417,6 +4418,7 @@ imageTrace Outline Kontur @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musi mieć wartość "vertical", "horizontal" lub kąt w stopniach, nie `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tło {other}: transparent, white, black lub kolor, np. "#ff8800" @msg bad color {v} nieprawidłowy kolor {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` to null, nazwa koloru warstwy lub #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musi być liczbą od 0,1 do 10 @msg the Color Picker is not open Próbnik kolorów nie jest otwarty @msg the Simplify slider is not open Suwak Uprość nie jest otwarty diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c4bf2cb43c..1f451c285e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -275,6 +275,7 @@ antiAlias Sharp Nítido Average… Média… BLANK DOCUMENT PRESETS PREDEFINIDOS DE DOCUMENTO EM BRANCO Background Color: Cor do Plano de Fundo: + Guide Label: Rótulo das Guias: Show Center Mark Mostrar Marca Central Show Cross Hairs Mostrar Linhas Cruzadas Show Video Safe Areas Mostrar Áreas Seguras de Vídeo @@ -3841,6 +3842,7 @@ axis Both Ambos @msg at this scale the drawing is {w} × {h} pt, more than the canvas holds: choose a smaller scale or fit it to the artboard nesta escala o desenho tem {w} × {h} pt, mais do que a tela comporta: escolha uma escala menor ou ajuste-o à prancheta @msg background {other}: transparent, white, black or a colour such as "#ff8800" plano de fundo {other}: transparent, white, black ou uma cor como "#ff8800" @msg bad color {v} cor inválida {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` é null, o nome de uma cor de camada ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve ser um número de 0,1 a 10 @msg bad colour `{hex}` (#rrggbb) cor inválida `{hex}` (#rrggbb) @msg bad page tree árvore de páginas inválida diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 877699ff3a..c413cf8602 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -287,6 +287,7 @@ font-technology Variable Вариативные Average… Усреднить… Axis: Ось: Background Color: Цвет фона: + Guide Label: Метка направляющих: Show Center Mark Показать центральную метку Show Cross Hairs Показать перекрестие Show Video Safe Areas Показать безопасные зоны видео @@ -4322,6 +4323,7 @@ axis Both Оба @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis должно быть "vertical", "horizontal" или углом в градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black или цвет, например "#ff8800" @msg bad color {v} недопустимый цвет {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` должен быть null, именем цвета слоя или #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio должно быть числом от 0,1 до 10 @msg the Color Picker is not open палитра цветов не открыта @msg the Simplify slider is not open ползунок «Упростить» не открыт diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9eebd4e53b..81731310ea 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -278,6 +278,7 @@ font-technology Variable Variabla Average… Medelvärde… Axis: Axel: Background Color: Bakgrundsfärg: + Guide Label: Stödlinjeetikett: Show Center Mark Visa mittmarkering Show Cross Hairs Visa hårkors Show Video Safe Areas Visa videosäkra områden @@ -4194,6 +4195,7 @@ axis Both Båda @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis måste vara "vertical", "horizontal" eller en vinkel i grader, inte `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black eller en färg som "#ff8800" @msg bad color {v} ogiltig färg {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` är null, namnet på en lagerfärg eller #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio måste vara ett tal från 0,1 till 10 @msg bad colour `{hex}` (#rrggbb) ogiltig färg `{hex}` (#rrggbb) @msg bad page tree ogiltigt sidträd diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 76ffbabccf..62e27ac6d8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -274,6 +274,7 @@ font-technology Variable Değişken Average… Ortalama… Axis: Eksen: Background Color: Arka Plan Rengi: + Guide Label: Kılavuz Etiketi: Show Center Mark Merkez İşaretini Göster Show Cross Hairs Artı Çizgilerini Göster Show Video Safe Areas Video Güvenli Alanlarını Göster @@ -4050,6 +4051,7 @@ axis Both Her İkisi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{v}` değil @msg background {other}: transparent, white, black or a colour such as "#ff8800" arka plan {other}: şeffaf, beyaz, siyah veya "#ff8800" gibi bir renk @msg bad color {v} kötü renk {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, bir katman renginin adı veya #rrggbb olur @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 0,1 ile 10 arasında bir sayı olmalıdır @msg the Color Picker is not open Renk Seçici açık değil @msg the screen color sampler is already open ekran rengi örnekleyici zaten açık diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 89c45d553b..5905e24190 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -283,6 +283,7 @@ font-technology Variable Варіативні Average… Усереднити… Axis: Вісь: Background Color: Колір тла: + Guide Label: Мітка напрямних: Show Center Mark Показати центральну позначку Show Cross Hairs Показати перехрестя Show Video Safe Areas Показати безпечні зони відео @@ -4312,6 +4313,7 @@ axis Both Обидві @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis має бути "vertical", "horizontal" або кутом у градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black або колір, наприклад "#ff8800" @msg bad color {v} неприпустимий колір {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` має бути null, назвою кольору шару або #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio має бути числом від 0,1 до 10 @msg the Color Picker is not open палітра кольорів не відкрита @msg the Simplify slider is not open повзунок «Спростити» не відкрито diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b1c43edf35..fcd635b794 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -312,6 +312,7 @@ font-technology Variable Biến thiên Axis: Trục: Back Sau Background Color: Màu nền: + Guide Label: Nhãn đường căn: Show Center Mark Hiện dấu tâm Show Cross Hairs Hiện đường chữ thập Show Video Safe Areas Hiện vùng an toàn video @@ -4482,6 +4483,7 @@ theme Appearance Giao diện @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis phải là "vertical", "horizontal" hoặc góc theo độ, không phải `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black hoặc màu như "#ff8800" @msg bad color {v} màu không hợp lệ {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` là null, tên một màu lớp hoặc #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio phải là một số từ 0,1 đến 10 @msg the Color Picker is not open Bộ chọn màu chưa được mở @msg the Simplify slider is not open Thanh trượt Đơn giản hóa chưa được mở diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a587ad15fa..c6936442e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -235,6 +235,7 @@ antiAlias Sharp 锐利 Average… 平均… Axis: 轴: Background Color: 背景颜色: + Guide Label: 参考线标签: Show Center Mark 显示中心标记 Show Cross Hairs 显示十字线 Show Video Safe Areas 显示视频安全区域 @@ -4396,6 +4397,7 @@ imageTrace Outline 轮廓 @msg {label}… {label}… @msg no blend options 没有混合选项 @msg bad color {v} 颜色 {v} 无效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 应为 null、图层颜色名称或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必须是 0.1 到 10 之间的数字 @msg the Color Picker is not open 拾色器未打开 @msg the Simplify slider is not open 简化滑块未打开 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e727056656..91b3a6f50b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -248,6 +248,7 @@ font-technology Variable 可變 Average… 平均… Axis: 軸: Background Color: 背景顏色: + Guide Label: 參考線標籤: Show Center Mark 顯示中心標記 Show Cross Hairs 顯示十字線 Show Video Safe Areas 顯示視訊安全區域 @@ -2224,6 +2225,7 @@ file-filter Templates 範本 @msg {label}… {label}… @msg no blend options 沒有漸變選項 @msg bad color {v} 顏色 {v} 無效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 應為 null、圖層顏色名稱或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必須是 0.1 到 10 之間的數字 @msg the Color Picker is not open 「顏色選擇器」未開啟 @msg the Simplify slider is not open 「簡化」滑桿未開啟 diff --git a/docs/mcp.md b/docs/mcp.md index 8363b44b75..ce4969fdf9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4786,7 +4786,7 @@ value: true}`; the Control bar's and Properties' Scale Artwork with Artboard che Artboard) makes its handle drags proportional and passes `scaleArt`, as do Properties' and the Transform panel's artboard size fields while the tool is in use. -`artboard.setProps {artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several +`artboard.setProps {artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are @@ -4920,6 +4920,20 @@ is the width of one video pixel over its height, which `view.videoRulers` counts the native format keep both (written only when on or not 1), and `inspect_document` adds `showVideoSafeAreas: true` and `videoRulerPixelAspectRatio` to an artboard that has them. +Artboard Options' Guide Label: `artboard.setProps {index, guideLabel?: name | "#rrggbb" | null}` (or each entry of +`artboards`) gives the artboard a guide label, and `artboard.new` takes one too. The canvas draws the artboard's own +guides (`guide.add {artboard}`) in the label's color instead of the guide color preference, in the preference's style; +canvas guides, guides of an artboard without a label and guides whose artboard is gone keep the preference's color, and +selected guides are still drawn in the selection color. The value is a layer color's name, spelled exactly as Layer +Options lists it (`"Light Blue"`, `"Red"`, …), or `#rrggbb`; null clears it, and new artboards and older files have none. +The label is VectorCraft's own (no public documentation describes one): it is screen-only, so exports and print leave +it out, the paper and the artboard's background color stay as they are, and a locked artboard's label can change. +Anything else (a preset's index, another letter case, `#rrggbbaa`) is refused with "`guideLabel` is null, a layer +color's name or #rrggbb", and a list with a bad value anywhere changes nothing. Duplicates and copies keep it, the +native format writes it only when set (a preset index past the layer colors opens as none), and `inspect_document` adds +`guideLabel` (the name or `#rrggbb`) to an artboard that has one. `artboard.setProps` adds no undo step when nothing it +is given differs from the artboard. + Artboard Options' Global checkboxes are application preferences, not artboard properties: `fadeRegionOutsideArtboard` (Fade Region Outside Artboard) and `artboardUpdateWhileDragging` (Update While Dragging), both on by default (`prefs.set {values: {fadeRegionOutsideArtboard: false}}`; also Edit › Preferences › General › Artboard Options). With diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c15e19cda6..1710909377 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -651,6 +651,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). +- **Artboard guide labels (#6414, in part):** Artboard Options' Guide Label gives an artboard a color label (`artboard.setProps`/`artboard.new` `guideLabel`: a layer color's name, `#rrggbb` or null), and the canvas draws that artboard's own guides in it; canvas guides, guides of an unlabeled artboard and guides whose artboard is gone keep the guide color preference, and selected guides keep the selection color. The [help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) describes guides restricted to an artboard, not a label, so the label, its palette and the color precedence are VectorCraft's own. It is screen-only (exports and print leave it out), written to the native format only when set, kept by duplicates and copies, and changeable on a locked artboard; `artboard.setProps` adds no undo step when nothing changes. This VectorCraft addition does not raise a score. Regression tests: `tests/panelcmds.rs` (`artboard_guide_labels_are_set_and_cleared_in_one_undo_step`, `artboard_guide_labels_round_trip_through_the_native_format`), `doc` `tests.rs` (`guide_label_text_names_a_layer_color_or_rgb`, `artboard_guide_label_defaults_and_skips_in_json`), `canvas::tests` (`artboard_guide_label_colors_only_its_own_guides`), `dialogs/tests.rs` (`artboard_options_shows_sets_and_clears_the_guide_label`). - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. From 8002598d64a31b1fbcbc0bb46b7fbcd11a1e6859 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:42:29 -0800 Subject: [PATCH 12/83] Native files: open reads the PDF preference in the same pass as the document Opening a native file read its JSON twice: once for the document and once more for the saved pdfCompatible preference. The format crate now takes the preference from craft-vectorcraft-format's Contents::read_with_pdf_preference (craft-libs#562), so a file is read in one pass. That method refuses a pdfCompatible that is not a boolean, which main opens by skipping the value and falling back to whether the file carries a PDF. Such a file, or one with any other data error, is read again with Contents::read and scanned for the preference as before, so the files that open today still open with the same result. The craft-vectorcraft-format pin moves to 1b34eba41e, the craft-libs revision craft-update already uses. --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/format/src/lib.rs | 60 +++++++++++++++++++++++++++++++++++----- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b77485ae02..c3a087e845 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "flate2", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9b4b99c92d..2d53acdc39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } # internal diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 5d7aabd077..1da653311a 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -510,20 +510,32 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // at `MAX_READ_ANCHORS` anchors together, the document at `MAX_READ_NODES` objects, and the // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the // PDF are skipped without being kept. - let read = || { - vectorcraft_doc::node::with_node_budget(max_nodes, || { - vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) + fn within_budgets(max_nodes: usize, max_values: usize, read: impl FnOnce() -> T) -> T { + vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, || { + vectorcraft_doc::node::with_node_budget(max_nodes, || vectorcraft_doc::node::with_buffered_value_budget(max_values, read)) }) - }; - let mut f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + } + let read_error = |e| match e { ReadError::Json(e) => { let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; FormatError::NotVectorcraft(why) } ReadError::Envelope(e) => e.into(), e => FormatError::NotVectorcraft(e.to_string()), - })?; - let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + }; + // The document and the saved PDF preference come from one pass over the JSON. + let (mut f, pdf_compatible) = match within_budgets(max_nodes, max_values, || Contents::::read_with_pdf_preference(file.json())) { + Ok(read) => read, + // That pass refuses a `pdfCompatible` that is not a boolean, and any other data error. + // The file is read again without the preference, and only then is its JSON scanned for + // the preference a second time, so such a file opens as before. + Err(ReadError::Json(e)) if e.is_data() => { + let f = within_budgets(max_nodes, max_values, || Contents::::read(file.json())).map_err(read_error)?; + let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + (f, pdf_compatible) + } + Err(e) => return Err(read_error(e)), + }; let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION, pdf_compatible }; // A version 1 document saved before VectorCraft 0.21.0, or for an app before it (an older file // version): its Twist angles turned the other way. The app that wrote it is read from the JSON @@ -615,9 +627,17 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result Ok(NativeFile { doc, depth_notes, info, profiles }) } +#[cfg(test)] +thread_local! { + /// Tests: how many times a file's JSON was scanned again for its PDF preference on this thread. + static PDF_MEMBER_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The saved PDF preference, falling back to the presence of its payload without retaining or /// decoding it. The array form has neither member. Repeated members use their last value. fn pdf_member(json: &[u8]) -> Result { + #[cfg(test)] + PDF_MEMBER_SCANS.with(|n| n.set(n.get() + 1)); struct PdfMember; impl<'de> Visitor<'de> for PdfMember { type Value = bool; @@ -801,6 +821,32 @@ mod tests { } } + #[test] + fn only_a_preference_that_is_not_a_boolean_scans_the_json_again() { + let scans_for = |bytes: &[u8]| { + PDF_MEMBER_SCANS.with(|n| n.set(0)); + let compatible = load_info(bytes).unwrap().1.pdf_compatible; + (compatible, PDF_MEMBER_SCANS.with(|n| n.get())) + }; + let d = Document::new(10.0, 10.0); + assert_eq!(scans_for(&save(&d, false)), (false, 0)); + assert_eq!(scans_for(&save(&d, true)), (false, 0)); + for compatible in [false, true] { + let bytes = save_with(&d, &SaveOptions { pdf_compatible: Some(compatible), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&bytes), (compatible, 0)); + } + let with_pdf = save_with(&d, &SaveOptions { pdf: Some(vec![7; 1024]), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&with_pdf), (true, 0)); + let mut value: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + for odd in [serde_json::json!("yes"), serde_json::json!(1), serde_json::json!([true])] { + value["pdfCompatible"] = odd.clone(); + assert_eq!(scans_for(&serde_json::to_vec(&value).unwrap()), (false, 1), "{odd}"); + } + // A document that can't be read still fails, after the second read. + value["document"] = serde_json::json!("not a document"); + assert!(load_info(&serde_json::to_vec(&value).unwrap()).is_err()); + } + #[test] fn file_info_keeps_the_pdf_preference_without_artboards() { let mut d = Document::new(10.0, 10.0); From 2faadd28f4b06f4b2a10a92c6fceb3c2a9893fab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 20:09:28 -0800 Subject: [PATCH 13/83] Symbols: Break Link keeps a hidden or locked instance's art hidden or locked Break Link to Symbol on a selected group, and Delete Symbol with its instances expanded, turned a hidden or locked instance into visible, unlocked art. The art now keeps the instance's hidden and locked state, as Object > Expand does, and Break Link leaves hidden or locked art out of the selection. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 13 ++++--- crates/engine/src/tests/brushsym.rs | 47 +++++++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 13b6ab8814..85c1412f0c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}", has_selection, symbol_break_link ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 60353921e4..ee4487ba72 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -390,9 +390,9 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { most.saturating_add(1).saturating_add(mask) } -/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the -/// art's ids. Fails before any edit when the instances together would make more than -/// [`MAX_EXPAND_NODES`] objects. +/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). A hidden or +/// locked instance's art stays hidden or locked. Returns the art's ids. Fails before any edit when +/// the instances together would make more than [`MAX_EXPAND_NODES`] objects. fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own))); if total > MAX_EXPAND_NODES as u64 { @@ -401,8 +401,10 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result Result { } let out = s.edit("Break Link to Symbol", |d, sel| { let out = break_links(d, &ids, true)?; - sel.set(out.iter().copied()); + // Hidden or locked art is left out of the selection. + sel.set(out.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked))); Ok(out) })?; Ok(json!({ "ids": ids_json(&out) })) diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 638b7a1f4b..34f2cc4b0b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1321,6 +1321,53 @@ fn break_link_counts_the_instances_mask_art() { assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance"); } +/// A hidden, a locked and a plain instance of one symbol in a group, the group selected. +fn group_with_hidden_and_locked_instances(s: &mut Session) -> (NodeId, String) { + let (shown, name, _) = make_symbol(s); + let hidden = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); + let locked = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 100})).unwrap()["id"].as_u64().unwrap()); + select(s, &[shown, hidden, locked]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(hidden).unwrap().visible = false; + doc.node_mut(locked).unwrap().locked = true; + select(s, &[group]); + (group, name) +} + +/// The visibility and lock state of the children of `group`, in paint order. +fn shown_and_locked(s: &Session, group: NodeId) -> Vec<(bool, bool)> { + let g = node(s, group); + let NodeKind::Group { children, .. } = &g.kind else { panic!("a group: {}", g.kind_label()) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::SymbolInstance { .. })), "every instance is expanded"); + children.iter().map(|c| (c.visible, c.locked)).collect() +} + +/// Break Link to Symbol on a selected group keeps a hidden instance's art hidden and a locked +/// instance's art locked, and selects only the art that can be selected. +#[test] +fn break_link_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, _) = group_with_hidden_and_locked_instances(&mut s); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}"); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); + let d = &s.doc().unwrap().doc; + let selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(selected.len(), 1, "{selected:?}"); + assert!(selected.iter().all(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked)), "{selected:?}"); +} + +/// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked +/// instance's art locked. +#[test] +fn delete_symbol_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, name) = group_with_hidden_and_locked_instances(&mut s); + s.execute("symbol.delete", &json!({"name": name})).unwrap(); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); +} + #[test] fn delete_duplicate_and_replace_symbols() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 14a5bfb6cf..749ddb2661 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2014,7 +2014,8 @@ already walks Image Trace. Short agent entry points: a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask), `symbol.replace`, + `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask; a hidden or locked instance's + art stays hidden or locked and is not selected), `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the From aaf27e1ec6129cfc73ed364cd4900c33833a1ebc Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:57:54 +0100 Subject: [PATCH 14/83] Keep blank value row in single-column graph CSV round trip Found while testing crates/engine/src/cmd/graph/data.rs:51 (parse_csv); written by crates/doc/src/graph.rs:497 (GraphSpec::to_csv) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/graph.rs | 4 +++- crates/engine/src/cmd/graph/data.rs | 4 ++++ crates/engine/src/cmd/graph/tests.rs | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 15f04ce156..72b066a06e 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -525,7 +525,9 @@ impl GraphSpec { out.push_str(&field(self.categories.get(i).map(String::as_str).unwrap_or_default(), true)); out.push(','); } - out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::>().join(",")); + let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::>().join(","); + // A lone blank value would be an empty line, which readers skip; a quoted empty field keeps the row. + out.push_str(if line.is_empty() && !labelled { "\"\"" } else { &line }); out.push('\n'); } out diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 3e21223497..f4eb3ef83c 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -50,6 +50,10 @@ pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec 1 { tabs } else { split_unquoted(l, ',') }; parts.into_iter().map(cell).collect() diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 650a4275ab..6cb36431e4 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4210,3 +4210,12 @@ fn character_formats_are_kept_and_bigger_labels_space_out() { fn csv_leading_byte_order_mark_is_ignored() { assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4")); } + +#[test] +fn csv_round_trip_keeps_blank_row_in_single_column_graph() { + let mut g = GraphSpec::default(); + g.set_cells(vec![vec![Some(1.0)], vec![None], vec![Some(3.0)]]); + let (_, c, r) = super::parse_csv(&g.to_csv()); + assert!(c.is_empty()); + assert_eq!(r, g.cells()); +} From bd396744696e49e924284174e29b08fd7956eff6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:29:51 -0800 Subject: [PATCH 15/83] Reshape: a click sets a focal point and a drag moves every focal point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A click with the Reshape tool on an anchor of a selected path makes it the focal point, and a click on a segment adds an anchor there that becomes the focal point. Shift-click adds an anchor or a point on a segment to the focal points, or removes an anchor that is one already. Each focal point shows a filled anchor square in a larger hollow one. A drag from a focal point moves all of them; a drag from another point moves that point alone, and Shift only keeps the drag's angle. path.reshape takes the other focal points as focal: [[subpath, anchor]...]. Anchors that are not direct-selected stay in place, and so do the ends of an open path unless they are focal points. A selected anchor between two focal points moves by the whole drag, and one between a focal point and an anchor that stays takes u² (3 - 2u) of the drag, as before. A closed subpath with every anchor selected moves whole: a Reshape drag on a fully selected closed path, and path.reshape without radius on a closed path selected whole or not selected, move the whole path instead of a local area. With radius, only the grabbed point's subpath changes, with the falloff as before. - An anchor added on a segment of a partly selected path is selected, and the selected anchors and segments after it keep their points. - A focal pair that names no anchor is refused ("`focal` names [0, 7], which is not an anchor of the path"), and so is focal with radius. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/path.rs | 243 ++++++++++++++++------ crates/engine/src/tests.rs | 375 +++++++++++++++++++++++++++++++++- crates/tools/src/extra.rs | 218 +++++++++++++++++--- docs/mcp.md | 41 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 776 insertions(+), 103 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 9b753a3953..e249a23fcc 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -131,7 +131,7 @@ pub fn specs() -> Vec { "Reshape", [], None, - "{id, x, y, dx, dy, tol=3, radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). An open path stretches from the grabbed point to its two ends, which stay in place: each anchor between takes a share of the drag that falls smoothly from 1 at the grabbed point to 0 at the end, by its distance along the path's control polygon. On a closed path, or when radius is given, nearby anchors follow with a smooth falloff over radius, measured along the path (0 or more; default: half the diagonal of the subpath's bounding box)", + "{id, x, y, dx, dy, tol=3, focal?: [[subpath, anchor]…], radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). The grabbed anchor and the anchors in focal are focal points and move by the whole drag. Anchors that are not direct-selected stay in place (a path selected whole, or not selected, has every anchor selected), and so do an open path's two ends unless they are focal points. A selected anchor between two focal points moves whole; one between a focal point and an anchor that stays takes a share of the drag that falls smoothly from 1 at the focal point to 0 at the anchor that stays, by its distance along the path's control polygon. A closed subpath with every anchor selected moves whole; a subpath with no focal point does not move. With radius, only the grabbed point's subpath changes: anchors follow with a smooth falloff over radius, measured along the path (0 or more), whatever the selection; focal and radius cannot be used together", has_doc, reshape ), @@ -1410,55 +1410,143 @@ fn open_run(mut anchors: Vec) -> Option { Some(SubPath::new(anchors, false)) } -/// The share of a Reshape drag that each anchor of an open subpath takes, as `[in handle, anchor, -/// out handle]`. The grabbed anchor takes all of it and the two end anchors take none. For an -/// anchor between the grabbed one and an end, `u` is its distance from that end along the control -/// polygon (anchor, out handle, the next in handle, the next anchor) divided by the grabbed -/// anchor's distance from that end, and its share is `u² (3 - 2u)`. A handle takes the share on -/// the tangent line of that curve at its anchor, so the two handles of a smooth anchor stay in -/// line with it. That share is below 0 or above 1 for a handle long enough beside the span. -fn stretch_weights(anchors: &[Anchor], grabbed: usize) -> Vec<[f64; 3]> { - let last = anchors.len().saturating_sub(1); +/// What an anchor does in a Reshape drag. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Stretch { + /// Not selected: it stays in place. + Fixed, + /// Selected: it takes a share of the drag that depends on where it lies between the anchors + /// that stay and the focal points. + Selected, + /// A focal point (the grabbed anchor, or one the Reshape tool highlighted): it moves by the + /// whole drag. + Focal, +} + +/// The share of a Reshape drag that each anchor of a subpath takes, as `[in handle, anchor, out +/// handle]`, from what each anchor does (`roles`, one per anchor). A focal point takes all of the +/// drag and an anchor that stays takes none. An open path's end anchors stay unless they are focal +/// points. A selected anchor between two focal points takes all of the drag, and one between two +/// anchors that stay takes none. For a selected anchor between an anchor that stays and a focal +/// point, `u` is its distance from the anchor that stays along the control polygon (anchor, out +/// handle, the next in handle, the next anchor) divided by the focal point's distance from it, and +/// its share is `u² (3 - 2u)`. A handle takes the share on the tangent line of that curve at its +/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or +/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays +/// moves whole when it has a focal point. +fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> { + let n = anchors.len(); + let mut shares = vec![[0.0; 3]; n]; + let role = |i: usize| match roles.get(i) { + Some(Stretch::Selected) if !closed && (i == 0 || i + 1 == n) => Stretch::Fixed, + Some(&r) => r, + None => Stretch::Fixed, + }; + // The walk along the subpath starts at an anchor that stays, or else at a focal point, and on a + // closed subpath it comes back round to the same anchor, so every selected anchor lies between + // two anchors that are not selected ones. + let start = if closed { (0..n).find(|&i| role(i) == Stretch::Fixed).or_else(|| (0..n).find(|&i| role(i) == Stretch::Focal)) } else { Some(0) }; + let Some(start) = start.filter(|_| n > 0) else { return shares }; + let len = if closed { n + 1 } else { n }; + let order: Vec = (0..len).map(|k| (start + k) % n).collect(); // Where each anchor's in handle, point and out handle lie along the control polygon. The in // handle of the first anchor and the out handle of the last are not part of an open path. - let mut pos: Vec<[f64; 3]> = Vec::with_capacity(anchors.len()); + let mut pos: Vec<[f64; 3]> = Vec::with_capacity(len); let mut run = 0.0; - for (i, a) in anchors.iter().enumerate() { - if let Some(before) = i.checked_sub(1).and_then(|b| anchors.get(b)) { - run += before.h_out.distance(a.h_in); + let mut before: Option<&Anchor> = None; + for (k, a) in order.iter().filter_map(|&i| anchors.get(i)).enumerate() { + if let Some(b) = before { + run += b.h_out.distance(a.h_in); } let c_in = run; - if i > 0 { + if k > 0 { run += a.h_in.distance(a.p); } let c = run; - if i < last { + if k + 1 < len { run += a.p.distance(a.h_out); } pos.push([c_in, c, run]); + before = Some(a); } - let at = pos.get(grabbed).map_or(0.0, |c| c[1]); - let length = pos.last().map_or(0.0, |c| c[1]); - pos.iter() - .enumerate() - .map(|(i, &[c_in, c, c_out])| { - if i == grabbed { - return [1.0; 3]; + // The nearest anchor before and after each place in the walk that is not a selected one. + let bound = |k: usize| role(order.get(k).copied().unwrap_or(start)) != Stretch::Selected; + let mut previous = vec![0; len]; + let mut last = 0; + for (k, slot) in previous.iter_mut().enumerate() { + if bound(k) { + last = k; + } + *slot = last; + } + let mut next = vec![len - 1; len]; + let mut first = len - 1; + for (k, slot) in next.iter_mut().enumerate().rev() { + if bound(k) { + first = k; + } + *slot = first; + } + let at = |k: usize| pos.get(k).map_or(0.0, |c| c[1]); + // The share of the anchor at `k` in the walk, between an anchor that stays at `end` and a + // focal point at `focal` along the walk. + let smooth = |k: usize, end: f64, focal: f64| { + let span = (focal - end).abs(); + let Some(&[c_in, c, c_out]) = pos.get(k).filter(|_| span > 0.0 && span.is_finite()) else { return [0.0; 3] }; + let along = |c: f64| (c - end).abs() / span; + let u = along(c); + let w = u * u * (3.0 - 2.0 * u); + let slope = 6.0 * u * (1.0 - u); + [w + slope * (along(c_in) - u), w, w + slope * (along(c_out) - u)] + }; + for (k, &i) in order.iter().enumerate().take(n) { + let share = match role(i) { + Stretch::Fixed => [0.0; 3], + Stretch::Focal => [1.0; 3], + Stretch::Selected => { + let (kp, kn) = (previous.get(k).copied().unwrap_or(k), next.get(k).copied().unwrap_or(k)); + match (role(order.get(kp).copied().unwrap_or(i)), role(order.get(kn).copied().unwrap_or(i))) { + (Stretch::Focal, Stretch::Focal) => [1.0; 3], + (Stretch::Fixed, Stretch::Focal) => smooth(k, at(kp), at(kn)), + (Stretch::Focal, Stretch::Fixed) => smooth(k, at(kn), at(kp)), + _ => [0.0; 3], + } } - let end = if i < grabbed { 0.0 } else { length }; - let span = (at - end).abs(); - if i == 0 || i == last || span <= 0.0 || !span.is_finite() { - return [0.0; 3]; - } - let along = |c: f64| (c - end).abs() / span; - let u = along(c); - let w = u * u * (3.0 - 2.0 * u); - let slope = 6.0 * u * (1.0 - u); - let shares = [w + slope * (along(c_in) - u), w, w + slope * (along(c_out) - u)]; - // A coordinate that isn't finite moves nothing. - if shares.iter().all(|s| s.is_finite()) { shares } else { [0.0; 3] } - }) - .collect() + }; + // A coordinate that isn't finite moves nothing. + if let Some(s) = shares.get_mut(i) + && share.iter().all(|s| s.is_finite()) + { + *s = share; + } + } + shares +} + +/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and +/// selected segments after it on that subpath one higher, so the selection keeps the same points. +/// A selected segment that the new anchor splits stays selected as its two halves, and the new +/// anchor joins its ends in the anchors that move with it. +fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { + if let Some(set) = sel.anchors.get_mut(&id) { + // A selected anchor index can name no anchor (`select.anchors` takes any index), so the + // renumbering saturates instead of overflowing. + *set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect(); + } + let split = added.checked_sub(1); + if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) { + sel.anchors.entry(id).or_default().insert((si, added)); + } + if let Some(set) = sel.segments.get_mut(&id) { + *set = set + .iter() + .flat_map(|&(s, g)| match (s == si, Some(g) == split) { + (true, true) => vec![(s, g), (s, g.saturating_add(1))], + (true, false) if g >= added => vec![(s, g.saturating_add(1))], + _ => vec![(s, g)], + }) + .collect(); + } } fn reshape(s: &mut Session, p: &Value) -> Result { @@ -1476,45 +1564,78 @@ fn reshape(s: &mut Session, p: &Value) -> Result { Some((i, dist)) if dist <= tol => Some(i), _ => None, }; - // A drag of no length on an anchor moves nothing, so it is not an edit. - if delta == Vec2::ZERO { + // The other focal points the Reshape tool highlighted on this path. + let mut focal: BTreeSet<(usize, usize)> = match p.get("focal") { + None | Some(Value::Null) => BTreeSet::new(), + Some(v) if v.is_array() => super::select::checked_refs(Some(v), "path.reshape")?.into_iter().collect(), + Some(_) => return Err(bad("path.reshape", "`focal` must be an array of [subpath, anchor] pairs")), + }; + if radius.is_some() && !focal.is_empty() { + return Err(bad("path.reshape", "`focal` and `radius` cannot be used together")); + } + { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let path = node.path_data().ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?; - let (si, ..) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?; - if path.subpaths.get(si).is_some_and(|sp| near(sp).is_some()) { - return ok(); + if let Some((si, ai)) = focal.iter().copied().find(|&(si, ai)| path.subpaths.get(si).is_none_or(|sp| ai >= sp.anchors.len())) { + return Err(bad("path.reshape", format!("`focal` names [{si}, {ai}], which is not an anchor of the path"))); + } + // A drag of no length on an anchor moves nothing, so it is not an edit. + if delta == Vec2::ZERO { + let (si, ..) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?; + if path.subpaths.get(si).is_some_and(|sp| near(sp).is_some()) { + return ok(); + } } } - s.edit("Reshape", |d, _| { + s.edit("Reshape", |d, sel| { let path = path_mut(d, id)?; let (si, seg, t, _, _) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?; - let sp = &mut path.subpaths[si]; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?; let grabbed = match near(sp) { Some(i) => i, - None => sp.insert_anchor(seg, t), + None => { + let added = sp.insert_anchor(seg, t); + focal = focal.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect(); + renumber_after_insert(sel, id, si, added); + // On a partly selected path the new anchor is selected too. + if let Some(set) = sel.anchors.get_mut(&id) { + set.insert((si, added)); + } + added + } }; - let closed = sp.closed; - if radius.is_none() && !closed { - let weights = stretch_weights(&sp.anchors, grabbed); - for (a, [w_in, w, w_out]) in sp.anchors.iter_mut().zip(weights) { - a.p += delta * w; - a.h_in += delta * w_in; - a.h_out += delta * w_out; + let Some(r) = radius else { + focal.insert((si, grabbed)); + // Anchors that are not direct-selected stay; a path selected whole, or not selected, + // has every anchor selected. + let selected = sel.anchors.get(&id); + for (k, sp) in path.subpaths.iter_mut().enumerate() { + if focal.range((k, 0)..=(k, usize::MAX)).next().is_none() { + continue; + } + let roles: Vec = (0..sp.anchors.len()) + .map(|i| match (focal.contains(&(k, i)), selected.is_none_or(|set| set.contains(&(k, i)))) { + (true, _) => Stretch::Focal, + (false, true) => Stretch::Selected, + (false, false) => Stretch::Fixed, + }) + .collect(); + let weights = stretch_weights(&sp.anchors, sp.closed, &roles); + for (a, [w_in, w, w_out]) in sp.anchors.iter_mut().zip(weights) { + a.p += delta * w; + a.h_in += delta * w_in; + a.h_out += delta * w_out; + } } return Ok(()); - } + }; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?; + let closed = sp.closed; // Each anchor's distance along the path from the grabbed one, the shorter way round a // closed path: the lengths are measured once, as a path can have many anchors. let pos = sp.anchor_arc_positions(); let total = pos.last().copied().unwrap_or(0.0); - // The default reach is the subpath's size, as before, now measured along it. - let r = radius.unwrap_or_else(|| { - let mut bp = vectorcraft_geom::BezPath::new(); - sp.to_bezpath_into(&mut bp); - let b = vectorcraft_geom::Shape::bounding_box(&bp); - (b.width().hypot(b.height()) / 2.0).max(1.0) - }); let from = pos.get(grabbed).copied().unwrap_or(0.0); for (i, a) in sp.anchors.iter_mut().enumerate() { let w = if i == grabbed { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 54248ebfd6..6c2fb000c5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3216,8 +3216,9 @@ fn flare_rotation_turns_only_the_rays() { fn reshape_moves_the_grabbed_point_and_its_neighbourhood() { let mut s = session(); let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); - // Grab the middle of the top edge: a new anchor appears there and moves the full delta. - s.execute("path.reshape", &json!({"id": r.0, "x": 50.0, "y": 0.0, "dx": 0.0, "dy": -40.0})).unwrap(); + // Grab the middle of the top edge: a new anchor appears there and moves the full delta. The + // radius, about half the square's diagonal, bounds the reach. + s.execute("path.reshape", &json!({"id": r.0, "x": 50.0, "y": 0.0, "dx": 0.0, "dy": -40.0, "radius": 70.0})).unwrap(); let st = s.doc().unwrap(); let pd = st.doc.node(r).unwrap().path_data().unwrap().clone(); assert_eq!(pd.anchor_count(), 5); @@ -3454,6 +3455,376 @@ fn reshape_by_no_distance_on_an_anchor_records_no_undo_step() { assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); } +/// Seven anchors 70 apart along a line, from x 0 to x 420. +fn reshape_line_of_seven() -> Value { + json!([{"x": 0, "y": 0}, {"x": 70, "y": 0}, {"x": 140, "y": 0}, {"x": 210, "y": 0}, {"x": 280, "y": 0}, {"x": 350, "y": 0}, {"x": 420, "y": 0}]) +} + +#[test] +fn reshape_with_two_focal_points_moves_the_anchors_between_them_whole() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("path.reshape", &json!({"id": id.0, "x": 280.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": [[0, 2]]})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "both focal points and the anchor between them: {y:?}"); + assert_eq!((y[0], y[6]), (0.0, 0.0), "the ends stay: {y:?}"); + // Each side stretches from its own end to its nearer focal point, 140 along the path. + assert!((y[1] - 100.0 * reshape_share(0.5)).abs() < 1e-9 && (y[5] - 100.0 * reshape_share(0.5)).abs() < 1e-9, "{y:?}"); +} + +#[test] +fn reshape_of_a_closed_path_selected_whole_moves_all_of_it() { + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let before = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); + s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 15.0, "dy": -40.0})).unwrap(); + let after = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); + assert_eq!(after.anchor_count(), before.anchor_count(), "a grab on an anchor adds none"); + let drag = vectorcraft_geom::Vec2::new(15.0, -40.0); + for ((_, _, a), (_, _, b)) in after.anchors().zip(before.anchors()) { + assert_eq!((a.p - b.p, a.h_in - b.h_in, a.h_out - b.h_out), (drag, drag, drag), "{after:?}"); + } +} + +#[test] +fn reshape_leaves_the_anchors_that_are_not_selected_in_place() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[1], y[5], y[6]), (0.0, 0.0, 100.0, 0.0), "{y:?}"); + // The stretch runs from the last anchor that is not selected, 280 from the focal point. + for i in 2..5 { + let u = (i as f64 - 1.0) / 4.0; + assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}"); + } +} + +#[test] +fn reshape_of_a_partly_selected_closed_path_stretches_between_the_anchors_that_stay() { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 200, "y": 0}, {"x": 200, "y": 100}, {"x": 100, "y": 100}, {"x": 0, "y": 100}], "closed": true}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // Anchors 5, 0, 1 and 2 are selected; 3 and 4 stay. The walk runs 4, 5, 0, 1, 2, 3. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 5], [0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -50.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[3], y[4]), (-50.0, 100.0, 100.0), "{y:?}"); + // From anchor 4 to the focal point is 200: anchor 5 is halfway. From anchor 3 back to it is + // 300: anchor 2 is a third of the way and anchor 1 two thirds. + let want = [(5, 100.0 + -50.0 * reshape_share(0.5)), (2, -50.0 * reshape_share(1.0 / 3.0)), (1, -50.0 * reshape_share(2.0 / 3.0))]; + for (i, w) in want { + assert!((y[i] - w).abs() < 1e-9, "anchor {i}: {y:?}"); + } +} + +#[test] +fn reshape_of_a_segment_keeps_the_selected_anchors_and_selects_the_new_one() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 245.0, "y": 0.0, "dx": 0.0, "dy": 60.0, "focal": [[0, 5]]})).unwrap(); + let a = reshape_anchors(&s, id); + assert_eq!(a.len(), 8, "the grab adds an anchor between 210 and 280"); + let selected: Vec<(usize, usize)> = s.doc().unwrap().selection.partial(id).unwrap().iter().copied().collect(); + assert_eq!(selected, vec![(0, 3), (0, 4), (0, 5), (0, 6)], "the same points stay selected, with the new one"); + // The focal point given before the anchor was added still names the anchor at 350. + let y: Vec = a.iter().map(|a| a.p.y).collect(); + assert_eq!(&y[4..7], &[60.0, 60.0, 60.0], "{y:?}"); + assert_eq!((y[0], y[1], y[2], y[7]), (0.0, 0.0, 0.0, 0.0), "{y:?}"); +} + +#[test] +fn reshape_of_a_segment_with_a_selected_anchor_index_past_the_end_does_not_panic() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + let past = usize::MAX; + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, past]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 105.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap(); + assert_eq!(reshape_anchors(&s, id).len(), 9); +} + +#[test] +fn reshape_of_a_segment_keeps_a_selected_segment_as_its_two_halves() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 0.0})).unwrap(); + let st = s.doc().unwrap(); + let segments: Vec<(usize, usize)> = st.selection.segments[&id].iter().copied().collect(); + assert_eq!(segments, vec![(0, 2), (0, 3), (0, 5)]); + let anchors: Vec<(usize, usize)> = st.selection.partial(id).unwrap().iter().copied().collect(); + assert_eq!(anchors, vec![(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor moves with the segment's ends"); +} + +#[test] +fn reshape_moves_only_the_subpaths_with_a_focal_point() { + let mut s = session(); + let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 40.0})).unwrap(); + let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); + let y: Vec> = pd.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p.y).collect()).collect(); + assert_eq!(y[1], vec![100.0, 100.0, 100.0], "{y:?}"); + assert_eq!((y[0][0], y[0][2]), (0.0, 40.0), "{y:?}"); + // A focal point on the other subpath stretches that one too. + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 40.0, "dx": 0.0, "dy": 10.0, "focal": [[1, 1]]})).unwrap(); + let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); + assert_eq!(pd.subpaths[1].anchors.iter().map(|a| a.p.y).collect::>(), vec![100.0, 110.0, 100.0]); +} + +#[test] +fn reshape_refuses_a_focal_point_that_is_not_an_anchor() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + let before = reshape_anchors(&s, id); + for (focal, want) in [ + (json!([[0, 7]]), "`focal` names [0, 7], which is not an anchor of the path"), + (json!([[1, 0]]), "`focal` names [1, 0], which is not an anchor of the path"), + (json!([[0, -1]]), "invalid anchor index -1"), + (json!({"0": 1}), "`focal` must be an array of [subpath, anchor] pairs"), + ] { + let e = s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal})).unwrap_err(); + assert!(e.to_string().contains(want), "{e}"); + } + assert_eq!(reshape_anchors(&s, id), before); + let steps = s.doc().unwrap().history.undo.len(); + let e = + s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": [[0, 2]], "radius": 50.0})).unwrap_err(); + assert!(e.to_string().contains("`focal` and `radius` cannot be used together"), "{e}"); + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + +/// The line of seven, selected whole, with the Reshape tool picked. +fn reshape_tool_on_a_line(s: &mut Session) -> NodeId { + let id = reshape_open_path(s, reshape_line_of_seven()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.select_tool("reshape", ViewInfo::default()).unwrap(); + id +} + +/// Presses at `a`, drags to `b` unless it is `a` (a click), and releases, with Shift when `shift`. +fn reshape_gesture(s: &mut Session, a: (f64, f64), b: (f64, f64), shift: bool) { + let v = ViewInfo::default(); + let mods = vectorcraft_tools::Mods { shift, ..vectorcraft_tools::Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, a.0, a.1).with_mods(mods), v).unwrap(); + if a != b { + s.pointer(&PointerEvent::new(PointerKind::Drag, b.0, b.1).with_mods(mods), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, b.0, b.1).with_mods(mods), v).unwrap(); +} + +/// Where the Reshape tool draws its highlighted focal points. +fn reshape_highlights(s: &mut Session) -> Vec { + s.overlays(ViewInfo::default()) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Anchor { p, filled: true, .. } => Some(p), + _ => None, + }) + .collect() +} + +#[test] +fn reshape_tool_shift_click_adds_focal_points_that_a_drag_moves_together() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a click on an anchor is not an edit"); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "{y:?}"); + assert!((y[1] - 50.0).abs() < 1e-9 && (y[5] - 50.0).abs() < 1e-9 && y[0] == 0.0 && y[6] == 0.0, "{y:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "the drag is one step"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 100.0), Point::new(280.0, 100.0)], "the focal points stay highlighted"); +} + +#[test] +fn reshape_tool_shift_click_on_a_focal_point_removes_it_and_a_click_starts_again() { + for (clicks, want) in [ + // Shift-click 140 again: only 280 is a focal point. + (vec![(140.0, false), (280.0, true), (140.0, true)], vec![Point::new(280.0, 0.0)]), + // A click without Shift: only 350 is a focal point. + (vec![(140.0, false), (280.0, true), (350.0, false)], vec![Point::new(350.0, 0.0)]), + ] { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + for (x, shift) in clicks { + reshape_gesture(&mut s, (x, 0.0), (x, 0.0), shift); + } + assert_eq!(reshape_highlights(&mut s), want); + let at = (want[0].x, 0.0); + reshape_gesture(&mut s, at, (at.0, 100.0), false); + let full = reshape_anchors(&s, id).iter().filter(|a| a.p.y == 100.0).count(); + assert_eq!(full, 1, "only the dragged focal point moves whole: {:?}", reshape_anchors(&s, id)); + } +} + +#[test] +fn reshape_tool_focal_point_stays_its_anchor_when_another_anchor_moves_onto_it() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // Anchor 2 now lies where the focal point, anchor 4, lies. + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap(); + // A Shift-click adds the last anchor, and a drag from it moves it and anchor 4 whole. + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[4] == 100.0 && y[6] == 100.0 && y[2] < 100.0, "{y:?}"); +} + +#[test] +fn reshape_tool_anchor_added_before_a_focal_point_keeps_it_highlighted() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // A Shift-click on the segment from 70 to 140 adds anchor 2, before the focal point. + reshape_gesture(&mut s, (105.0, 0.0), (105.0, 0.0), true); + assert_eq!(reshape_anchors(&s, id).len(), 8); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(280.0, 0.0), Point::new(105.0, 0.0)]); + // A drag from the added anchor moves both focal points whole. + reshape_gesture(&mut s, (105.0, 0.0), (105.0, 40.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[2] == 40.0 && y[5] == 40.0, "{y:?}"); +} + +#[test] +fn reshape_tool_focal_point_moved_by_another_edit_is_not_passed_to_another_anchor() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // The focal point, anchor 4, moves away, and anchor 2 takes its old place. + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 4, "x": 280.0, "y": 50.0})).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap(); + assert_eq!(reshape_highlights(&mut s), vec![]); + // A Shift-click adds the last anchor, and a drag from it moves it alone as the focal point. + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(420.0, 0.0)]); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[6] == 100.0 && y[2] < 100.0, "{y:?}"); +} + +#[test] +fn reshape_tool_drag_from_an_anchor_that_is_not_highlighted_moves_only_it_whole() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[2] < 100.0 && y[5] == 100.0, "{y:?}"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]); +} + +#[test] +fn reshape_tool_click_on_a_segment_adds_a_highlighted_anchor() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (245.0, 0.0), (245.0, 0.0), true); + assert_eq!(reshape_anchors(&s, id).len(), 8); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "adding the anchor is one step"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(245.0, 0.0)]); + reshape_gesture(&mut s, (245.0, 0.0), (245.0, 60.0), false); + let a = reshape_anchors(&s, id); + assert_eq!((a[2].p.y, a[3].p.y, a[4].p.y), (60.0, 60.0, 60.0), "{a:?}"); + // Undo takes back the drag, then the added anchor. The highlights stay where the drag left + // them, where no anchor is now, so none shows. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(reshape_anchors(&s, id).len(), 7); + assert!(reshape_highlights(&mut s).is_empty()); +} + +#[test] +fn reshape_tool_escape_during_a_drag_keeps_the_path_and_its_focal_points() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let before = reshape_anchors(&s, id); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true); + let v = ViewInfo::default(); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 0.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), v).unwrap(); + assert_ne!(reshape_anchors(&s, id), before, "the preview moves the path"); + s.tool_key(ToolKey::Escape, vectorcraft_tools::Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), v).unwrap(); + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]); +} + +#[test] +fn reshape_tool_shift_drag_from_an_anchor_that_is_not_highlighted_moves_only_it() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + // Shift keeps the drag's angle; the highlighted anchor at 140 does not move whole with it. + reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), true); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[5] == 100.0 && y[2] < 100.0, "{y:?}"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]); +} + +#[test] +fn reshape_tool_click_on_a_curved_segment_highlights_the_anchor_it_adds() { + // Points on the curve from 0 to 300, away from its anchors, each clicked from off it on a + // new copy of the path. + let c = vectorcraft_geom::CubicBez::new(Point::new(0.0, 0.0), Point::new(40.0, -90.0), Point::new(230.0, 110.0), Point::new(300.0, 0.0)); + for k in 1..60 { + let t = 0.05 + 0.015 * f64::from(k); + for off in [(0.3, -0.2), (-2.1, 1.7), (2.6, 2.2)] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [{"x": 0, "y": 0, "out": [40, -90]}, {"x": 300, "y": 0, "in": [230, 110]}, {"x": 600, "y": 0}]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.select_tool("reshape", ViewInfo::default()).unwrap(); + let q = vectorcraft_geom::ParamCurve::eval(&c, t); + reshape_gesture(&mut s, (q.x + off.0, q.y + off.1), (q.x + off.0, q.y + off.1), false); + let a = reshape_anchors(&s, id); + assert_eq!(a.len(), 4, "t {t}, {off:?}"); + assert_eq!(reshape_highlights(&mut s), vec![a[1].p], "t {t}, {off:?}"); + } + } +} + +#[test] +fn reshape_tool_leaves_a_locked_or_hidden_path_alone() { + for command in ["object.lock", "object.hide"] { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let before = reshape_anchors(&s, id); + s.execute(command, &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).ok(); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), false); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 60.0), false); + assert_eq!(reshape_anchors(&s, id), before, "{command}"); + assert!(reshape_highlights(&mut s).is_empty(), "{command}"); + } +} + #[test] fn graph_tool_drag_creates_a_graph_and_asks_for_data() { let mut s = session(); diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 6b496869ea..bcf7d6e655 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -3,9 +3,10 @@ //! Flare: drag sets the center and its size and turns the rays as the pointer moves up or down //! (Shift holds their turn; click without dragging opens the Flare Tool Options), then a click //! sets the end point of the rings; Space held during either drag moves the flare. The rest comes -//! from the tool's options (the Flare Tool Options, which last). Reshape: drag a point of a -//! selected path; the engine's `path.reshape` adds an anchor there if needed and stretches an open -//! path from that point to its two ends, or moves the neighborhood of the point on a closed path. +//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected +//! path sets a focal point (adding an anchor on a segment), Shift-click adds or removes more, and +//! a drag from a focal point moves them all; the engine's `path.reshape` stretches the selected +//! anchors between them and the anchors that stay. use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; @@ -268,27 +269,145 @@ impl Tool for FlareTool { } } -/// Reshape Tool: drag a point on a selected path. +/// Where a Reshape press landed on a selected path. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ReshapeHit { + /// On an anchor: (subpath, anchor). + Anchor(usize, usize), + /// On a segment, away from its anchors: (subpath, the index of the anchor `path.reshape` adds + /// there). + Segment(usize, usize), +} + +impl ReshapeHit { + /// The anchor the press grabs, as `(subpath, anchor)` once any anchor has been added. + fn anchor(self) -> (usize, usize) { + match self { + Self::Anchor(si, ai) | Self::Segment(si, ai) => (si, ai), + } + } + + /// Where the anchor `r` is once the press has added its anchor: one further on after an + /// anchor added before it on its subpath. + fn renumber(self, r: (usize, usize)) -> (usize, usize) { + match self { + Self::Segment(si, added) if r.0 == si && r.1 >= added => (r.0, r.1.saturating_add(1)), + _ => r, + } + } +} + +/// A Reshape press: the path, the point on it, what it landed on and whether Shift was held. +#[derive(Clone, Debug)] +struct ReshapePress { + id: vectorcraft_doc::NodeId, + at: Point, + hit: ReshapeHit, + shift: bool, + /// The drag so far. + d: Vec2, + /// The other focal points the drag moves, found when it starts, before the preview moves them. + others: Vec<((usize, usize), Point)>, +} + +/// How near a focal point's stored position an anchor must be to be that focal point. An anchor +/// added on a segment lies where the curve's point was found, to within rounding. +const FOCAL_MATCH: f64 = 1e-6; + +/// A focal point: its `(subpath, anchor)` and where that anchor lies. +type FocalPoint = ((usize, usize), Point); + +/// Reshape Tool: a click on a selected path makes the anchor or the point on a segment there the +/// focal point (on a segment it adds an anchor), Shift-click adds or removes more, and a drag +/// moves the focal points with the drag and stretches the selected anchors around them. #[derive(Default)] pub struct ReshapeTool { - /// (path, grab point) while dragging. - grab: Option<(vectorcraft_doc::NodeId, Point)>, + /// The press, until the button is released. + press: Option, began: bool, /// Pointer and offset readout while a reshape drag is in progress. measure: Option<(Point, String)>, + /// The focal points the tool highlighted: their path, and each one's `(subpath, anchor)` and + /// where that anchor lies. An anchor the tool adds before one renumbers it. A focal point + /// whose anchor no longer lies there (another edit moved or removed it) shows nothing and + /// moves nothing. + focal: Option<(vectorcraft_doc::NodeId, Vec)>, } impl ReshapeTool { - /// The selected path under `p` (Reshape works on selected paths only, like Illustrator). - fn hit(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, Point)> { + /// The selected path under `p` (Reshape works on selected paths only), the point on it and + /// what the point is. + fn hit(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, Point, ReshapeHit)> { let tol = cx.tol(4.0); - let editable = cx.doc.editable(); - cx.selection.objects.iter().copied().filter(|id| editable(*id)).find_map(|id| { + Self::paths(cx).into_iter().find_map(|id| { let pd = cx.doc.node(id)?.path_data()?; - let (_, _, _, q, d) = pd.nearest(p)?; - (d <= tol).then_some((id, q)) + let (si, seg, _, q, d) = pd.nearest(p)?; + if d > tol { + return None; + } + // `path.reshape` takes the anchor within `tol` of the point on the path. + let anchor = pd + .subpaths + .get(si)? + .anchors + .iter() + .enumerate() + .map(|(i, a)| (i, a.p.distance(q))) + .filter(|&(_, dist)| dist <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)); + Some(match anchor { + Some((ai, _)) => (id, pd.subpaths.get(si)?.anchors.get(ai)?.p, ReshapeHit::Anchor(si, ai)), + // `SubPath::insert_anchor` puts the new anchor after the segment's first anchor. + None => (id, q, ReshapeHit::Segment(si, seg.saturating_add(1))), + }) }) } + + /// The paths Reshape works on: the selected paths that can be edited, in selection order. + fn paths(cx: &ToolContext) -> Vec { + let editable = cx.doc.editable(); + cx.selection.objects.iter().copied().filter(|&id| editable(id) && cx.doc.node(id).is_some_and(|n| n.path_data().is_some())).collect() + } + + /// The highlighted focal points of path `id` as `(subpath, anchor)`, with their positions: the + /// anchors of the path that lie where the tool stored them. None while Reshape does not work + /// on the path. + fn focal_points(&self, cx: &ToolContext, id: vectorcraft_doc::NodeId) -> Vec<((usize, usize), Point)> { + let Some((fid, points)) = &self.focal else { return vec![] }; + if *fid != id || !Self::paths(cx).contains(&id) { + return vec![]; + } + let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { return vec![] }; + let mut out: Vec<((usize, usize), Point)> = vec![]; + for &((si, ai), p) in points { + let here = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p); + if let Some(q) = here.filter(|q| q.distance(p) <= FOCAL_MATCH) + && !out.iter().any(|(o, _)| *o == (si, ai)) + { + out.push(((si, ai), q)); + } + } + out + } + + /// The focal points other than the pressed point that a drag from `press` moves: all the + /// highlighted ones when the press is on one of them, else none (Shift only keeps the drag's + /// angle). + fn dragged_focal(&self, cx: &ToolContext, press: &ReshapePress) -> Vec<((usize, usize), Point)> { + let focal = self.focal_points(cx, press.id); + let pressed = |r: &(usize, usize)| matches!(press.hit, ReshapeHit::Anchor(si, ai) if (si, ai) == *r); + if focal.iter().any(|(r, _)| pressed(r)) { focal.into_iter().filter(|(r, _)| !pressed(r)).collect() } else { vec![] } + } + + /// `path.reshape`'s params for `press` dragged by `d`. + fn params(cx: &ToolContext, press: &ReshapePress, d: Vec2) -> Value { + let others: Vec<[usize; 2]> = press.others.iter().map(|&((si, ai), _)| [si, ai]).collect(); + let mut v = json!({ "id": press.id.0, "x": press.at.x, "y": press.at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0) }); + if !others.is_empty() { + v["focal"] = json!(others); + } + v + } } impl Tool for ReshapeTool { @@ -296,18 +415,19 @@ impl Tool for ReshapeTool { "reshape" } fn busy(&self) -> bool { - self.grab.is_some() + self.press.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { PointerKind::Down => { - self.grab = Self::hit(cx, ev.pos); + self.press = + Self::hit(cx, ev.pos).map(|(id, at, hit)| ReshapePress { id, at, hit, shift: ev.mods.shift, d: Vec2::ZERO, others: vec![] }); self.began = false; self.measure = None; vec![] } PointerKind::Drag => { - let Some((id, at)) = self.grab else { return vec![] }; + let Some(at) = self.press.as_ref().map(|p| p.at) else { return vec![] }; let mut d: Vec2 = ev.pos - at; if ev.mods.shift { d = vectorcraft_geom::constrain_angle_from(d, 45.0, cx.constrain_angle); @@ -318,25 +438,58 @@ impl Tool for ReshapeTool { return out; } self.began = true; + let others = self.press.as_ref().map(|p| self.dragged_focal(cx, p)).unwrap_or_default(); + if let Some(p) = self.press.as_mut() { + p.others = others; + } out.push(Action::Begin("Reshape".into())); } + let Some(press) = self.press.as_mut() else { return out }; + press.d = d; self.measure = cx.measurement_labels.then(|| (ev.pos + Vec2::new(cx.tol(12.0), cx.tol(12.0)), cx.offset_label(d.x, d.y))); - out.push(Action::Preview( - "path.reshape".into(), - json!({ "id": id.0, "x": at.x, "y": at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0) }), - )); + out.push(Action::Preview("path.reshape".into(), Self::params(cx, press, d))); out } PointerKind::Up => { - self.grab = None; self.measure = None; - if std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] } + let Some(press) = self.press.take() else { return vec![] }; + if std::mem::take(&mut self.began) { + // The focal points move with the whole drag, the grabbed point too, and are + // renumbered after an anchor added on a segment. + let mut points: Vec<((usize, usize), Point)> = press.others.iter().map(|&(r, p)| (press.hit.renumber(r), p + press.d)).collect(); + points.push((press.hit.anchor(), press.at + press.d)); + self.focal = Some((press.id, points)); + return vec![Action::Commit]; + } + // A click: the point becomes the focal point, or with Shift is added to them or, + // when it is one already, removed. + let mut points: Vec<((usize, usize), Point)> = if press.shift { self.focal_points(cx, press.id) } else { vec![] }; + let mut out = vec![]; + match press.hit { + ReshapeHit::Anchor(si, ai) => { + let before = points.len(); + points.retain(|&(r, _)| r != (si, ai)); + if points.len() == before { + points.push(((si, ai), press.at)); + } + } + ReshapeHit::Segment(..) => { + // A reshape by no distance adds the anchor and keeps the selection as it is. + out.push(Action::Exec("path.reshape".into(), Self::params(cx, &press, Vec2::ZERO))); + for (r, _) in &mut points { + *r = press.hit.renumber(*r); + } + points.push((press.hit.anchor(), press.at)); + } + } + self.focal = (!points.is_empty()).then_some((press.id, points)); + out } _ => vec![], } } fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { - if key == ToolKey::Escape && self.grab.take().is_some() { + if key == ToolKey::Escape && self.press.take().is_some() { self.measure = None; if std::mem::take(&mut self.began) { return vec![Action::Cancel]; @@ -344,17 +497,30 @@ impl Tool for ReshapeTool { } vec![] } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.focal = None; + self.measure = None; + if self.press.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Cancel] } else { vec![] } + } fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + // Each focal point: a filled anchor square inside a larger hollow one. + if let Some((id, _)) = &self.focal { + let color = cx.doc.layer_color(*id); + for (_, p) in self.focal_points(cx, *id) { + out.push(Overlay::Anchor { p, color, filled: false, size: 10.0 }); + out.push(Overlay::Anchor { p, color, filled: true, size: 5.0 }); + } + } if cx.measurement_labels && let Some((p, t)) = &self.measure { - vec![Overlay::Measure { p: *p, text: t.clone() }] - } else { - vec![] + out.push(Overlay::Measure { p: *p, text: t.clone() }); } + out } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { - if self.grab.is_some() || Self::hit(cx, p).is_some() { Cursor::Move } else { Cursor::Arrow } + if self.press.is_some() || Self::hit(cx, p).is_some() { Cursor::Move } else { Cursor::Arrow } } } diff --git a/docs/mcp.md b/docs/mcp.md index 14a5bfb6cf..e15674d7ec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3641,21 +3641,36 @@ the canvas (coordinates out of range)". is not a whole number of 0 or more, such as 1.5, -1 or "1" ("missing integer `subpath`"); `path.split` refuses such an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. -`path.reshape {id, x, y, dx, dy, tol?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an anchor -there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. +`path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an +anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) -has the Reshape tool stretch part of a path from the dragged point without losing the path's general form. How far -the stretch reaches and the share of the drag each point takes are VectorCraft's own rule. An open path stretches from -the grabbed point to its two ends: the two end anchors stay in place, and each anchor between an end and the grabbed -point takes `u² (3 - 2u)` of the drag, where `u` is its distance from that end along the path's control polygon -(anchor, out handle, the next in handle, the next anchor) divided by the grabbed point's distance from that end. A +has the Reshape tool stretch part of a path from the dragged point without losing the path's general form, with every +highlighted focal point pulling the path. Which anchors stay, how far the stretch reaches and the share of the drag each +point takes are VectorCraft's own rule. The grabbed point and the anchors that `focal` lists as `[subpath, anchor]` pairs are focal +points and move by the whole drag; a pair that names no anchor of the path is refused ("`focal` names [0, 7], which is +not an anchor of the path"). Anchors that are not direct-selected stay in place (on a path selected whole, or not +selected, every anchor is selected), and so do the two ends of an open path unless they are focal points. A selected +anchor between two focal points moves by the whole drag. A selected anchor between a focal point and an anchor that +stays takes `u² (3 - 2u)` of the drag, where `u` is its distance from the anchor that stays along the path's control +polygon (anchor, out handle, the next in handle, the next anchor) divided by the focal point's distance from it. A handle takes the share on the tangent line of that curve at its anchor, so the handles of a smooth anchor stay in line -with it; a handle that is long beside the distance from the end to the grabbed point takes a share below 0 or above 1, -and moves against the drag or farther than the grabbed point. On a closed path, or when `radius` is given, the anchors -within `radius` of the grabbed point along the path follow with a smooth falloff and the others stay; `radius` -defaults to half the diagonal of the subpath's bounding box, and a negative `radius` is refused ("`radius` must be 0 -or more"). A drag of no length on an anchor (`dx` and `dy` 0 or left out) leaves the path as it is and records no undo -step. +with it; a handle that is long beside that distance takes a share below 0 or above 1, and moves against the drag or +farther than the focal point. A closed subpath with every anchor selected moves whole, and a subpath with no focal +point does not move. An anchor added on a segment of a partly selected path is selected, and the other selected +anchors stay selected. With `radius`, only the grabbed point's subpath changes, whatever the selection: the anchors +within `radius` of the grabbed point along the path follow with a smooth falloff and the others stay; a negative +`radius` is refused ("`radius` must be 0 or more"), and so is `radius` given with `focal` ("`focal` and `radius` +cannot be used together"). A drag of no length on an anchor (`dx` and `dy` 0 or left out) leaves the path as it is +and records no undo step. + +With the Reshape tool, a click on an anchor of a selected path makes it the focal point, and a click on a segment adds +an anchor there (one undo step) that becomes the focal point. Shift-click adds an anchor or a point on a segment to the +focal points. The rest of the tool's behavior is VectorCraft's own rule: Shift-click on a focal point removes it, and +the focal points belong to one path, so a click on another selected path starts again there. Each focal point shows a +filled anchor square in a larger hollow one. A drag from a focal point moves all of them; a drag from another point +moves that point alone as the focal point, with or without Shift (Shift keeps the drag's angle). After a drag the +focal points stay highlighted where it left them; Escape during a drag puts the path back and keeps them, and +switching to another tool clears them. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c15e19cda6..5e417879de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -932,7 +932,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). - A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). On a closed path the anchors within half the diagonal of the subpath's bounding box, measured along the path, follow the dragged point. Clicks do not set focal points. + A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). From 549391a50da435aef273cbcba938f53cfb03725f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:20:56 -0800 Subject: [PATCH 16/83] Menus: a scrolling list keeps each label on one line A popup measures its list on the first frame, when the scroll area does not yet show its bar. When the bar then appeared, its column took its width from the items, and the widest label wrapped onto two lines: Distort & Transform in the Add New Effect menu, and Black and White Logo in the Image Trace presets, in short windows. menu_scroll now lays the items out at least as wide as on the popup's first frame, so the bar's column widens the popup instead. That width is kept until the popup closes and is never wider than the window has room for. The items are laid out in the same child Ui on every frame, so their ids do not change when the width does. --- crates/ui-egui/src/panels/appearance/tests.rs | 17 ++- .../ui-egui/src/panels/image_trace/tests.rs | 18 +++- .../ui-egui/src/panels/tests_long_popups.rs | 100 +++++++++++++++++- crates/ui-egui/src/widgets/dropdowns.rs | 34 ++++-- 4 files changed, 158 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index d3050ad5e3..27bae8fcf4 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -1,5 +1,6 @@ use super::super::tests_long_popups::{ - PopupWindow, assert_last_row_scrolls_into_view, assert_popup_stays_put, assert_short_list_does_not_scroll, fx_menu_ends, + PopupWindow, assert_last_row_scrolls_into_view, assert_popup_stays_put, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, + fx_menu_ends, }; use super::*; @@ -65,6 +66,20 @@ fn a_short_swatch_picker_does_not_scroll() { assert_eq!(window.clickable(TILE), tiles, "a list that fits does not scroll"); } +/// The Add New Effect popup keeps each group's name on one line when its list scrolls: the scroll +/// bar's column widens the popup instead of narrowing the rows. +#[test] +fn the_add_effect_popup_keeps_its_rows_on_one_line_when_it_scrolls() { + let mut groups: Vec = vec![]; + for effect in vectorcraft_effects::effect_catalog() { + let group = effect.menu.get(1).copied().unwrap_or("Other").to_string(); + if !groups.contains(&group) { + groups.push(group); + } + } + assert_rows_stay_on_one_line(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &groups, "Distort & Transform", 120.0); +} + /// The Add New Effect button: the third of the bottom bar's 24 pt buttons. fn fx_button(window: &PopupWindow) -> egui::Pos2 { window.clickable(vec2(24.0, 24.0))[2].center() diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 7e797cead5..1586943c07 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1,4 +1,6 @@ -use super::super::tests_long_popups::{PopupWindow, assert_last_row_scrolls_into_view, assert_short_list_does_not_scroll}; +use super::super::tests_long_popups::{ + PopupWindow, assert_last_row_scrolls_into_view, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, +}; use super::*; use crate::panels::library_panel; use egui::{Event, PointerButton, Pos2, Rect, vec2}; @@ -66,6 +68,20 @@ fn a_long_tracing_preset_list_scrolls_inside_a_short_window() { assert_last_row_scrolls_into_view(&mut app, 200.0, draw, tracing_presets_arrow, &first, "Saved 29"); } +/// The list of presets keeps each name on one line when it scrolls: the scroll bar's column widens +/// the list instead of narrowing the rows. +#[test] +fn a_long_tracing_preset_list_keeps_its_rows_on_one_line() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| trace_button(app, ui, TRACE_BUTTON_W); + for n in 0..30 { + app.session.execute("imageTrace.presets.save", &json!({"name": format!("Saved {n}"), "preset": "Default"})).unwrap(); + } + let presets = app.session.execute("imageTrace.presets", &json!({})).unwrap(); + let names: Vec = presets["presets"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap().to_string()).collect(); + assert_rows_stay_on_one_line(&mut app, draw, tracing_presets_arrow, &names, "Black and White Logo", 120.0); +} + #[test] fn a_large_image_traces_and_the_status_bar_says_it_is_slower() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/tests_long_popups.rs b/crates/ui-egui/src/panels/tests_long_popups.rs index f12e91ab77..c562d3540f 100644 --- a/crates/ui-egui/src/panels/tests_long_popups.rs +++ b/crates/ui-egui/src/panels/tests_long_popups.rs @@ -21,6 +21,7 @@ type Draw<'a> = Box; pub(super) struct PopupWindow<'a> { ctx: egui::Context, time: f64, + width: f32, height: f32, draw: Draw<'a>, texts: Vec<(String, Rect)>, @@ -30,7 +31,7 @@ impl<'a> PopupWindow<'a> { pub(super) fn new(app: &mut VectorcraftApp, height: f32, draw: impl FnMut(&mut VectorcraftApp, &mut Ui) + 'a) -> Self { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let mut window = Self { ctx, time: 0.0, height, draw: Box::new(draw), texts: vec![] }; + let mut window = Self { ctx, time: 0.0, width: WIDTH, height, draw: Box::new(draw), texts: vec![] }; window.frames(app, 2); window } @@ -38,7 +39,7 @@ impl<'a> PopupWindow<'a> { /// One frame with `events`. fn frame(&mut self, app: &mut VectorcraftApp, events: Vec) { self.time += 1.0 / 60.0; - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(WIDTH, self.height))); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, self.height))); let input = egui::RawInput { time: Some(self.time), screen_rect, events, ..Default::default() }; let draw = &mut self.draw; let mut out = self.ctx.run_ui(input, |ui| draw(app, ui)); @@ -46,6 +47,12 @@ impl<'a> PopupWindow<'a> { self.texts = crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); } + /// Makes the window `width` pt wide and draws the frames that takes. + pub(super) fn resize(&mut self, app: &mut VectorcraftApp, width: f32) { + self.width = width; + self.frames(app, OPEN_FRAMES); + } + fn frames(&mut self, app: &mut VectorcraftApp, count: usize) { for _ in 0..count { self.frame(app, vec![]); @@ -58,6 +65,14 @@ impl<'a> PopupWindow<'a> { self.texts.iter().rfind(|(text, _)| text.trim() == wanted).map(|(_, rect)| *rect) } + /// The rect of the popup drawn on top: the last shown area in the foreground. + pub(super) fn popup(&self) -> Option { + self.ctx.memory(|m| { + let top = m.layer_ids().filter(|layer| layer.order == egui::Order::Foreground && m.areas().is_visible(layer)).last()?; + m.area_rect(top.id) + }) + } + /// The rects of the last frame's clickable widgets `size` across, in the order they were drawn. pub(super) fn clickable(&self, size: egui::Vec2) -> Vec { self.ctx.viewport(|vp| { @@ -81,9 +96,14 @@ impl<'a> PopupWindow<'a> { /// Turns the wheel far down with the pointer at `over`, and lets the scrolling finish. pub(super) fn wheel_down(&mut self, app: &mut VectorcraftApp, over: Pos2) { + self.wheel(app, over, 5000.0); + } + + /// Turns the wheel `down` pt down with the pointer at `over`, and lets the scrolling finish. + pub(super) fn wheel(&mut self, app: &mut VectorcraftApp, over: Pos2, down: f32) { let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -5000.0), + delta: vec2(0.0, -down), phase: egui::TouchPhase::Move, modifiers: Default::default(), source: egui::MouseWheelSource::Unknown, @@ -189,6 +209,80 @@ pub(super) fn assert_last_row_scrolls_into_view( assert!(row.bottom() <= height, "{last} at {row:?} is inside the {height} pt window"); } +/// In windows 200, 400 and 900 pt tall, the popup of the button `pick` finds draws each of its rows +/// `rows` that are in view on one line, as tall as the row with the shortest name, and left of the +/// scroll bar's column, whether or not its list scrolls. The row `widest` is drawn the widest; the +/// wheel brings it into view when the popup opens without it. The popup and that row keep their +/// place and size while the popup stays open. After the 200 pt window becomes `narrow` pt wide, +/// the popup and its rows in view stay inside the window. +pub(super) fn assert_rows_stay_on_one_line( + app: &mut VectorcraftApp, + mut draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl Fn(&PopupWindow) -> Pos2, + rows: &[String], + widest: &str, + narrow: f32, +) { + let bar = crate::widgets::list_scroll_style().allocated_width(); + let in_view = + |window: &PopupWindow| -> Vec<(String, Rect)> { rows.iter().filter_map(|row| window.text(row).map(|rect| (row.clone(), rect))).collect() }; + let assert_inside = |window: &PopupWindow, drawn: &[(String, Rect)], name: &str| { + let popup = window.popup().unwrap_or_else(|| panic!("the popup is open in the {name} window")); + for (row, rect) in drawn { + assert!( + rect.left() >= popup.left() && rect.right() <= popup.right() - bar, + "{row} at {rect:?} is drawn left of the scroll bar's column in the popup at {popup:?} in the {name} window" + ); + } + popup + }; + for height in [200.0, 400.0, TALL] { + let mut window = PopupWindow::new(app, height, |app, ui| draw(app, ui)); + let button = pick(&window); + window.click(app, button); + for _ in 0..rows.len() { + if window.text(widest).is_some() { + break; + } + let drawn = in_view(&window); + let Some((_, middle)) = drawn.get(drawn.len() / 2) else { break }; + window.wheel(app, middle.center(), 20.0); + } + let opened = window.text(widest).unwrap_or_else(|| panic!("the popup's row {widest} is in view in the {height} pt window")); + let drawn = in_view(&window); + assert!(drawn.len() >= 3, "the popup's rows are in view in the {height} pt window: {drawn:?}"); + let Some((shortest, line)) = drawn.iter().min_by_key(|(row, _)| row.chars().count()) else { panic!("no rows in view") }; + let line = line.height(); + for (row, rect) in &drawn { + assert!( + rect.height() <= line + 0.5, + "{row} at {rect:?} is drawn on one line, as tall as {shortest} ({line} pt), in the {height} pt window" + ); + } + for (row, rect) in &drawn { + assert!(rect.width() <= opened.width() + 0.5, "{widest} is drawn as wide as {row} at {rect:?} or wider in the {height} pt window"); + } + let popup = assert_inside(&window, &drawn, &format!("{height} pt")); + // The popup's size settles within a frame of opening; after that it stays the same. + window.frames(app, 30); + let settled = window.popup(); + assert!( + settled.is_some_and(|settled| (settled.width() - popup.width()).abs() <= 0.5 && settled.min == popup.min), + "the popup at {settled:?} stays where it opened, at {popup:?}, in the {height} pt window" + ); + window.frames(app, 300); + assert_eq!(window.text(widest), Some(opened), "{widest} keeps its place and size while the popup stays open in the {height} pt window"); + assert_eq!(window.popup(), settled, "the popup keeps its place and size while it stays open in the {height} pt window"); + if height == 200.0 { + window.resize(app, narrow); + let drawn = in_view(&window); + assert!(!drawn.is_empty(), "the popup's rows are in view in the {narrow} pt wide window"); + let popup = assert_inside(&window, &drawn, &format!("{narrow} pt wide")); + assert!(popup.left() >= 0.0, "the popup at {popup:?} starts inside the {narrow} pt wide window"); + } + } +} + /// In a tall window the popup of the button `pick` finds shows its rows `first` to `last` without /// scrolling, and the wheel moves neither. pub(super) fn assert_short_list_does_not_scroll( diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 28ed7c6fb1..44903d6613 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -379,29 +379,51 @@ fn popup_anchor(ui: &Ui) -> Option<(Rect, bool)> { /// The body of a menu or popup list: as tall as its items up to the bottom bars of the window it /// opens in, and scrolling only past that, so long menus (Window, Effect, a panel's menu) stay /// reachable on small windows and in a floating panel's short OS window. Its scroll bar has a column -/// of its own, so it never covers the shortcuts or the submenu arrows (#2086, #5347). +/// of its own, so it never covers the shortcuts or the submenu arrows (#2086, #5347). When the list +/// scrolls, that column widens the popup instead of narrowing the items, so their labels stay on one +/// line. /// /// The list's height comes from the room below and above the button, row or point the popup opens /// from. A popup with an id of its own measures from its own top instead. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - let ctx = ui.ctx(); - let tallest = (ctx.content_rect().height() - egui::Frame::popup(ui.style()).total_margin().sum().y).max(0.0); + let ctx = ui.ctx().clone(); + let margins = egui::Frame::popup(ui.style()).total_margin().sum(); + let tallest = (ctx.content_rect().height() - margins.y).max(0.0); let top = ui.next_widget_position().y; // The rows above the list (the popup's margin, a search field) move with the popup. let popup_top = ui.stack().iter().last().map_or(top, |root| root.max_rect.top()); let ahead = top - popup_top; - let (floor, window_top) = (menu_floor(ctx), ctx.content_rect().top()); + let (floor, window_top) = (menu_floor(&ctx), ctx.content_rect().top()); let room = if let Some((anchor, submenu)) = popup_anchor(ui) { let (down_from, up_to) = if submenu { (anchor.top(), anchor.bottom()) } else { (anchor.bottom(), anchor.top()) }; menu_room_either(floor - down_from - ahead, up_to - window_top - ahead, tallest) } else { menu_room(floor, top, tallest) }; + // The items' width on the first frame of this showing, when the scroll area does not yet show + // its bar. Later frames lay the items out at least that wide, and the bar's column is added to + // the popup's width. The width is kept until the popup closes. + let key = ui.next_auto_id().with("menu-scroll-width"); + let frame = ctx.cumulative_frame_nr(); + let first = ctx.data(|d| d.get_temp::<(u64, f32)>(key)).filter(|(shown, _)| shown + 1 >= frame).map(|(_, width)| width); + let scroll = list_scroll_style(); + // The widest the items can be with the popup's margins and the bar's column inside the window. + let widest = (ctx.content_rect().width() - margins.x - scroll.allocated_width()).max(0.0); ui.scope(|ui| { - ui.spacing_mut().scroll = list_scroll_style(); + ui.spacing_mut().scroll = scroll; // The minimum lets the list grow past a popup's default 400 pt size; it still shrinks to // its items when they need less. - egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner + let area = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room); + let out = area.show(ui, |ui| { + // Always the same child, so the items' ids stay the same on the frame the width changes. + let max = ui.max_rect(); + let width = first.map_or(max.width(), |first| first.min(widest).max(max.width())); + let rect = egui::Rect::from_min_size(max.min, egui::vec2(width, max.height())); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect).layout(*ui.layout()), add_contents).inner + }); + let width = first.unwrap_or(out.content_size.x); + ctx.data_mut(|d| d.insert_temp(key, (frame, width))); + out.inner }) .inner } From f5daa27a2fccc80d7223276a6e47a89e533692c6 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:56:19 +0530 Subject: [PATCH 17/83] =?UTF-8?q?#5820:=20files=20that=20record=20no=20uni?= =?UTF-8?q?ts=20open=20in=20Preferences=20=E2=80=BA=20Units=20=E2=80=BA=20?= =?UTF-8?q?General?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A PDF, an EPS or .ai without ruler units, a raster image, a metafile, an Affinity file or an importer plug-in's document opened (and reverted) in points whatever the General unit was. They now open in the General unit, as the reference app opens files that record no unit. Native, SVG and DXF files and a .ai or EPS with %AI5_RulerUnits keep their own units. Only the displayed units change, not the art. --- crates/doc/src/document.rs | 2 + crates/doc/src/lib.rs | 5 ++ crates/engine/src/cmd/fileio/load.rs | 19 +++++- crates/engine/src/cmd/fileio/save.rs | 2 +- crates/engine/src/tests/units.rs | 75 +++++++++++++++++++++++ crates/engine/src/units.rs | 2 +- crates/eps/src/import/ai/read/document.rs | 1 + docs/ui-parity.md | 5 +- 8 files changed, 106 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 2a2f8a8d7a..0d5163baca 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -75,6 +75,7 @@ impl Document { dimensions, retired_artboard_id: _, opened_artboard: _, + units_from_file: _, index: _, } = self; *version == other.version @@ -256,6 +257,7 @@ impl Document { dimensions: false, retired_artboard_id: Default::default(), opened_artboard: None, + units_from_file: false, index: Default::default(), }; let id = d.alloc_id(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5735d9b480..1f555b74e3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -339,6 +339,11 @@ pub struct Document { /// names it as the file's active artboard. `None`: the first. Native files do not keep it. #[serde(skip)] pub opened_artboard: Option, + /// The file this document was read from recorded its units (a `.ai` file's + /// `%AI5_RulerUnits`): it opens in them. A file that records none opens in Preferences › + /// Units › General (#5820). Native files do not keep it: they always keep their units. + #[serde(skip)] + pub units_from_file: bool, /// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this /// is set, so documents without any pay nothing for them. #[serde(default, skip_serializing_if = "std::ops::Not::not")] diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index fd40139cfe..1c1989bb94 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -43,6 +43,22 @@ impl Loaded { } self } + + /// The file in the units of Preferences › Units › General when it records none of its own: a + /// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or + /// what an importer plug-in reads, as the reference app opens such files (#5820). A native + /// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the + /// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read + /// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows + /// change, not its art. + pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self { + let records_units = + self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf"); + if !records_units { + self.doc.units = crate::units::pref_unit(&prefs.units_general); + } + self + } } /// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG @@ -610,7 +626,8 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st /// Make a loaded file the new active document; `links` is what became of its linked files, and /// `opts` are the options it was read with. fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option, opts: &LoadOptions, as_template: bool) -> Result { - let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = loaded.with_grid_prefs(&s.prefs); + let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = + loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); // EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing // fallbacks must ask before overwriting the richer source they could not fully read. let losses: Vec = warnings diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 6cc93ede1b..9f4e5b0572 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1051,7 +1051,7 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> { fn revert(s: &mut Session, _: &Value) -> Result { let index = s.active_index().ok_or(crate::EngineError::NoDocument)?; let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?; - let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs); + let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); doc.template = false; // Back to the saved file: its recovery copy has nothing left to recover. let uid = s.doc()?.uid; diff --git a/crates/engine/src/tests/units.rs b/crates/engine/src/tests/units.rs index e29365ec9e..6c859b7276 100644 --- a/crates/engine/src/tests/units.rs +++ b/crates/engine/src/tests/units.rs @@ -199,3 +199,78 @@ fn east_asian_type_unit_leaves_the_document_in_points() { assert!((lead.unwrap() - Unit::Ha.to_pt(20.0)).abs() < 1e-9, "{lead:?}"); assert!((sz - 17.0 * 72.0 / 101.6).abs() < 1e-9); } + +/// A session whose Preferences › Units › General is `unit`, with no document open. +fn general_in(unit: &str) -> Session { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": unit})).unwrap(); + s +} + +/// `bytes` opened as `name` in `s` → the opened document's units. +fn opened_units(s: &mut Session, name: &str, bytes: &[u8]) -> Unit { + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + units(s) +} + +/// The active document of a session in `unit`, exported as `format`. +fn exported(unit: &str, format: &str) -> Vec { + let mut s = session(); + s.execute("document.setUnits", &json!({"units": unit})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap(); + let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone(); + vectorcraft_format::base64_decode(data.as_str().unwrap()).unwrap() +} + +/// A PostScript `.ai` with one empty layer and `header` among its comments. +fn postscript_ai(header: &str) -> Vec { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 14.0\n{header}%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 A\n0 Xw\n\nLB\n%AI5_EndLayer--\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) + .into_bytes() +} + +#[test] +fn files_that_record_no_units_open_in_the_general_unit() { + let pdf = vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None); + let png = exported("Inches", "png"); + let ai = postscript_ai(""); + let mut s = general_in("Millimeters"); + assert_eq!(opened_units(&mut s, "plain.pdf", &pdf), Unit::Millimeters, "a PDF records no units (#5820)"); + assert_eq!(opened_units(&mut s, "image.png", &png), Unit::Millimeters, "nor does an image"); + assert_eq!(opened_units(&mut s, "old.ai", &ai), Unit::Millimeters, "nor a .ai without ruler units"); + // Only the units change: the page keeps its size in points. + s.execute("document.open", &json!({"name": "plain.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})).unwrap(); + let board = s.doc().unwrap().doc.artboards[0].rect; + assert!((board.width() - 120.0).abs() < 1e-6 && (board.height() - 60.0).abs() < 1e-6, "{board:?}"); + // With the preference left at points, they open in points as before. + let mut p = general_in("Points"); + assert_eq!(opened_units(&mut p, "plain.pdf", &pdf), Unit::Points); +} + +#[test] +fn files_that_record_units_keep_them_whatever_the_general_unit() { + let mut s = general_in("Millimeters"); + assert_eq!(opened_units(&mut s, "inches.ai", &postscript_ai("%AI5_RulerUnits: 0\n")), Unit::Inches, "a .ai's ruler units"); + assert_eq!(opened_units(&mut s, "points.ai", &postscript_ai("%AI5_RulerUnits: 2\n")), Unit::Points, "ruler units in points are kept too"); + assert_eq!(opened_units(&mut s, "saved.vectorcraft", &exported("Inches", "vectorcraft")), Unit::Inches, "a native file"); + let svg = r#""#; + assert_eq!(opened_units(&mut s, "inches.svg", svg.as_bytes()), Unit::Inches, "an SVG's root size"); +} + +#[test] +fn revert_reopens_a_file_without_units_in_the_general_unit() { + let dir = std::env::temp_dir().join(format!("vc-5820-revert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plain.pdf"); + std::fs::write(&path, vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None)) + .unwrap(); + let mut s = general_in("Millimeters"); + s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(units(&s), Unit::Millimeters); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 5, "height": 5})).unwrap(); + s.execute("document.setUnits", &json!({"units": "Inches"})).unwrap(); + s.execute("file.revert", &json!({})).unwrap(); + assert_eq!(units(&s), Unit::Millimeters, "as the file opens"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index edad5c532c..26fd9ba14f 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -44,7 +44,7 @@ impl Measure { } /// The unit a Units preference value names (points when it names none). -fn pref_unit(value: &str) -> Unit { +pub(crate) fn pref_unit(value: &str) -> Unit { Unit::named(value).unwrap_or_default() } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 63e9f3df77..3cf057abf0 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1253,6 +1253,7 @@ impl<'a> Reader<'a> { } if let Some(u) = self.ruler_units.and_then(ruler_unit) { doc.units = u; + doc.units_from_file = true; } // The file's own swatches in place of the defaults, in its order and colour groups. let own_palette = match self.palette_swatches(&doc.patterns) { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d1b54ef4d6..38297994fa 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -282,7 +282,7 @@ tools, never checked side by side) isn't captured row by row. | Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | | Arithmetic in fields (`+ - * /`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse`; mixed units in one expression not verified | | Numeric fields: focus click selects the whole value; dragging selects from the pressed character | partial | #1326; select-all waits for click release; px/pt/plain/optional fields, both directions and replacement text tested; native API input, 17 px partial replacement, Undo/Redo, saved-file round trip and screenshots verified; Tab, double-click, arrows and wheel preserved; short movements still classified as clicks can select all and remain open | -| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864) | +| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864). A file that records no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files) opens and reverts in General units; native, SVG and DXF files and a `.ai` or EPS with ruler units keep theirs, as a [Community Expert's answer](https://community.adobe.com/questions-652/change-units-from-points-to-inches-won-t-stick-765372) describes (#5820) | | Units › East Asian Type (Q and Ha) | done | #394: `unitsAsianType` offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide's Measurement Units](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`); only it lists Q and Ha. The public pages do not say which fields use it, so no field uses it yet and that waits for a source. Tests `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | Field precision: 3 decimals for steps; values kept as f64 | done | | | Scrubby labels (beyond Illustrator) | done | #400; the labels that are links (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke) scrub too, and a click on them still opens their panel (#4088) | @@ -507,6 +507,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Files that record no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files, importer plug-ins) open and revert in Preferences › Units › General instead of points; native, SVG and DXF files and `.ai`/EPS ruler units are kept (#5820). Scores and estimates unchanged. | | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-08 | minor | Floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part); tab groups remain intact. Scores and estimates unchanged. | From 52918add2d1d94adb43ad1b662b426ad85b4f254 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:12:00 +0530 Subject: [PATCH 18/83] #5820: keep ruler units the EPS program header gives when the editing data has none --- crates/eps/src/import/ai/read/document.rs | 4 ++++ crates/eps/src/import/tests_native.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 3cf057abf0..e9bca36465 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -648,6 +648,10 @@ impl<'a> Reader<'a> { if self.author.is_none() { self.author = outer.author; } + // Ruler units the editing data doesn't give: the file still records them (#5820). + if self.ruler_units.is_none() { + self.ruler_units = outer.ruler_units; + } self.names.absorb(outer.names); for n in outer.custom_colors { if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 867d36d1a2..4adb04e8be 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -77,6 +77,26 @@ fn names(d: &Document) -> Vec { d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect() } +#[test] +fn ruler_units_in_the_program_header_alone_are_kept() { + let art = layer("Art", true, &square(10, 10)); + let native = |units: &str| { + format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n{units}%AI5_NumLayers: 1\n{art}%%Trailer\n" + ) + }; + let with_header = |data: Vec| { + let at = data.windows(13).position(|w| w == b"%%EndComments").unwrap(); + [&data[..at], &b"%AI5_RulerUnits: 0\n"[..], &data[at..]].concat() + }; + let r = import(&with_header(eps(&page_square(10, 10), &native("")))).unwrap(); + assert_eq!((r.document.units, r.document.units_from_file), (Unit::Inches, true), "the program's header gives them"); + let r = import(&with_header(eps(&page_square(10, 10), &native("%AI5_RulerUnits: 1\n")))).unwrap(); + assert_eq!(r.document.units, Unit::Millimeters, "the editing data's own come first"); + let r = import(&eps(&page_square(10, 10), &native(""))).unwrap(); + assert_eq!((r.document.units, r.document.units_from_file), (Unit::Points, false), "none recorded"); +} + #[test] fn native_import_keeps_ruler_units_from_editing_data() { let art = layer("Art", true, &square(10, 10)); From c6760516414914a48892f0279c032a6ae9e8c24f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 20:53:24 -0800 Subject: [PATCH 19/83] Character Styles: the style dialogs' fields have accessible names The text fields and menus of the Basic Character Formats, Advanced Character Formats, Character Color and OpenType Features sections, and the Style Name field of Character Style Options, are now named by the label beside them, so screen readers announce them. This covers both Character Style Options and New Character Style, which share the sections. The New Character Style UI test runs with the accessibility check on again, and a new test opens every section of both dialogs and checks that no input is unnamed. --- .../ui-egui/src/dialogs/char_style_options.rs | 110 ++++++++++++------ 1 file changed, 73 insertions(+), 37 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 86f8fe4531..e1f564d08a 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -661,18 +661,22 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { ("kerning", tl!("Kerning")), ("tracking", tl!("Tracking")), ] { - ui.label(caption); + let row = ui.label(caption); if d.fields.get(key).is_some_and(Value::is_null) { d.fields.insert(key.into(), json!("")); } - form::text(ui, d, key, 190.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, key, 190.0)); ui.end_row(); } - ui.label(tl!("Case")); - choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + let row = ui.label(tl!("Case")); + ui.label_inputs_by(row.id, |ui| { + choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + }); ui.end_row(); - ui.label(tl!("Position")); - choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + let row = ui.label(tl!("Position")); + ui.label_inputs_by(row.id, |ui| { + choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + }); ui.end_row(); for (key, caption) in [ ("underline", tl!("Underline")), @@ -693,20 +697,22 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { } ui.end_row(); } - ui.label(tl!("Character Alignment")); - choice( - ui, - d, - "charAlign", - &[ - ("romanBaseline", tl!("Roman Baseline")), - ("emBoxTop", tl!("Em Box Top/Right")), - ("emBoxCenter", tl!("Em Box Center")), - ("emBoxBottom", tl!("Em Box Bottom/Left")), - ("icfTop", tl!("ICF Top/Right")), - ("icfBottom", tl!("ICF Bottom/Left")), - ], - ); + let row = ui.label(tl!("Character Alignment")); + ui.label_inputs_by(row.id, |ui| { + choice( + ui, + d, + "charAlign", + &[ + ("romanBaseline", tl!("Roman Baseline")), + ("emBoxTop", tl!("Em Box Top/Right")), + ("emBoxCenter", tl!("Em Box Center")), + ("emBoxBottom", tl!("Em Box Bottom/Left")), + ("icfTop", tl!("ICF Top/Right")), + ("icfBottom", tl!("ICF Bottom/Left")), + ], + ); + }); ui.end_row(); }); } @@ -721,20 +727,20 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { ("baseline_shift", tl!("Baseline Shift"), "pt"), ("rotation", tl!("Character Rotation"), "°"), ] { - ui.label(caption); + let row = ui.label(caption); if d.fields.get(key).is_some_and(Value::is_null) { d.fields.insert(key.into(), json!("")); } ui.horizontal(|ui| { - form::text(ui, d, key, 160.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, key, 160.0)); ui.label(unit); }); ui.end_row(); } - ui.label(tl!("Language:")); + let row = ui.label(tl!("Language:")); let names: Vec<&str> = std::iter::once(" ").chain(vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| *name)).collect(); let current = d.fields.get("language").and_then(Value::as_str).unwrap_or("").to_string(); - if let Some(i) = crate::widgets::dropdown(ui, (KIND, "language"), ¤t, &names, 190.0) { + if let Some(i) = ui.label_inputs_by(row.id, |ui| crate::widgets::dropdown(ui, (KIND, "language"), ¤t, &names, 190.0)) { d.fields.insert("language".into(), if i == 0 { Value::Null } else { names.get(i).map_or(Value::Null, |name| json!(name)) }); } ui.end_row(); @@ -799,31 +805,31 @@ fn paint_choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-color").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { for (key, caption) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { - ui.label(caption); - paint_choice(ui, d, key); + let row = ui.label(caption); + ui.label_inputs_by(row.id, |ui| paint_choice(ui, d, key)); ui.end_row(); let tint_key = format!("{key}_tint"); - ui.label(tl!("Tint")); + let row = ui.label(tl!("Tint")); if d.fields.get(&tint_key).is_none_or(Value::is_null) { d.fields.insert(tint_key.clone(), json!("")); } let linked = d.fields.get(key).and_then(|p| p.get("swatch")).is_some_and(Value::is_string); ui.add_enabled_ui(linked, |ui| { ui.horizontal(|ui| { - form::text(ui, d, &tint_key, 160.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, &tint_key, 160.0)); ui.label("%"); }); }); ui.end_row(); } - ui.label(tl!("Weight")); + let row = ui.label(tl!("Weight")); if d.fields.get("stroke_width").is_none_or(Value::is_null) { d.fields.insert("stroke_width".into(), json!("")); } let stroked = d.fields.get("stroke").and_then(|p| p.get("type")).and_then(Value::as_str) != Some("none"); ui.add_enabled_ui(stroked, |ui| { ui.horizontal(|ui| { - form::text(ui, d, "stroke_width", 160.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, "stroke_width", 160.0)); ui.label("pt"); }); }); @@ -839,11 +845,11 @@ pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { let figures: Vec<(&str, &str)> = FIGURE_VALUES.into_iter().zip(crate::panels::opentype::FIGURES).collect(); let positions: Vec<(&str, &str)> = POSITION_VALUES.into_iter().zip(crate::panels::opentype::POSITIONS).collect(); egui::Grid::new("character-style-opentype").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { - ui.label(tl!("Figure:")); - choice(ui, d, "ot_figure", &figures); + let row = ui.label(tl!("Figure:")); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "ot_figure", &figures)); ui.end_row(); - ui.label(tl!("Position:")); - choice(ui, d, "ot_position", &positions); + let row = ui.label(tl!("Position:")); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "ot_position", &positions)); ui.end_row(); for (key, caption) in [ ("ot_liga", tl!("Standard Ligatures")), @@ -929,8 +935,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { opentype_body(ui, d); } else { ui.horizontal(|ui| { - ui.label(tl!("Style Name:")); - form::text(ui, d, "name", 190.0); + let row = ui.label(tl!("Style Name:")); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, "name", 190.0)); }); ui.separator(); if let Ok(attrs) = edited_attrs(d) { @@ -1837,7 +1843,7 @@ mod tests { }; let shown = crate::i18n::message(crate::i18n::current(), &why); let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).with_accessibility_check(false).build_ui_state( + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { if !std::mem::replace(&mut fonts, true) { crate::theme::install_fonts(ui.ctx()); @@ -1857,6 +1863,36 @@ mod tests { } } + #[test] + fn every_section_names_its_inputs_in_both_dialogs() { + for new_style in [false, true] { + for section in ["general", "basic", "advanced", "color", "opentype"] { + let mut app = app(); + if new_style { + app.run("ui.newCharStyle", json!({})).unwrap(); + } else { + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + } + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section)); + let mut fonts = false; + // The harness fails a frame that leaves an input without an accessible name. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + assert!(h.unnamed_widgets().is_empty(), "new {new_style}, {section}: {:?}", h.unnamed_widgets()); + } + } + } + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); From 561dcb20d3d92f2b905e81c84ca204b087804424 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:08:32 -0800 Subject: [PATCH 20/83] Docs: the Scripts folder lines say which path each command checks and which platforms read it on File --- docs/mcp.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 4cacb595dd..8d6debc9a6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1660,7 +1660,7 @@ way. The listed scripts come first in the menu, above Check Script… and Other The rest of this section is VectorCraft's own rules: - The folder is read when the app starts, each time its window becomes the active one, and, where the menus are in - the window (Windows and Linux), each time the File menu opens. A script added while VectorCraft runs is listed + the window (Windows, Linux and BSD), each time the File menu opens. A script added while VectorCraft runs is listed after the next of these. A read takes names only, never a script's text, and runs off the UI thread, one read at a time. - Each level is sorted by label without regard to case, with scripts and subfolders mixed. A script whose label @@ -1684,8 +1684,9 @@ The rest of this section is VectorCraft's own rules: `script.listInstalled {}` returns the same listing: `{folder, scripts: [{path, label, folders}], truncated, unreadable}`, with the scripts in menu order and `folders` the labels of the subfolders a script is in. `folder` is `null` without a Scripts folder. `ui.runInstalledScript {path}` runs one of them by the `path` the listing gave, as -its menu item does. Under `--automation-read-root`, both read the folder only when it lies inside a read root, and -`ui.menu.list` leaves out the listed scripts outside the read roots. +its menu item does. Under `--automation-read-root`, `script.listInstalled` lists the folder only when the folder lies +inside a read root, `ui.runInstalledScript` runs a script only when the script lies inside one, and `ui.menu.list` +leaves out the listed scripts outside the read roots. ```json {"name":"run_command","arguments":{"command":"script.listInstalled","params":{}}} From d069e0e4be2ddd7bab82ef3a0f4c6a2f6daa9d0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:08:57 -0800 Subject: [PATCH 21/83] Symbols: Break Link selects no art inside a hidden or locked group Break Link to Symbol on a selected group selected the art of every instance it expanded that was itself shown and unlocked, including art in a hidden or locked group inside the selection. The art now goes into the selection only when it and every group and layer holding it are shown and unlocked, the check Select All uses (select::is_selectable). --- crates/engine/src/cmd/brushsym/symbols.rs | 7 ++++-- crates/engine/src/tests/brushsym.rs | 28 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index ee4487ba72..395c07052c 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -493,10 +493,13 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(EngineError::Other("no symbol instances selected".into())); } + let iso = s.doc()?.isolation; let out = s.edit("Break Link to Symbol", |d, sel| { let out = break_links(d, &ids, true)?; - // Hidden or locked art is left out of the selection. - sel.set(out.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked))); + // Art that is hidden or locked, or in a hidden or locked group or layer, is left out of the + // selection. + let locks = d.locked_artboards(); + sel.set(out.iter().copied().filter(|id| crate::cmd::select::is_selectable(d, iso, &locks, *id))); Ok(out) })?; Ok(json!({ "ids": ids_json(&out) })) diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 34f2cc4b0b..ccf277585f 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1358,6 +1358,34 @@ fn break_link_keeps_hidden_and_locked_instances_hidden_and_locked() { assert!(selected.iter().all(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked)), "{selected:?}"); } +/// Break Link to Symbol on a selected group does not select the art of a shown, unlocked instance +/// that sits in a hidden or a locked group inside it. +#[test] +fn break_link_leaves_art_in_hidden_or_locked_groups_unselected() { + let mut s = session(); + let (shown, name, _) = make_symbol(&mut s); + let subgroup = |s: &mut Session, y: i64| { + let id = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": y})).unwrap()["id"].as_u64().unwrap()); + select(s, &[id]); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + }; + let hidden = subgroup(&mut s, 200); + let locked = subgroup(&mut s, 100); + select(&mut s, &[shown, hidden, locked]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(hidden).unwrap().visible = false; + doc.node_mut(locked).unwrap().locked = true; + select(&mut s, &[group]); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}"); + let d = &s.doc().unwrap().doc; + let selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(selected.len(), 1, "{selected:?}"); + let a = d.ancestry(selected[0]).unwrap(); + assert!(!a.contains(&hidden) && !a.contains(&locked), "{a:?}"); +} + /// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked /// instance's art locked. #[test] From ef6d14dc2240931ec02dc508fd027c7a04b62167 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:28:17 -0800 Subject: [PATCH 22/83] Dimension tool: both ends of a dimension follow the art it measures A linear dimension clicked from an anchor to a point that is not an anchor (a point on a segment, or a point a Smart Guide gave) followed the art at the anchor end only, so scaling the art turned it into a long slanted dimension. - A point on a segment is stored by its curve parameter on that segment, and stays on it when the segment's anchors or handles are edited. - Any other point is stored against anchors (and, for a path whose anchors lie on one line, handles) of the path under it, or of the path at the other end, and moves, scales, turns and reflects with that path. Beside a path whose anchors and handles all lie on one line, such as a straight line, it keeps its distance along and across the path: a reflection moves it as a half turn does, and a scale that is not uniform moves it as a uniform scale does. - When linked art is reflected, a linear dimension's line goes to the reflected side, except for art whose anchors and handles lie on one line. - Deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. Undo links it again. Docs: docs/dimensions.md, docs/target-app-parity.md. --- crates/doc/src/dimension.rs | 314 ++++++++++++++++++- crates/engine/src/cmd/dimension.rs | 35 ++- crates/engine/src/cmd/expand.rs | 2 +- crates/engine/tests/it/dimensions.rs | 430 ++++++++++++++++++++++++++- crates/tools/src/dimension.rs | 92 +++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/dimensions.md | 21 +- docs/target-app-parity.md | 1 + 34 files changed, 896 insertions(+), 26 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 301e1beb8e..89df899743 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -1,7 +1,7 @@ //! Persistent dimension recipes. Children are ordinary paths and type for all renderers/exporters. use crate::{Document, NodeId, Unit}; use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, Vec2}; /// What a dimension measures. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -306,6 +306,12 @@ pub enum DimensionSource { a: Option, b: Option, vertex: Option, + /// The first point when it is not an anchor, held against a path's anchors. + #[serde(default, rename = "freeA", skip_serializing_if = "Option::is_none")] + free_a: Option, + /// The second point when it is not an anchor. + #[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")] + free_b: Option, }, } @@ -315,7 +321,11 @@ impl DimensionSource { Self::Segment { edge } | Self::Arc { edge } => vec![edge.node], Self::Angle { first, second } => vec![first.node, second.node], Self::Circle { node } => vec![*node], - Self::Points { a, b, vertex } => [a, b, vertex].into_iter().filter_map(|p| p.as_ref().map(|r| r.node)).collect(), + Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex] + .into_iter() + .filter_map(|p| p.as_ref().map(|r| r.node)) + .chain([free_a, free_b].into_iter().filter_map(|p| p.as_ref().map(FreePoint::node))) + .collect(), } } /// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle @@ -332,6 +342,34 @@ impl DimensionSource { old.is_some() && old != counts(after) }) } + /// The map that took the measured art from `before` to `after`, when every path it measures + /// went through one [`art_transform`] that reflects it (a negative determinant). None when a + /// measured path is unchanged, or when two of them went through different maps. + pub fn reflection(&self, before: &Document, after: &Document) -> Option { + let mut first: Option = None; + for id in self.nodes() { + let (old, new) = (before.node(id)?, after.node(id)?); + if std::ptr::eq(old, new) || old.path_data() == new.path_data() { + return None; + } + let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?; + match first { + None => first = Some(xf), + Some(f) => { + // The linear parts and the translations, each against its own size. + let (a, b) = (f.as_coeffs(), xf.as_coeffs()); + let differ = |range: std::ops::Range, tolerance: f64| { + let size = a[range.clone()].iter().map(|c| c.abs()).fold(1.0, f64::max); + a[range.clone()].iter().zip(&b[range]).any(|(p, q)| (p - q).abs() > tolerance * size) + }; + if differ(0..4, 1e-9) || differ(4..6, 1e-9) { + return None; + } + } + } + } + first + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -348,6 +386,235 @@ impl PointRef { } } +/// The point of an anchor that an [`AnchorWeight`] names: the anchor, or one of its handles. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AnchorPart { + #[default] + Point, + In, + Out, +} + +impl AnchorPart { + fn of(self, a: &Anchor) -> Point { + match self { + Self::Point => a.p, + Self::In => a.h_in, + Self::Out => a.h_out, + } + } +} + +/// One anchor's share of a [`FreePoint`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AnchorWeight { + pub subpath: usize, + pub anchor: usize, + /// The anchor itself, or its in or out handle. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub part: AnchorPart, + pub weight: f64, +} + +/// A measured point that is not an anchor (a point on a segment, or a point a Smart Guide gave), +/// linked to one path so that it moves with it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum FreePoint { + /// A point on a segment at curve parameter `t`, 0 at the segment's first anchor and 1 at its + /// last. It stays on the segment when the segment's anchors or handles are edited. + OnSegment { edge: SegmentRef, t: f64 }, + /// A weighted sum of two or three anchors or handles of one path, the weights adding up to 1, + /// plus `across` times the vector from the first anchor to the second turned a quarter turn, + /// from (x, y) to (-y, x), so that a vector pointing right in the y-down document space + /// turns to point down (two anchors only). When the + /// path is moved, scaled, rotated, reflected or sheared, a point held by three moves with + /// it. A point held by two and `across`, beside a straight path, moves, turns and scales + /// uniformly with it, and a reflection or a non-uniform scale moves it as a half turn or a + /// uniform scale would. + Anchors { + node: NodeId, + anchors: Vec, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + across: f64, + }, +} + +/// A point of a path: (subpath, anchor, part, place). +type PathPoint = (usize, usize, AnchorPart, Point); + +/// Every anchor of `path` in order, each followed by its in and out handles when `handles` is set. +fn path_points(path: &PathData, handles: bool) -> impl Iterator + Clone + '_ { + let parts: &'static [AnchorPart] = if handles { &[AnchorPart::Point, AnchorPart::In, AnchorPart::Out] } else { &[AnchorPart::Point] }; + path.subpaths + .iter() + .enumerate() + .flat_map(move |(si, sp)| sp.anchors.iter().enumerate().flat_map(move |(ai, a)| parts.iter().map(move |&part| (si, ai, part, part.of(a))))) +} + +/// Three points that span `points`: the first, the one farthest from it, and the one farthest +/// from the line through those two. None when every point is in one place. +fn spanning(points: impl Iterator + Clone) -> Option<[PathPoint; 3]> { + let first = points.clone().next()?; + let o = first.3; + let second = points.clone().max_by(|x, y| x.3.distance(o).total_cmp(&y.3.distance(o)))?; + let u = second.3 - o; + let span = u.hypot(); + if !span.is_finite() || span <= 1e-6 { + return None; + } + let third = points.max_by(|x, y| u.cross(x.3 - o).abs().total_cmp(&u.cross(y.3 - o).abs()))?; + Some([first, second, third]) +} + +/// The map that takes the anchors and handles of path `node` in `before` to where they are in +/// `after`, when one affine map does that for every one of them: the path was moved, scaled, +/// rotated, reflected or sheared as a whole. None when its anchors changed in number, moved in +/// another way, or lie on one line with all their handles, as on a straight line: a reflection +/// across a line through such a path puts its points where a turn can put them too. +pub fn art_transform(before: &Document, after: &Document, node: NodeId) -> Option { + fitted(before, after, node, |_| true) +} + +/// [`art_transform`] when the map passes `wanted`. The map is found from three points, and +/// `wanted` is asked before every other point is checked against it. +fn fitted(before: &Document, after: &Document, node: NodeId, wanted: impl Fn(&Affine) -> bool) -> Option { + let (old, new) = (before.node(node)?.path_data()?, after.node(node)?.path_data()?); + if old.subpaths.len() != new.subpaths.len() || old.subpaths.iter().zip(&new.subpaths).any(|(o, n)| o.anchors.len() != n.anchors.len()) { + return None; + } + let [o, f, g] = spanning(path_points(old, true))?; + let place = |q: PathPoint| new.subpaths.get(q.0).and_then(|sp| sp.anchors.get(q.1)).map(|a| q.2.of(a)); + let (o2, f2, g2) = (place(o)?, place(f)?, place(g)?); + let (u, v) = (f.3 - o.3, g.3 - o.3); + let span = u.hypot(); + if u.cross(v).abs() <= 1e-9 * span * span { + return None; + } + let basis = |u: Vec2, v: Vec2| Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]); + let linear = basis(f2 - o2, g2 - o2) * basis(u, v).inverse(); + let xf = Affine::translate(o2.to_vec2()) * linear * Affine::translate(-o.3.to_vec2()); + if !xf.as_coeffs().iter().all(|c| c.is_finite()) || !wanted(&xf) { + return None; + } + let tolerance = 1e-6 * span.max(1.0); + path_points(old, true).zip(path_points(new, true)).all(|(o, n)| (xf * o.3).distance(n.3) <= tolerance).then_some(xf) +} + +impl FreePoint { + /// Largest weight: a point far outside the anchors that hold it is not held. + const MAX_WEIGHT: f64 = 1e4; + + /// The path it is linked to. + pub fn node(&self) -> NodeId { + match self { + Self::OnSegment { edge, .. } => edge.node, + Self::Anchors { node, .. } => *node, + } + } + + /// `p` held against path `node`: three anchors that span the path; when all its anchors lie + /// on one line or in one place, as on an arch, three of its anchors and handles; when its + /// handles lie on that line too, or so nearly that the weights would be too large, two anchors + /// and `p`'s distance across that line. None when none of these holds `p`. + pub fn on(doc: &Document, node: NodeId, p: Point) -> Option { + let path = doc.node(node)?.path_data()?; + let weight = |(subpath, anchor, part, _): PathPoint, weight| AnchorWeight { subpath, anchor, part, weight }; + for handles in [false, true] { + let Some([o, f, g]) = spanning(path_points(path, handles)) else { continue }; + let (u, v) = (f.3 - o.3, g.3 - o.3); + let span = u.hypot(); + let det = u.cross(v); + if det.abs() > 1e-9 * span * span { + let s = (p - o.3).cross(v) / det; + let t = u.cross(p - o.3) / det; + let anchors = vec![weight(o, 1.0 - s - t), weight(f, s), weight(g, t)]; + // A nearly flat set of points gives weights too large to keep: the next fit is tried. + if let Some(held) = (Self::Anchors { node, anchors, across: 0.0 }).holding(doc, p, span) { + return Some(held); + } + } + } + // Every anchor and handle on one line, or nearly: along it from the first anchor, and across it. + let [o, f, _] = spanning(path_points(path, false))?; + let u = f.3 - o.3; + let span = u.hypot(); + let (t, across) = ((p - o.3).dot(u) / (span * span), u.cross(p - o.3) / (span * span)); + Self::Anchors { node, anchors: vec![weight(o, 1.0 - t), weight(f, t)], across }.holding(doc, p, span) + } + + /// `p` on the segment `edge`, at the curve parameter of the segment's point nearest to it. + /// None when the segment is gone or `p` is not on it. + pub fn on_segment(doc: &Document, edge: &SegmentRef, p: Point) -> Option { + use vectorcraft_geom::kurbo::ParamCurveNearest; + let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?; + if edge.segment >= sp.segment_count() { + return None; + } + let (a, b) = edge.endpoints(doc)?; + let t = sp.segment(edge.segment).nearest(p, 1e-12).t; + Self::OnSegment { edge: edge.clone(), t }.holding(doc, p, a.distance(b)) + } + + /// Itself when it is [`Self::valid`] and puts the point at `p`, within a tolerance that grows + /// with `span`, the size of the art that holds it. + fn holding(self, doc: &Document, p: Point, span: f64) -> Option { + let at = self.position(doc)?; + (at.distance(p) <= 1e-6 * span.max(1.0)).then_some(self) + } + + /// Whether its numbers can be used: a finite `t` from 0 to 1 on a segment; or two or three + /// weights that add up to 1, with `across` set only for two, each finite and at most + /// [`Self::MAX_WEIGHT`] across. + pub fn valid(&self) -> bool { + match self { + Self::OnSegment { t, .. } => (0.0..=1.0).contains(t), + Self::Anchors { anchors, across, .. } => { + (2..=3).contains(&anchors.len()) + && anchors.iter().all(|w| w.weight.is_finite() && w.weight.abs() <= Self::MAX_WEIGHT) + && (anchors.iter().map(|w| w.weight).sum::() - 1.0).abs() <= 1e-9 + && across.is_finite() + && across.abs() <= Self::MAX_WEIGHT + && (*across == 0.0 || anchors.len() == 2) + } + } + } + + /// Where the point is now. None when its segment or an anchor is gone or the point is not + /// [`Self::valid`]. + pub fn position(&self, doc: &Document) -> Option { + use vectorcraft_geom::kurbo::ParamCurve; + if !self.valid() { + return None; + } + let at = match self { + Self::OnSegment { edge, t } => { + let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?; + if edge.segment >= sp.segment_count() { + return None; + } + sp.segment(edge.segment).eval(*t) + } + Self::Anchors { node, anchors, across } => { + let path = doc.node(*node)?.path_data()?; + let place = |w: &AnchorWeight| path.subpaths.get(w.subpath).and_then(|sp| sp.anchors.get(w.anchor)).map(|a| w.part.of(a).to_vec2()); + let mut at = Vec2::ZERO; + for w in anchors { + at += place(w)? * w.weight; + } + if *across != 0.0 { + let u = place(anchors.get(1)?)? - place(anchors.first()?)?; + at += Vec2::new(-u.y, u.x) * *across; + } + at.to_point() + } + }; + (at.x.is_finite() && at.y.is_finite()).then_some(at) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Dimension { @@ -441,6 +708,36 @@ impl Dimension { self.offset = offset; } } + /// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes + /// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far + /// past the outermost point on that side as `old`'s line was. A line that lay between the two + /// points is left as it is. + pub fn mirror_line(&mut self, old: &Dimension, image: Point) { + if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear { + return; + } + let gap = { + let n = old.normal(); + let across = |p: Point| p.to_vec2().dot(n); + let line = across(old.a) + old.offset; + let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b))); + if line >= high { + line - high + } else if line <= low { + low - line + } else { + return; + } + }; + let n = self.normal(); + let across = |p: Point| p.to_vec2().dot(n); + let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap }; + let offset = at - across(self.a); + if offset.is_finite() && offset.abs() <= 1e6 { + self.offset = offset; + } + } /// Whether a linear dimension's line lies strictly between its two points along the normal. fn line_between_points(&self) -> bool { let n = self.normal(); @@ -525,10 +822,15 @@ impl Dimension { } pub fn resolve(&mut self, doc: &Document) -> Result<(), String> { match &self.source { - Some(DimensionSource::Points { a, b, vertex }) => { - for (reference, point) in [(a, &mut self.a), (b, &mut self.b), (vertex, &mut self.vertex)] { - if let Some(r) = reference { - *point = r.position(doc).ok_or("Measured anchor no longer exists")?; + Some(DimensionSource::Points { a, b, vertex, free_a, free_b }) => { + for (reference, free, point) in [(a, free_a, &mut self.a), (b, free_b, &mut self.b), (vertex, &None, &mut self.vertex)] { + match (reference, free) { + // An end is an anchor or a free point, never both. + (Some(_), Some(_)) => return Err("Invalid measured point".into()), + (Some(r), None) => *point = r.position(doc).ok_or("Measured anchor no longer exists")?, + (None, Some(f)) if !f.valid() => return Err("Invalid measured point".into()), + (None, Some(f)) => *point = f.position(doc).ok_or("Measured anchor no longer exists")?, + (None, None) => {} } } self.length = if self.mode == DimensionMode::Linear { self.measured() } else { self.a.distance(self.b) }; diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 01f1effe3e..fa2137c9d1 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Create Dimension", [], None, - "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", + "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", has_doc, create ), @@ -231,9 +231,10 @@ fn apply_to_all(s: &mut Session, p: &Value) -> Result { fn replace(doc: &mut Document, id: NodeId, dim: Dimension) -> Result<()> { let old: Vec = doc.node(id).and_then(Node::children).map(|ch| ch.iter().map(|n| n.id).collect()).unwrap_or_default(); let children = artwork(doc, &dim, &old)?; + let name = format!("Dimension · {}", dim.label().map_err(error)?); if let Some(n) = doc.node_mut(id) { n.kind = NodeKind::Group { children, clip: false }; - n.name = Some(format!("Dimension · {}", dim.label().map_err(error)?)); + n.name = Some(name); n.extras_mut().dimension = Some(Box::new(dim)); } Ok(()) @@ -272,7 +273,8 @@ impl EndedLink { /// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it /// measured. A command that replaces art calls this before it changes anything, since replacing -/// the art a dimension measures would remove the dimension, and then [`restore_unchanged`]. +/// the art a dimension measures would otherwise leave the dimension unlinked, and then +/// [`restore_unchanged`]. pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec { let mut ended = Vec::new(); for id in reached(doc, roots) { @@ -315,18 +317,37 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { let mut next = old.clone(); let moved = next.moved.take(); if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() { - // A deleted/degenerate source has no valid measurement. Remove its annotation in - // this same undo step instead of keeping a silently wrong number. - doc.remove(id)?; + // The art it measured was deleted, or rebuilt with other anchors, or no longer fits + // (an ellipse that was a circle): it stays where it was, no longer linked, in this + // same undo step, rather than attaching to a different edge. + let mut unlinked = old.clone(); + unlinked.source = None; + unlinked.moved = None; + if let Some(v) = moved { + let mut shifted = unlinked.clone(); + (shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v); + if shifted.validate().is_ok() { + unlinked = shifted; + } + } + if replace(doc, id, unlinked).is_err() + && let Some(n) = doc.node_mut(id) + { + // Its recipe cannot be drawn again: its art stays as it is, as a plain group. + n.extras_mut().dimension = None; + } changed = true; continue; } next.keep_gap(&old); + if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) { + next.mirror_line(&old, xf * old.handle()); + } // Moved on its own (the art it measures stayed put): it keeps its new place. if let Some(v) = moved && (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex) { - next.place(next.handle() + v); + next.place(old.handle() + v); if next.resolve(doc).is_err() { next = old.clone(); next.moved = None; diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 546b5a8258..c5c0fbd65b 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -242,7 +242,7 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result { let to = GradientTo::parse(p)?; let from = s.doc()?.history.undo.len(); let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); - // Before anything expands: outlining the art a dimension measures would remove the dimension. + // Before anything expands: outlining the art a dimension measures would leave the dimension unlinked. let before = s.doc()?.doc.clone(); let mut ended = vec![]; end_dimension_links(s, &mut ended)?; diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index bcb684b0a5..934108905c 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -59,9 +59,11 @@ fn dimension_length_scale_live_edit_undo_and_roundtrip() { run(&mut reopened, "object.scale", json!({"sx":50,"sy":100})); assert_eq!(text(&reopened, id), "10.00 in"); run(&mut reopened, "edit.clear", json!({})); - assert!(reopened.doc().unwrap().doc.node(NodeId(id)).is_none()); + assert_eq!(text(&reopened, id), "10.00 in", "deleting the art leaves the dimension"); + assert!(recipe(&reopened, id).source.is_none(), "no longer linked"); run(&mut reopened, "edit.undo", json!({})); assert_eq!(text(&reopened, id), "10.00 in"); + assert!(recipe(&reopened, id).source.is_some(), "undo links it again"); } /// Documents without dimensions skip the refresh, and lose the flag when the last goes. @@ -567,6 +569,425 @@ fn dimension_anchor_links_and_native_file_survive_source_moves() { assert_eq!(text(&s, id), "100 pt"); } +/// The anchors of path `id`'s first subpath. +fn anchors(s: &Session, id: u64) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect() +} +fn near(p: vectorcraft_geom::Point, q: vectorcraft_geom::Point) -> bool { + p.distance(q) < 1e-6 +} +/// Clicks with the Dimension tool at each point in turn. +fn clicks(s: &mut Session, points: &[(f64, f64)]) -> u64 { + s.select_tool("dimension", ViewInfo::default()).unwrap(); + for &(x, y) in points { + ev(s, PointerKind::Move, x, y); + ev(s, PointerKind::Down, x, y); + ev(s, PointerKind::Up, x, y); + } + s.doc().unwrap().selection.objects[0].0 +} + +/// A dimension from an anchor to a point on a straight segment follows the art at both ends: the +/// segment end keeps its place along the segment when the art is scaled, moved or reflected. +#[test] +fn a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let length = recipe(&s, id).length; + for (command, p) in [ + ("object.scale", json!({"sx":150,"sy":150})), + ("object.move", json!({"dx":40,"dy":-30})), + ("object.rotate", json!({"angle":30})), + ("object.reflect", json!({"axis":"vertical"})), + ] { + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, command, p); + let (d, at) = (recipe(&s, id), anchors(&s, rect)); + assert!(near(d.a, at[0]), "{command}: {:?} {:?}", d.a, at[0]); + assert!(near(d.b, at[1].midpoint(at[2])), "{command}: {:?} {:?}", d.b, at[1].midpoint(at[2])); + assert!(d.source.is_some(), "{command}: still linked"); + } + assert!((recipe(&s, id).length - 1.5 * length).abs() < 1e-6); +} + +/// A point off the art is held against the anchors of the art at the other end, and moves with it. +#[test] +fn a_dimension_to_a_point_off_the_art_moves_with_the_art() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(200.0, 200.0), (330.0, 260.0), (260.0, 330.0)]); + let before = recipe(&s, id); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + let v = vectorcraft_geom::Vec2::new(40.0, -30.0); + assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); + assert!((d.length - before.length).abs() < 1e-6 && (d.offset - before.offset).abs() < 1e-6); + run(&mut s, "object.scale", json!({"sx":200,"sy":200})); + assert!((recipe(&s, id).length - 2.0 * before.length).abs() < 1e-6); +} + +/// When the art it measures is deleted or gets another number of anchors, a dimension stays where +/// it was, no longer linked: later edits of the art do not move it, and undo links it again. +#[test] +fn a_dimension_whose_art_changes_its_anchors_stays_where_it_was() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let before = recipe(&s, id); + let label = text(&s, id); + run(&mut s, "path.insertAnchor", json!({"id":rect,"segment":3,"t":0.5})); + let d = recipe(&s, id); + assert!(d.source.is_none(), "no longer linked"); + assert_eq!((d.a, d.b, d.offset, text(&s, id)), (before.a, before.b, before.offset, label.clone())); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.scale", json!({"sx":150,"sy":150})); + assert_eq!((recipe(&s, id).a, recipe(&s, id).b), (before.a, before.b), "does not follow the art"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, id).source, before.source, "undo links it again"); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "edit.clear", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, label)); +} + +/// A linked dimension whose art is reflected has its line on the reflected side: a line above the +/// top edge is below that edge's points after a flip top to bottom. +#[test] +fn a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side() { + use vectorcraft_doc::dimension::Orientation; + for orientation in ["aligned", "horizontal"] { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let at = anchors(&s, rect); + let top = |p: vectorcraft_geom::Point| (p.y - 100.0).abs() < 1e-9; + let (i, j) = (at.iter().position(|p| top(*p)).unwrap(), at.iter().rposition(|p| top(*p)).unwrap()); + let anchor = |anchor: usize| json!({"node":rect,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(i),"b":anchor(j)}); + // The line 30 pt above the top edge: the offset is along the left normal of a → b when + // aligned, downward when horizontal. + let offset = if orientation == "aligned" && at[i].x > at[j].x { 30.0 } else { -30.0 }; + let id = run(&mut s, "dimension.create", json!({"source":src,"orientation":orientation,"offset":offset}))["id"].as_u64().unwrap(); + let line_y = |s: &Session| recipe(s, id).line_ends().0.y; + assert!((line_y(&s) - 70.0).abs() < 1e-6, "{orientation}: {}", line_y(&s)); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal"})); + let d = recipe(&s, id); + assert!(d.source.is_some()); + assert!(((d.a.y, d.b.y) == (200.0, 200.0)), "{orientation}: {d:?}"); + assert!((line_y(&s) - 230.0).abs() < 1e-6, "{orientation}: line at {}", line_y(&s)); + let want = if orientation == "aligned" { Orientation::Aligned } else { Orientation::Horizontal }; + assert_eq!(d.orientation, want); + run(&mut s, "edit.undo", json!({})); + assert!((line_y(&s) - 70.0).abs() < 1e-6); + } +} + +/// Reflected across the line through the two points it measures, an arch keeps those points +/// where they were, and the dimension's line goes to the other side with the arch. +#[test] +fn a_dimension_of_art_reflected_across_its_points_changes_sides() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":curve,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":-30}))["id"].as_u64().unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 170.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + let d = recipe(&s, id); + assert_eq!((d.a, d.b), (vectorcraft_geom::Point::new(100.0, 200.0), vectorcraft_geom::Point::new(200.0, 200.0))); + assert!((d.line_ends().0.y - 230.0).abs() < 1e-6, "below with the arch: {:?}", d.line_ends()); + // Reflected together with the art, it ends in the same place. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids":[curve, id]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + assert!((recipe(&s, id).line_ends().0.y - 230.0).abs() < 1e-6, "{:?}", recipe(&s, id).line_ends()); +} + +/// A dimension between two paths that are each reflected in their own way in one edit is not +/// mirrored by the map of one of them. +#[test] +fn a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset() { + let mut s = session(); + let low = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let high = json!([{"x":300,"y":200,"out":[300,100]},{"x":400,"y":200,"in":[400,100]}]); + let first = run(&mut s, "path.create", json!({"anchors":low,"closed":false}))["id"].as_u64().unwrap(); + let second = run(&mut s, "path.create", json!({"anchors":high,"closed":false}))["id"].as_u64().unwrap(); + let src = json!({"kind":"points","a":{"node":first,"subpath":0,"anchor":0},"b":{"node":second,"subpath":0,"anchor":1}}); + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":30}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, second]})); + run(&mut s, "object.transformEach", json!({"reflectY":true})); + let d = recipe(&s, id); + assert!(d.source.is_some() && (d.a.y - d.b.y).abs() > 1.0, "{d:?}"); + assert!((d.offset - 30.0).abs() < 1e-6, "{d:?}"); +} + +/// A recipe's free points are checked: weights that do not add up to 1, or an end that is both an +/// anchor and a free point, are refused without changing the document. +#[test] +fn dimension_free_points_are_checked() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let original = serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + let w = |anchor: u64, weight: f64| json!({"subpath":0,"anchor":anchor,"weight":weight}); + let held = |anchors: Value, across: f64| json!({"kind":"anchors","node":rect,"anchors":anchors,"across":across}); + let on = |segment: u64, t: f64| json!({"kind":"onSegment","edge":{"node":rect,"subpath":0,"segment":segment},"t":t}); + let anchor = json!({"node":rect,"subpath":0,"anchor":0}); + for free in [ + held(json!([w(1, 0.5), w(2, 0.6)]), 0.0), + held(json!([w(1, 1.0)]), 0.0), + held(json!([w(1, 1e300), w(2, -1e300)]), 0.0), + held(json!([w(1, 0.5), w(99, 0.5)]), 0.0), + held(json!([w(1, 0.5), w(2, f64::MAX)]), 0.0), + held(json!([w(1, 0.5), w(2, 0.5)]), 1e300), + held(json!([w(1, 0.5), w(2, 0.25), w(3, 0.25)]), 0.5), + on(1, 1.5), + on(1, -0.1), + on(99, 0.5), + json!({"kind":"elsewhere","node":rect}), + ] { + let p = json!({"source":{"kind":"points","a":anchor,"freeB":free}}); + assert!(s.execute("dimension.create", &p).is_err(), "{p}"); + assert_eq!(serde_json::to_value(&*s.doc().unwrap().doc).unwrap(), original); + } + let both = json!({"source":{"kind":"points","a":anchor,"freeA":held(json!([w(1, 0.5), w(2, 0.5)]), 0.0),"b":anchor}}); + assert!(s.execute("dimension.create", &both).is_err()); + let at = anchors(&s, rect); + for (free, want) in [(held(json!([w(1, 0.5), w(2, 0.5)]), 0.0), at[1].midpoint(at[2])), (on(1, 0.5), at[1].midpoint(at[2]))] { + let ok = json!({"source":{"kind":"points","a":anchor,"freeB":free}}); + let id = run(&mut s, "dimension.create", ok)["id"].as_u64().unwrap(); + assert!(near(recipe(&s, id).b, want), "{:?}", recipe(&s, id).b); + } +} + +/// A point off a straight two-anchor line is held by its distance along and across the line: it +/// moves, turns and scales with the line. +#[test] +fn a_dimension_to_a_point_off_a_line_follows_the_line() { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":200,"y2":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (150.0, 160.0), (60.0, 130.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(line), NodeId(line)]), "{:?}", d.source); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"})); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.rotate", json!({"angle":90,"origin":[100,100]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":200,"origin":[100,100]})); + run(&mut s, "object.move", json!({"dx":10,"dy":20})); + let at = anchors(&s, line); + let (o, u) = (at[0], at[1] - at[0]); + // 50 along the line and 60 across it before, now in the line's new frame at twice the size. + let want = o + u * 0.5 + vectorcraft_geom::Vec2::new(-u.y, u.x) * 0.6; + let d = recipe(&s, id); + assert!(near(d.a, o) && near(d.b, want), "{d:?} want {want:?}"); + assert!((d.length - 2.0 * (50.0f64.hypot(60.0))).abs() < 1e-6); +} + +/// A point on a straight segment stays on the segment when its handles are edited into a curve. +#[test] +fn a_point_on_a_segment_stays_on_it_when_the_segment_curves() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let at = anchors(&s, rect); + assert!(near(at[1], vectorcraft_geom::Point::new(200.0, 100.0)) && near(at[2], vectorcraft_geom::Point::new(200.0, 200.0)), "{at:?}"); + let a = |p: vectorcraft_geom::Point| json!({"x":p.x,"y":p.y}); + let mut curved = vec![a(at[0]), a(at[1]), a(at[2]), a(at[3])]; + curved[1]["out"] = json!([240, 110]); + curved[2]["in"] = json!([240, 190]); + run(&mut s, "path.setAnchors", json!({"id":rect,"subpaths":[{"anchors":curved,"closed":true}]})); + let d = recipe(&s, id); + assert!(d.source.is_some(), "still linked"); + assert!(near(d.b, vectorcraft_geom::Point::new(230.0, 150.0)), "on the curve: {:?}", d.b); +} + +/// The line of a linked dimension of a curved two-anchor path goes to the reflected side when the +/// path is reflected: its handles tell a reflection from a turn. +#[test] +fn a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":curve,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + // The line 30 pt below the two points (the left normal of a → b points down). + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":30}))["id"].as_u64().unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 230.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"vertical"})); + let d = recipe(&s, id); + assert!((d.a.y, d.b.y) == (200.0, 200.0) && d.a.x > d.b.x, "{d:?}"); + assert!((d.line_ends().0.y - 230.0).abs() < 1e-6, "below the points: {:?}", d.line_ends()); + run(&mut s, "object.reflect", json!({"axis":"horizontal"})); + let d = recipe(&s, id); + assert!((d.line_ends().0.y - (d.a.y - 30.0)).abs() < 1e-6, "above the points: {d:?}"); +} + +/// A point off an arch, whose anchors lie on one line, is held against its anchors and handles: +/// it is reflected with the arch, to the same side as the dimension's line. +#[test] +fn a_point_off_an_arch_is_reflected_with_the_arch() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (150.0, 120.0), (60.0, 120.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 120.0)), "{:?}", d.b); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + let d = recipe(&s, id); + assert!(near(d.a, vectorcraft_geom::Point::new(100.0, 200.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 280.0)), "below with the arch: {:?}", d.b); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]})); + let d = recipe(&s, id); + assert!(near(d.a, vectorcraft_geom::Point::new(200.0, 200.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 120.0)), "above with the arch: {:?}", d.b); +} + +/// A point beside a curve that is almost straight is still held against it. +#[test] +fn a_point_beside_an_almost_straight_curve_follows_it() { + let mut s = session(); + let flat = json!([{"x":100,"y":200,"out":[100,199.999]},{"x":200,"y":200}]); + let curve = run(&mut s, "path.create", json!({"anchors":flat,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (150.0, 150.0), (60.0, 120.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + assert!(near(d.b, vectorcraft_geom::Point::new(190.0, 120.0)), "{:?}", d.b); +} + +/// A point off a loop whose two anchors are in one place is held against the loop's handles. +#[test] +fn a_point_off_a_loop_with_its_anchors_in_one_place_follows_it() { + let mut s = session(); + let tear = json!([{"x":100,"y":200,"out":[60,120]},{"x":100,"y":200,"in":[140,120]}]); + let curve = run(&mut s, "path.create", json!({"anchors":tear,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (100.0, 60.0), (30.0, 130.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + assert!(near(d.b, vectorcraft_geom::Point::new(140.0, 30.0)), "{:?}", d.b); +} + +/// Beside a straight two-anchor line, a point is moved by a reflection as a half turn would move +/// it: the line's positions alone do not tell the two apart. +#[test] +fn a_point_beside_a_reflected_line_moves_as_a_half_turn_would() { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":200,"y2":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (150.0, 160.0), (60.0, 130.0)]); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]})); + let d = recipe(&s, id); + assert!(d.source.is_some()); + assert!(near(d.a, vectorcraft_geom::Point::new(200.0, 100.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 40.0)), "{:?}", d.b); +} + +/// Opening a closed path that a dimension measures leaves the dimension where it was, no longer +/// linked, and undo links it again. +#[test] +fn a_dimension_whose_art_is_opened_stays_where_it_was() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let before = recipe(&s, id); + let label = text(&s, id); + let a = |p: vectorcraft_geom::Point| json!({"x":p.x,"y":p.y}); + let open: Vec = anchors(&s, rect).into_iter().map(a).collect(); + run(&mut s, "path.setAnchors", json!({"id":rect,"subpaths":[{"anchors":open,"closed":false}]})); + let d = recipe(&s, id); + assert!(d.source.is_none(), "no longer linked"); + assert_eq!((d.a, d.b, d.offset, text(&s, id)), (before.a, before.b, before.offset, label)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, id).source, before.source, "undo links it again"); +} + +/// An angle whose arm becomes a curve, and an arc radius whose arc stops being circular, stay where +/// they were, no longer linked. +#[test] +fn angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were() { + let mut s = session(); + let first = edge(&mut s); + let second = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":100,"y2":172}))["id"].as_u64().unwrap(); + let angle = json!({"mode":"angular","source":{"kind":"angle","first":{"node":first,"subpath":0,"segment":0},"second":{"node":second,"subpath":0,"segment":0}}}); + let id = run(&mut s, "dimension.create", angle)["id"].as_u64().unwrap(); + let label = text(&s, id); + let curved = json!([{"x":100,"y":100,"out":[140,130]},{"x":100,"y":172}]); + run(&mut s, "path.setAnchors", json!({"id":second,"subpaths":[{"anchors":curved,"closed":false}]})); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, label)); + let circle = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let arc = json!({"mode":"radius","source":{"kind":"arc","edge":{"node":circle,"subpath":0,"segment":0}},"options":{"units":"in","precision":1}}); + let id = run(&mut s, "dimension.create", arc)["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "1.0 in"); + run(&mut s, "select.set", json!({"ids":[circle]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":100})); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, "1.0 in".to_string())); +} + +/// Saved and opened again, a dimension to points that are not anchors still follows its art. +#[test] +fn free_points_survive_a_native_file() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(200.0, 150.0), (330.0, 260.0), (260.0, 330.0)]); + let before = recipe(&s, id); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + assert_eq!(recipe(&reopened, id).source, before.source); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&reopened, id); + let v = vectorcraft_geom::Vec2::new(40.0, -30.0); + assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); +} + +/// A linked dimension opened from a file with options it cannot be drawn with keeps its art, as a +/// plain group, when the art it measures is deleted. +#[test] +fn a_dimension_that_cannot_be_drawn_again_keeps_its_art() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 100.0), (150.0, 80.0)]); + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let mut v: Value = serde_json::from_slice(&saved).unwrap(); + fn bad_precision(v: &mut Value) { + match v { + Value::Object(m) => { + if let Some(Value::Object(o)) = m.get_mut("dimension").and_then(|d| d.get_mut("options")) { + o.insert("precision".into(), json!(99)); + } + m.values_mut().for_each(bad_precision); + } + Value::Array(a) => a.iter_mut().for_each(bad_precision), + _ => {} + } + } + bad_precision(&mut v); + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&serde_json::to_vec(&v).unwrap()).unwrap(), None); + let art = reopened.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().clone(); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "edit.clear", json!({})); + let n = reopened.doc().unwrap().doc.node(NodeId(id)).cloned().expect("the dimension's art stays"); + assert!(n.extras().dimension.is_none(), "no longer a live dimension"); + assert_eq!(n.children().unwrap(), &art); +} + /// A linked dimension moved on its own keeps its new place when its art changes later; moved with /// its art, it keeps its distance from it. #[test] @@ -653,7 +1074,8 @@ fn an_expanded_dimension_stays_plain_art() { assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); run(&mut s, "edit.clear", json!({})); assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); - assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none()); + assert_eq!(text(&s, other), "20.00 in", "the live dimension stays, no longer linked"); + assert!(recipe(&s, other).source.is_none()); // Saved and opened again, it is still plain art. let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); let mut reopened = Session::new(); @@ -975,7 +1397,9 @@ fn dimension_linked_angle_and_circle_update_and_reject_non_circles() { run(&mut s, "object.scale", json!({"sx":200,"sy":200})); assert_eq!(text(&s, id), "4 in"); run(&mut s, "object.scale", json!({"sx":200,"sy":100})); - assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none()); + // An ellipse has no single radius: the dimension stays where it was, no longer linked. + assert_eq!(text(&s, id), "4 in"); + assert!(recipe(&s, id).source.is_none()); assert!(s.execute("dimension.create", &json!({"mode":"radius","source":{"kind":"circle","node":circle}})).is_err()); } diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d132273698..7a3d3de765 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -5,8 +5,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use serde_json::{Value, json}; use vectorcraft_doc::{ - Node, - dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, Orientation, PointRef, SegmentRef}, + Node, NodeId, + dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, FreePoint, Orientation, PointRef, SegmentRef}, }; use vectorcraft_geom::{BezPath, Point, Vec2}; @@ -213,6 +213,30 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { (q.x.is_finite() && q.y.is_finite()).then_some(q) } +/// What a dimension between two picked points links to. A point on an anchor links to the anchor. +/// A point on a segment keeps its place along the segment. Any other point is held +/// against the anchors of the path under it, or, with no path under it, the path of the other +/// point, so that it moves with that path. None when neither point has a path to link to. +fn points_source(cx: &ToolContext, (a, ra): (Point, &Option), (b, rb): (Point, &Option)) -> Option { + let (edge_a, edge_b) = (pick(cx, a), pick(cx, b)); + let node = |r: &Option, e: &Option| r.as_ref().map(|r| r.node).or_else(|| e.as_ref().map(|e| e.node)); + let (path_a, path_b) = (node(ra, &edge_a), node(rb, &edge_b)); + let free = |p: Point, r: &Option, edge: &Option, own: Option, other: Option| { + if r.is_some() { + return None; + } + edge.as_ref().and_then(|e| FreePoint::on_segment(cx.doc, e, p)).or_else(|| own.or(other).and_then(|node| FreePoint::on(cx.doc, node, p))) + }; + let (free_a, free_b) = (free(a, ra, &edge_a, path_a, path_b), free(b, rb, &edge_b, path_b, path_a)); + (ra.is_some() || rb.is_some() || free_a.is_some() || free_b.is_some()).then(|| DimensionSource::Points { + a: ra.clone(), + b: rb.clone(), + vertex: None, + free_a, + free_b, + }) +} + impl DimensionTool { /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as /// a link to its path); else where Smart Guides put it (another object's anchor or centre, in @@ -364,7 +388,7 @@ impl DimensionTool { } self.points.push((at, reference)); if let [(a, ra), (b, rb)] = self.points.as_slice() { - let source = (ra.is_some() || rb.is_some()).then(|| DimensionSource::Points { a: ra.clone(), b: rb.clone(), vertex: None }); + let source = points_source(cx, (*a, ra), (*b, rb)); let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { self.second = Some((*b, p)); @@ -667,7 +691,7 @@ mod tests { let d = t.pending.as_ref().expect("both anchors were picked"); assert_eq!((d.a, d.b), (Point::new(100.0, 100.0), Point::new(200.0, 200.0))); let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor }); - assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None })); + assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None, free_a: None, free_b: None })); // Dragged past the anchor's reach, the press drags out the dimension of a segment there. let mut t = DimensionTool::default(); t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); @@ -677,6 +701,66 @@ mod tests { assert!(matches!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 60.0)).last(), Some(Action::Commit))); } + /// A point picked on a segment, not on an anchor, keeps its place along the segment. A point + /// off the art is held against the anchors of the other point's path. Both then follow the + /// path, as the anchor at the other end does. + #[test] + fn points_off_anchors_are_held_against_the_path() { + use vectorcraft_doc::dimension::FreePoint; + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let click = |t: &mut DimensionTool, x: f64, y: f64| { + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y)); + }; + let mut t = DimensionTool::default(); + click(&mut t, 100.0, 100.0); + click(&mut t, 200.0, 150.0); + let pending = t.pending.as_ref().expect("both points were picked"); + let anchor = Some(PointRef { node: id, subpath: 0, anchor: 0 }); + let Some(DimensionSource::Points { a, b: None, vertex: None, free_a: None, free_b: Some(FreePoint::OnSegment { edge, t }) }) = + &pending.source + else { + panic!("{:?}", pending.source) + }; + assert_eq!((a, edge), (&anchor, &SegmentRef { node: id, subpath: 0, segment: 1 })); + assert!((t - 0.5).abs() < 1e-9, "{t}"); + let mut t = DimensionTool::default(); + click(&mut t, 400.0, 400.0); + click(&mut t, 200.0, 200.0); + let pending = t.pending.as_ref().expect("both points were picked"); + let Some(DimensionSource::Points { free_a: Some(free), b: Some(b), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + let FreePoint::Anchors { node, anchors, across } = free else { panic!("{free:?}") }; + assert_eq!((*node, anchors.len(), *across, b.node, b.anchor), (id, 3, 0.0, id, 2)); + let at = free.position(&d).expect("the anchors that hold it exist"); + assert!(at.distance(pending.a) < 1e-9, "{at:?} {:?}", pending.a); + } + + /// A point that Smart Guides put in line with the path's center is held, where the guide put + /// it, against the anchors of the path at the other end. + #[test] + fn a_point_smart_guides_place_is_held_against_the_path() { + use vectorcraft_doc::dimension::FreePoint; + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + assert!(c.smart_guides); + let mut t = DimensionTool::default(); + for (x, y) in [(200.0, 200.0), (151.5, 330.0)] { + t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y)); + } + let pending = t.pending.as_ref().expect("both points were picked"); + assert!((pending.b.x - 150.0).abs() < 1e-9, "in line with the center: {:?}", pending.b); + let Some(DimensionSource::Points { a: Some(a), free_b: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}"); + assert_eq!(a.node, id); + let at = free.position(&d).expect("the anchors that hold it exist"); + assert!(at.distance(pending.b) < 1e-9, "{at:?} {:?}", pending.b); + } + /// The anchors of a live rectangle are picked the same way. #[test] fn a_press_on_a_live_shapes_anchor_picks_it() { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 4ac5d5dd66..a438b240ea 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5535,6 +5535,7 @@ theme Appearance Външен вид @msg Invalid drawing scale Невалиден мащаб на чертежа @msg Invalid real scale Невалиден реален мащаб @msg Measured anchor no longer exists Измерената опорна точка вече не съществува +@msg Invalid measured point Невалидна измерена точка @msg Measured segment no longer exists Измереният сегмент вече не съществува @msg Non-finite dimension Размерът не е крайно число @msg Only linear dimensions are horizontal or vertical Само линейните размери са хоризонтални или вертикални diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index aa76735421..d88c223240 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5583,6 +5583,7 @@ mark-style Japanese Japanski @msg Invalid drawing scale Nevažeća skala crteža @msg Invalid real scale Nevažeća stvarna skala @msg Measured anchor no longer exists Izmjereno sidro više ne postoji +@msg Invalid measured point Neispravna izmjerena tačka @msg Measured segment no longer exists Izmjereni segment više ne postoji @msg Non-finite dimension Nekonačna kota @msg Only linear dimensions are horizontal or vertical Samo linearne kote su horizontalne ili vertikalne diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f14cc12c44..d0ee71c659 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5360,6 +5360,7 @@ digits Malayalam Malaiàlam @msg Make Guides: select paths Crea guies: seleccioneu traçats @msg mask art ends outside a mask dictionary l’art de la màscara acaba fora d’un diccionari de màscara @msg Measured anchor no longer exists El punt d’ancoratge mesurat ja no existeix +@msg Invalid measured point El punt mesurat no és vàlid @msg Measured segment no longer exists El segment mesurat ja no existeix @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (vegeu plugin.list) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9f2e06fd11..9f80a397cc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5714,6 +5714,7 @@ mark-style Japanese Japonské @msg Invalid drawing scale Neplatné měřítko výkresu @msg Invalid real scale Neplatné skutečné měřítko @msg Measured anchor no longer exists Měřený kotevní bod už neexistuje +@msg Invalid measured point Neplatný měřený bod @msg Measured segment no longer exists Měřený segment už neexistuje @msg Non-finite dimension Kóta není konečné číslo @msg Only linear dimensions are horizontal or vertical Vodorovné nebo svislé jsou jen lineární kóty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 577f4d1ee4..af4ac9b0ae 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5305,6 +5305,7 @@ mark-style Japanese Japansk @msg Invalid drawing scale Ugyldig tegningsmålestok @msg Invalid real scale Ugyldig virkelig målestok @msg Measured anchor no longer exists Det målte ankerpunkt findes ikke længere +@msg Invalid measured point Ugyldigt målt punkt @msg Measured segment no longer exists Det målte segment findes ikke længere @msg Non-finite dimension Ikke-endeligt mål @msg Only linear dimensions are horizontal or vertical Kun lineære mål er vandrette eller lodrette diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index cd44eba7dc..c0d48f2e9a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5291,6 +5291,7 @@ effect Soft Weich @msg Invalid drawing scale Ungültiger Zeichnungsmaßstab @msg Invalid real scale Ungültiger realer Maßstab @msg Measured anchor no longer exists Der gemessene Ankerpunkt existiert nicht mehr +@msg Invalid measured point Ungültiger gemessener Punkt @msg Measured segment no longer exists Das gemessene Segment existiert nicht mehr @msg Non-finite dimension Die Bemaßung ist keine endliche Zahl @msg Only linear dimensions are horizontal or vertical Nur lineare Bemaßungen sind horizontal oder vertikal diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e9d8df097d..49f9523656 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5669,6 +5669,7 @@ effect Points Σημεία @msg Invalid drawing scale Μη έγκυρη κλίμακα σχεδίου @msg Invalid real scale Μη έγκυρη πραγματική κλίμακα @msg Measured anchor no longer exists Το μετρημένο σημείο αγκύρωσης δεν υπάρχει πλέον +@msg Invalid measured point Μη έγκυρο μετρημένο σημείο @msg Measured segment no longer exists Το μετρημένο τμήμα δεν υπάρχει πλέον @msg Non-finite dimension Η διάσταση δεν είναι πεπερασμένος αριθμός @msg Only linear dimensions are horizontal or vertical Μόνο οι γραμμικές διαστάσεις είναι οριζόντιες ή κατακόρυφες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 148c48fd52..8f8b5e17e7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5655,6 +5655,7 @@ mark-style Japanese Japonesas @msg Invalid drawing scale Escala de dibujo no válida @msg Invalid real scale Escala real no válida @msg Measured anchor no longer exists El punto de ancla medido ya no existe +@msg Invalid measured point Punto medido no válido @msg Measured segment no longer exists El segmento medido ya no existe @msg Non-finite dimension Cota no finita @msg Only linear dimensions are horizontal or vertical Solo las cotas lineales son horizontales o verticales diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 4fe1a150d1..d86f68b4fc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5681,6 +5681,7 @@ mark-style Japanese Japanilainen @msg Invalid drawing scale Virheellinen piirustuksen mittakaava @msg Invalid real scale Virheellinen todellinen mittakaava @msg Measured anchor no longer exists Mitattua ankkuripistettä ei ole enää +@msg Invalid measured point Virheellinen mitattu piste @msg Measured segment no longer exists Mitattua segmenttiä ei ole enää @msg Non-finite dimension Mitta ei ole äärellinen luku @msg Only linear dimensions are horizontal or vertical Vain lineaariset mitat ovat vaaka- tai pystysuuntaisia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index fc07cea935..933e02b953 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5709,6 +5709,7 @@ theme Appearance Apparence @msg Invalid drawing scale Échelle du dessin non valide @msg Invalid real scale Échelle réelle non valide @msg Measured anchor no longer exists Le point d’ancrage mesuré n’existe plus +@msg Invalid measured point Point mesuré non valide @msg Measured segment no longer exists Le segment mesuré n’existe plus @msg Non-finite dimension Cote non finie @msg Only linear dimensions are horizontal or vertical Seules les cotes linéaires sont horizontales ou verticales diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6ef0b56668..06f8f25dcc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6612,6 +6612,7 @@ antiAlias Sharp शार्प @msg matrix must be finite and invertible, depth finite matrix: मैट्रिक्स को परिमित और उलटा, गहराई परिमित होना चाहिए @msg matte: {e} मैट: {e} @msg Measured anchor no longer exists मापने वाला एंकर अब मौजूद नहीं है +@msg Invalid measured point मापा गया बिंदु अमान्य है @msg Measured segment no longer exists मापदंड अब मौजूद नहीं है @msg member is for order front, forward, backward or back member केवल order front, forward, backward या back के लिए है @msg memory budget (the selection is too large to hand over) स्मृति बजट (चुनाव बहुत बड़ा है) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87a745a439..af7810f02b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5696,6 +5696,7 @@ imageTrace Outline Körvonal @msg Invalid drawing scale Érvénytelen rajzlépték @msg Invalid real scale Érvénytelen valós lépték @msg Measured anchor no longer exists A mért horgonypont már nem létezik +@msg Invalid measured point Érvénytelen mért pont @msg Measured segment no longer exists A mért szakasz már nem létezik @msg Non-finite dimension Nem véges méret @msg Only linear dimensions are horizontal or vertical Csak a lineáris méretek lehetnek vízszintesek vagy függőlegesek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2da754164b..e1170943b9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5305,6 +5305,7 @@ mark-style Japanese Jepang @msg Invalid drawing scale Skala gambar tidak valid @msg Invalid real scale Skala sebenarnya tidak valid @msg Measured anchor no longer exists Titik jangkar yang diukur sudah tidak ada +@msg Invalid measured point Titik yang diukur tidak valid @msg Measured segment no longer exists Segmen yang diukur sudah tidak ada @msg Non-finite dimension Dimensi bukan bilangan berhingga @msg Only linear dimensions are horizontal or vertical Hanya dimensi linear yang horizontal atau vertikal diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 89e3c7dc22..bb0650e8c3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5326,6 +5326,7 @@ lighting Light Luce @msg Invalid drawing scale Scala del disegno non valida @msg Invalid real scale Scala reale non valida @msg Measured anchor no longer exists Il punto di ancoraggio misurato non esiste più +@msg Invalid measured point Punto misurato non valido @msg Measured segment no longer exists Il segmento misurato non esiste più @msg Non-finite dimension Quota non finita @msg Only linear dimensions are horizontal or vertical Solo le quote lineari sono orizzontali o verticali diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5f62b25c09..f8b0e6ab4a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5369,6 +5369,7 @@ lighting Light ライト @msg Invalid drawing scale 図面の縮尺が無効です @msg Invalid real scale 実寸の縮尺が無効です @msg Measured anchor no longer exists 測定したアンカーポイントはもう存在しません +@msg Invalid measured point 測定した点が無効です @msg Measured segment no longer exists 測定したセグメントはもう存在しません @msg Non-finite dimension 寸法が有限ではありません @msg Only linear dimensions are horizontal or vertical 水平または垂直にできるのは直線寸法のみです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1cec04df12..62a6512326 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5320,6 +5320,7 @@ imageTrace Outline კონტური @msg Invalid drawing scale ნახაზის არასწორი მასშტაბი @msg Invalid real scale რეალური ზომის არასწორი მასშტაბი @msg Measured anchor no longer exists გაზომილი საყრდენი წერტილი აღარ არსებობს +@msg Invalid measured point გაზომილი წერტილი არასწორია @msg Measured segment no longer exists გაზომილი სეგმენტი აღარ არსებობს @msg Non-finite dimension ზომა სასრული რიცხვი არ არის @msg Only linear dimensions are horizontal or vertical მხოლოდ ხაზოვანი ზომებია ჰორიზონტალური ან ვერტიკალური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b3bdd0c361..318df7a4f2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5287,6 +5287,7 @@ lighting Light 광원 @msg Invalid drawing scale 잘못된 도면 축척 @msg Invalid real scale 잘못된 실제 축척 @msg Measured anchor no longer exists 측정한 고정점이 더 이상 없습니다 +@msg Invalid measured point 측정한 점이 잘못되었습니다 @msg Measured segment no longer exists 측정한 세그먼트가 더 이상 없습니다 @msg Non-finite dimension 유한하지 않은 치수 @msg Only linear dimensions are horizontal or vertical 선형 치수만 가로 또는 세로로 지정할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3359ff99b3..9ffc7e1749 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5317,6 +5317,7 @@ mark-style Japanese Japans @msg Invalid drawing scale Ongeldige tekeningsschaal @msg Invalid real scale Ongeldige werkelijke schaal @msg Measured anchor no longer exists Gemeten ankerpunt bestaat niet meer +@msg Invalid measured point Ongeldig gemeten punt @msg Measured segment no longer exists Gemeten segment bestaat niet meer @msg Non-finite dimension Niet-eindige maatlijn @msg Only linear dimensions are horizontal or vertical Alleen lineaire maatlijnen zijn horizontaal of verticaal diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d43c83a0a1..b0c3f12d68 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5566,6 +5566,7 @@ mark-style Japanese Japońskie @msg Invalid drawing scale Nieprawidłowa skala rysunku @msg Invalid real scale Nieprawidłowa skala rzeczywista @msg Measured anchor no longer exists Mierzony punkt kontrolny już nie istnieje +@msg Invalid measured point Nieprawidłowy mierzony punkt @msg Measured segment no longer exists Mierzony odcinek już nie istnieje @msg Non-finite dimension Wymiar nie jest liczbą skończoną @msg Only linear dimensions are horizontal or vertical Tylko wymiary liniowe są poziome lub pionowe diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9117394f7e..6eb8eb5212 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5645,6 +5645,7 @@ mark-style Japanese Japonesas @msg Invalid drawing scale Escala de desenho inválida @msg Invalid real scale Escala real inválida @msg Measured anchor no longer exists O ponto de ancoragem medido não existe mais +@msg Invalid measured point Ponto medido inválido @msg Measured segment no longer exists O segmento medido não existe mais @msg Non-finite dimension Cota não finita @msg Only linear dimensions are horizontal or vertical Somente cotas lineares são horizontais ou verticais diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cef9bafd20..87f497f96a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5320,6 +5320,7 @@ lighting Light Свет @msg Invalid drawing scale Недопустимый масштаб чертежа @msg Invalid real scale Недопустимый реальный масштаб @msg Measured anchor no longer exists Измеряемая опорная точка больше не существует +@msg Invalid measured point Недопустимая измеряемая точка @msg Measured segment no longer exists Измеряемый сегмент больше не существует @msg Non-finite dimension Размер не является конечным числом @msg Only linear dimensions are horizontal or vertical Только линейные размеры бывают горизонтальными или вертикальными diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1fdf7ce255..2bc44ef31d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5673,6 +5673,7 @@ theme Appearance Utseende @msg Invalid drawing scale Ogiltig ritningsskala @msg Invalid real scale Ogiltig verklig skala @msg Measured anchor no longer exists Den mätta ankarpunkten finns inte längre +@msg Invalid measured point Ogiltig mätt punkt @msg Measured segment no longer exists Det mätta segmentet finns inte längre @msg Non-finite dimension Måttet är inte ett ändligt tal @msg Only linear dimensions are horizontal or vertical Endast linjära mått är vågräta eller lodräta diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 91e2b3a4bd..050e7c05d2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5394,6 +5394,7 @@ theme Appearance Görünüm @msg Invalid drawing scale Geçersiz çizim ölçeği @msg Invalid real scale Geçersiz gerçek ölçek @msg Measured anchor no longer exists Ölçülen çapa artık mevcut değil +@msg Invalid measured point Geçersiz ölçülen nokta @msg Measured segment no longer exists Ölçülen segment artık mevcut değil @msg Non-finite dimension Sonlu olmayan boyut @msg Only linear dimensions are horizontal or vertical Yalnızca doğrusal boyutlar yatay veya dikey olabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5eb9f255fc..f4c4f6ee86 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5306,6 +5306,7 @@ lighting Light Світло @msg Invalid drawing scale Неприпустимий масштаб креслення @msg Invalid real scale Неприпустимий реальний масштаб @msg Measured anchor no longer exists Виміряна опорна точка більше не існує +@msg Invalid measured point Недійсна виміряна точка @msg Measured segment no longer exists Виміряний сегмент більше не існує @msg Non-finite dimension Розмір не є скінченним числом @msg Only linear dimensions are horizontal or vertical Лише лінійні розміри бувають горизонтальними або вертикальними diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1c17d61e65..0dda56d3de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5307,6 +5307,7 @@ theme Appearance Giao diện @msg Invalid drawing scale Tỷ lệ bản vẽ không hợp lệ @msg Invalid real scale Tỷ lệ thực không hợp lệ @msg Measured anchor no longer exists Điểm neo được đo không còn tồn tại +@msg Invalid measured point Điểm được đo không hợp lệ @msg Measured segment no longer exists Đoạn được đo không còn tồn tại @msg Non-finite dimension Kích thước không phải là số hữu hạn @msg Only linear dimensions are horizontal or vertical Chỉ kích thước tuyến tính mới nằm ngang hoặc thẳng đứng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5c0c35240c..f6e3c9c140 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4757,6 +4757,7 @@ imageTrace Outline 轮廓 @msg Invalid drawing scale 图纸比例无效 @msg Invalid real scale 实际比例无效 @msg Measured anchor no longer exists 测量锚点已不存在 +@msg Invalid measured point 测量点无效 @msg Measured segment no longer exists 测量线段已不存在 @msg Non-finite dimension 尺寸标注不是有限值 @msg Only linear dimensions are horizontal or vertical 只有线性尺寸可以是水平或垂直的 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b538cb9d32..a02e03cc29 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2589,6 +2589,7 @@ file-filter Templates 範本 @msg Invalid drawing scale 圖紙比例無效 @msg Invalid real scale 實際比例無效 @msg Measured anchor no longer exists 測量的錨點已不存在 +@msg Invalid measured point 測量點無效 @msg Measured segment no longer exists 測量的線段已不存在 @msg Non-finite dimension 尺寸標註不是有限值 @msg Only linear dimensions are horizontal or vertical 只有線性尺寸可以是水平或垂直的 diff --git a/docs/dimensions.md b/docs/dimensions.md index 6327c9f501..bcd08c3b83 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -6,7 +6,13 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers - **Linear:** hover a path segment and drag outwards: releasing places the dimension. Or click two points (anchors snap, Shift constrains to 45°), then click to place. A click within 8 pixels of an anchor of any path, in groups and compound paths too, takes that anchor, and the dimension - stays linked to it. A press on an anchor picks it when the pointer moves less than 8 pixels + stays linked to it. A point on a segment stays at its place along the segment, also when the + segment's anchors or handles are edited. Any other point is linked to the path under it, or, + with no path under it, to the path at the other end, and moves, scales, turns and reflects with + that path. Beside a path whose anchors and handles all lie on one line, such as a straight line, + the point keeps its distance along and across the path: a reflection moves it as a half turn + does, and a scale that is not uniform changes its distance across the path in proportion to the + path's length. A press on an anchor picks it when the pointer moves less than 8 pixels before the release; a longer drag drags out the dimension of the segment under the pointer. A curved segment is measured from end to end. With Smart Guides on, both points also snap into line with other objects' anchors and centres, and the second onto the construction guides through the first; the guides @@ -52,10 +58,15 @@ position and alignment; changing one changes that dimension. **Apply to All** gi dimension in the document its style; **Set as Default** makes it the style of new dimensions. Measurements follow the art they measure through moves, scaling and anchor and handle edits, -undo and redo included. Deleting the art, or changing its number of anchors or whether it is -closed, removes its dimensions in the same undo step rather than attaching them to a different -edge. A linked dimension moved on its own stays where it was dropped (its distance from the art -changes); moved together with its art, it keeps its distance. +undo and redo included. When the art is reflected, the line of a linked linear dimension goes to +the reflected side, as far past the outermost point as before. This does not happen for art whose +anchors and handles all lie on one line, such as a straight line, which a half turn puts in the +same place as a reflection. Deleting the art, changing its number of anchors or whether it is +closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular +leaves its dimensions where they were, no longer linked, in the same undo step, rather than +attaching them to a different edge. Undo links them again. A linked dimension moved on its own +stays where it was dropped (its distance from the art changes); moved together with its art, it +keeps its distance. Native `.vectorcraft` files keep the recipes and links. SVG, PDF and bitmap output contain ordinary paths and text, so exported dimensions look the same. Ungrouping a dimension leaves its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc6e7a73a5..70c415cffc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -565,6 +565,7 @@ since 2026-10-01. **Drawing tools — Polygon and Star counts:** The existing canvas placement dialog reads the stored count and saves it only after successful placement. `polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs` covers both tools, repeated drags, tool switching, reopening and Cancel. Counts remain session tool options. Existing click and toolbar gestures are retained; no score or hour change. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. +**Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. From eaaf1155a858a119dbd8d9a18b0359401a55f866 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:35:47 -0800 Subject: [PATCH 23/83] Render: node renders and thumbnails follow the supersample and precise options render_node_with and render_node_thumbnail_with ignored RenderOptions::supersample and RenderOptions::precise, so the Asset Export tiles, which ask for both, were drawn with the canvas's shape-by-shape edges and the fast render mode instead of the export's look. A node render now supersamples Art Optimized edges as a page render does, and picks the quality render mode when precise is set, for the art's offscreen groups too. --- crates/render/src/renderer.rs | 83 ++++++++++++++++++++++------------- crates/render/src/tests.rs | 37 ++++++++++++++++ 2 files changed, 90 insertions(+), 30 deletions(-) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index a5bfcbf26e..7e67cc7b23 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -258,8 +258,7 @@ impl Renderer { }; // `reset` keeps the threshold of the previous render: set it every time. ctx.set_aliasing_threshold(opts.anti_alias.threshold()); - let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; - self.raster = vello_cpu::RasterizerSettings { render_mode, ..Default::default() }; + self.raster = raster_settings(opts); if opts.artboards && !opts.outline { // Paper: white on screen, no ink on the ink planes. ctx.set_transform(f.view); @@ -358,20 +357,59 @@ impl Renderer { pub fn render_node_with(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option { self.check_plugins(doc); self.check_symbols(doc); - let inv = view.inverse(); - let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let pixels = self.node_pixels(doc, n, (w, h), view, visible, opts, false, 1); + Some(Rendered { width: w as u32, height: h as u32, pixels }) + } + + /// Node `n` drawn into `w`×`h` transparent pixels through `view`, culled to `visible` (document + /// space); `forced` draws it whatever its visibility and bounds. With [`RenderOptions::supersample`] + /// and Art Optimized edges the art is drawn with hard edges at several times the size and + /// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page + /// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`]. + #[allow(clippy::too_many_arguments)] + fn node_pixels( + &mut self, + doc: &Document, + n: &Arc, + (w, h): (u16, u16), + view: Affine, + visible: Rect, + opts: &RenderOptions, + forced: bool, + cell: u32, + ) -> Vec { + if opts.supersample + && opts.anti_alias == AntiAlias::Art + && let Some(k) = supersample_factor(u32::from(w), u32::from(h)) + { + let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; + // `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16. + let (bw, bh) = (u32::from(w) * k, u32::from(h) * k); + let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); + let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k); + self.hairline = hairline; + return downsample(&big, bw as usize, bh as usize, k as usize); + } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output: view, plates: None }; + let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; + let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); - self.draw_arc(&mut ctx, &frame, n); - let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); + if forced { + self.draw_forced_arc(&mut ctx, &frame, n); + } else { + self.draw_arc(&mut ctx, &frame, n); + } + let pm = self.finish(&mut ctx, self.raster); self.end_frame(); - Some(Rendered { width: w as u32, height: h as u32, pixels: pm.data_as_u8_slice().to_vec() }) + self.raster = raster; + pm.data_as_u8_slice().to_vec() } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into @@ -402,28 +440,7 @@ impl Renderer { // A 1-pixel margin on each side, unless the thumbnail is too small to keep one. let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); - let mut ctx = single_threaded_context(w, w); - ctx.set_aliasing_threshold(opts.anti_alias.threshold()); - let symbols = doc.symbol_boxes().quick(); - let frame = Frame { - mt: false, - doc, - symbols: &symbols, - view, - visible: b.inflate(1.0, 1.0), - px: 1.0 / s, - opts, - ink: Ink::Display, - output: view, - plates: None, - }; - self.begin_frame(); - (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); - self.clip_paths.clear(); - self.draw_forced_arc(&mut ctx, &frame, &Arc::new(n.clone())); - let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); - self.end_frame(); - let mut pixels = pm.data_as_u8_slice().to_vec(); + let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1); if let Some(bg) = background { over_background(&mut pixels, bg); } @@ -431,6 +448,12 @@ impl Renderer { } } +/// The rasterizer settings for `opts`: the quality render mode when [`RenderOptions::precise`] is set. +fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings { + let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; + vello_cpu::RasterizerSettings { render_mode, ..Default::default() } +} + /// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight). pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) { let alpha = u32::from(a); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index a12e79e867..dd7198d531 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -952,6 +952,43 @@ fn node_renders_follow_the_anti_alias_option() { assert!(drawn(&thumb) && !partial(&thumb), "render_node_thumbnail_with: every alpha is 0 or 255"); } +/// Node renders follow `supersample` and `precise` as a page render does: two rectangles that meet +/// at x = 50.37 leave no seam when supersampled, and a node render gives the pixels of a page +/// render of the same art with the same options. +#[test] +fn node_renders_follow_the_supersample_and_precise_options() { + let mut d = Document::new(100.0, 100.0); + let left = rect_node(&mut d, Rect::new(10.0, 10.0, 50.37, 90.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + let right = rect_node(&mut d, Rect::new(50.37, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.2, 0.6, 0.9)), Paint::None, 0.0); + // Blended at half opacity over both, so the group composites offscreen. + let mut over = rect_node(&mut d, Rect::new(30.0, 60.0, 70.0, 80.0), Paint::solid(Color::rgb(0.9, 0.7, 0.1)), Paint::None, 0.0); + over.opacity = 0.5; + over.blend = vectorcraft_color::BlendMode::Multiply; + let group = Node::group(d.alloc_id(), vec![Arc::new(left), Arc::new(right), Arc::new(over)]); + let l = d.layers[0].id; + d.insert(Some(l), 0, group.clone()).unwrap(); + let node = Arc::new(group.clone()); + let page = |opts: &RenderOptions| RenderOptions { background: None, artboards: false, ..opts.clone() }; + let mut r = Renderer::new(); + for (supersample, precise) in [(false, false), (true, false), (false, true), (true, true)] { + let opts = RenderOptions { supersample, precise, ..Default::default() }; + let case = format!("supersample {supersample}, precise {precise}"); + let img = r.render_node_with(&d, &node, 100, 100, Affine::IDENTITY, &opts).unwrap(); + let whole = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &page(&opts)); + assert!(img.pixels == whole.pixels, "{case}: render_node_with draws as a page render does"); + // Pixel column 50 at row 50: the black rectangle covers 37% of it and the blue one the rest. + let seam = img.pixels[(50 * 100 + 50) * 4 + 3]; + assert_eq!(seam == 255, supersample, "{case}: render_node_with seam alpha {seam}"); + // A 37-pixel thumbnail draws 0.4375 pixels a point, the seam at x = 18.66. + let thumb = r.render_node_thumbnail_with(&d, &group, 37, None, &opts).unwrap(); + let view = Affine::translate((18.5, 18.5)) * Affine::scale(0.4375) * Affine::translate((-50.0, -50.0)); + let whole = Renderer::new().render(&d, 37, 37, view, &page(&opts)); + assert!(thumb.pixels == whole.pixels, "{case}: the thumbnail draws as a page render does"); + let seam = thumb.pixels[(18 * 37 + 18) * 4 + 3]; + assert_eq!(seam == 255, supersample, "{case}: thumbnail seam alpha {seam}"); + } +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; From f8307b19cde0cb71648d2b7a04fc4676355321d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:36:30 -0800 Subject: [PATCH 24/83] Type: on a vertical path, letters lie a quarter turn clockwise from upright glyphs, in a column centered on the path Follows #5557. Letters and digits lying on their side in vertical type on a path kept their top toward the path's end, opposite the upright glyphs. They are now set as horizontal type on the path sets them: baseline along the path, top to the path's left, a quarter turn clockwise from upright glyphs (CSS Writing Modes 3, Unicode UAX #50). - The column is centered on the path: upright glyphs, letters on their side and tate-chu-yoko blocks have their em box centers on the path line instead of a column one em wide to the path's right. - Upright glyphs are turned in the path effect's glyph space, so with Skew on a curve their top runs back along the tangent and their x axis stays up the page, as letters keep theirs. - Tate-chu-yoko blocks on a path stand upright, stay whole on a curve and move by Tate-chu-yoko Settings toward the path's start and left. - A tate-chu-yoko block of mixed sizes sets every glyph in its first character's em, on a path and off it. Existing vertical type on a path redraws with these placements. --- crates/text/src/layout.rs | 94 ++++++++-- crates/text/src/layout/driver.rs | 1 + crates/text/src/layout/wrapping_tests.rs | 1 + crates/text/src/tests/ligature_carets.rs | 10 +- crates/text/src/tests/vertical.rs | 214 +++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 6 files changed, 299 insertions(+), 23 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 8e594c0369..4a92c4ed34 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -137,6 +137,10 @@ struct Ctx<'a> { /// next glyph of its cluster would take, the turn it got, the line-space x that next glyph is /// set after), so that a combining mark shaped into the same cluster turns with it. upright_cluster: Option<(usize, usize, Affine, f64)>, + /// Vertical type on a path: the tate-chu-yoko block [`Self::emit`] is placing, as (the + /// block's transform from its first glyph's place on the path, the center of its em in the + /// column before that transform), so that the block's other glyphs stand with it on a curve. + tcy_block: Option<(Affine, Point)>, out: TextLayout, } @@ -365,28 +369,82 @@ impl Ctx<'_> { let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance) / g.sy; (cell + proportional, top) }); - if self.vertical && self.on_path { - // Vertical path type keeps the baseline path and turns each glyph across it. - m = Affine::rotate_about(std::f64::consts::FRAC_PI_2, origin) * m; - if let Some((cell, top)) = path_cell { - // An upright glyph whose top then faces the path's end turns half a turn about the - // center of its cell (without its Character Rotation), so that its top faces the - // path's start and the characters of an upright ligature read along the path in - // order. The effects that keep the glyph's up direction fixed already turn it so on - // a path that runs to the left. - let turned = m * unturned; - let tangent = Vec2::new(angle.cos(), angle.sin()); - let along = |y: f64| (turned * Point::new(0.0, y) - origin).dot(tangent); - if along(-top) > along(cell - top) { - let centre = turned * Point::new(g.face.advance(g.gid) * 0.5, cell * 0.5 - top); - m = Affine::translate(centre.to_vec2() * 2.0) * Affine::scale(-1.0) * m; + // Vertical type on a path: the column is centered on the line Align to Path puts the baseline + // on, so the em boxes of upright glyphs, tate-chu-yoko blocks and glyphs lying on their side + // straddle the path. Glyph space here is horizontal path type's: x runs along the path and y + // across it, to the right of the path's direction. + if let (true, true, Some(t)) = (self.vertical, self.on_path, g.tcy) { + // Tate-chu-yoko stands upright as one block: set across the column, centered on its em of + // it and on the path, its top toward the path's start, then moved by + // its Up/Down toward the path's start and by its Left/Right to the path's left, whatever + // the effect does to the glyph's axes. The block's first glyph sets where the block + // stands; the others take its em, its place on the path and its column, so the block + // stays whole on a curve. + let (block, centre) = match self.tcy_block.filter(|_| t.pen > 0.0) { + Some(b) => b, + None => { + // A later glyph without its first glyph: placed back by its pen offset. + let (em, back) = + if t.pen > 0.0 { (t.pen, Affine::translate((-t.pen, 0.0))) } else { (self.style_at(g.byte).size, Affine::IDENTITY) }; + let centre = Point::new(em * 0.5, 0.0); + let squeeze = + Affine::translate((centre.x, 0.0)) * Affine::scale_non_uniform(t.squeeze, 1.0) * Affine::translate((-centre.x, 0.0)); + let on_path = pre * back; + let mut block = on_path * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, centre) * squeeze; + // The effects that keep the glyph's axes fixed leave the block's top toward the + // path's end on a path that runs to the left: it turns half a turn about its + // center, as an upright glyph does. + let tangent = Vec2::new(angle.cos(), angle.sin()); + if (block * Point::new(centre.x, centre.y - 1.0) - block * centre).dot(tangent) > 0.0 { + block = Affine::translate((on_path * centre).to_vec2() * 2.0) * Affine::scale(-1.0) * block; + } + let left = Vec2::new(tangent.y, -tangent.x); + block = Affine::translate(-tangent * t.up + left * t.right) * block; + self.tcy_block = Some((block, centre)); + (block, centre) } + }; + let em = centre.x * 2.0; + let across = Affine::translate((centre.x - t.width * 0.5 + t.ink, centre.y + g.face.ideographic_centre() * em)); + m = block * across * local; + } else if self.vertical && self.on_path && (g.inline.is_some() || !stands_upright(g)) { + // A glyph lying on its side (and an inline graphic) is a quarter turn clockwise from an + // upright glyph, as horizontal type on the path sets it: its baseline runs along the path + // and its top faces the path's left. It moves across the path so that the center of its + // ideographic em box lies on the path. + // + // + let centre = g.face.ideographic_centre() * g.face.units_per_em() * g.sy; + m = pre * Affine::translate((0.0, centre)) * local; + } else if self.vertical && self.on_path { + // An upright glyph is a quarter turn counterclockwise from horizontal path type's pose, + // turned in glyph space so that every effect bends it as it bends glyphs lying on their + // side: its top faces the path's start and the characters of an upright ligature read + // along the path in order. The center of its cell (without its Character Rotation) keeps + // its place along the path, and its em box is centered across the path. + let (cell, top) = path_cell.unwrap_or((0.0, 0.0)); + let unrotated = local * unturned; + let middle = Point::new(g.face.units_per_em() * 0.5, cell * 0.5 - top); + // The em box's middle across the column, which the shaper's offsets then move. + let at = Point::new(g.face.units_per_em() * g.sx * 0.5, (unrotated * middle).y); + let target = Point::new(-at.y, 0.0); + let quarter = Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]); + let mut turn = Affine::translate(target.to_vec2() - (quarter * at).to_vec2()) * quarter; + // The effects that keep the glyph's axes fixed (Stair Step) leave its top toward the + // path's end on a path that runs to the left: it turns half a turn about its cell's + // center. + let tangent = Vec2::new(angle.cos(), angle.sin()); + let placed = pre * turn * unrotated; + if (placed * Point::new(middle.x, middle.y - 1.0) - placed * middle).dot(tangent) > 0.0 { + turn = Affine::translate(target.to_vec2() * 2.0) * Affine::scale(-1.0) * turn; } + m = pre * turn * local; } else if let (true, Some(t)) = (self.vertical, g.tcy) { // Tate-chu-yoko: the block set across the column, centred on its em of it, then moved up // by its Up/Down and right by its Left/Right (line x runs down the column and line y - // from right to left across it). - let em = self.style_at(g.byte).size; + // from right to left across it). Every glyph of the block takes the em of its first + // glyph, the pen offset of the others. + let em = if t.pen > 0.0 { t.pen } else { self.style_at(g.byte).size }; let start = origin.x - t.pen; let centre = Point::new(start + em * 0.5, origin.y - g.face.ideographic_centre() * em); let across = Affine::translate((centre.x - t.width * 0.5 + t.ink - origin.x, 0.0)); @@ -629,6 +687,7 @@ mod emit_kashida_mark_last { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Last visual glyph of the cluster: a mark that wrongly keeps the mark run (run 1). @@ -692,6 +751,7 @@ mod emit_kashida_mark_last { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Simulate the pre-fix path: clone run from the mark glyph only. diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 805c4dead4..79a7ebd8d8 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -374,6 +374,7 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T system_layout: t.system_layout, fractional_widths: t.fractional_widths, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Vertical type: line space turned a quarter turn clockwise (lines become columns, each next diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 30f8d76eb8..c94d25f897 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -136,6 +136,7 @@ fn composition_trim_stays_along_the_line_when_a_character_rotates() { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; cx.emit(&glyph, pre, origin, angle, 30.0 - lead, 0); diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index a93d1a9cd1..2f9699de68 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -718,7 +718,7 @@ fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() { /// On a path, an upright ligature in vertical type reads along the path in order: the top of its /// cell comes first, and its font caret (600 units down the cell) is drawn where the caret, a click /// and the selection put the stop, on a path running either way with any path effect. A glyph lying -/// on its side keeps its top toward the path's end. +/// on its side is a quarter turn clockwise from that, as horizontal type on the path sets it. #[test] fn an_upright_ligature_on_a_path_reads_along_it_in_order() { use vectorcraft_doc::PathEffect; @@ -763,8 +763,8 @@ fn an_upright_ligature_on_a_path_reads_along_it_in_order() { let (q0, q1) = (along(q[0][0]), along(q[0][1])); assert!((q0.min(q1) - drawn.min(0.0)).abs() < 1e-6 && (q0.max(q1) - drawn.max(0.0)).abs() < 1e-6, "{to} {effect:?}: {q:?} against {drawn}"); } - // Without Standard Vertical Roman Alignment the letter lies on its side: its top still faces - // the path's end and its advance runs across the path, to its right. + // Without Standard Vertical Roman Alignment the letter lies on its side: its top faces the + // path's left and its advance runs along the path. let mut line = BezPath::new(); line.move_to((0.0, 0.0)); line.line_to((1000.0, 0.0)); @@ -774,9 +774,9 @@ fn an_upright_ligature_on_a_path_reads_along_it_in_order() { let l = layout(&db, &t); let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; let tangent = Vec2::new(s.angle.cos(), s.angle.sin()); - let right = Vec2::new(-tangent.y, tangent.x); + let left = Vec2::new(tangent.y, -tangent.x); let (pen, up, ahead) = (s.xf * Point::ZERO, s.xf * Point::new(0.0, -500.0), s.xf * Point::new(500.0, 0.0)); - assert!((up - pen).dot(tangent) > 1.0 && (ahead - pen).dot(right) > 1.0, "{pen:?} {up:?} {ahead:?}"); + assert!((up - pen).dot(left) > 1.0 && (ahead - pen).dot(tangent) > 1.0, "{pen:?} {up:?} {ahead:?}"); } /// On a path, an upright ligature whose cell Proportional Metrics shortens (`vpal`, from 1000 units diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 225395d348..4df48c51ef 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -184,6 +184,220 @@ fn type_on_a_path_stays_horizontal() { assert!(!layout(FontDb::global(), &t).vertical); } +/// `text` in vertical type on a straight path from `from` to `to`, with path effect `effect`. +fn on_vertical_path(text: &str, from: (f64, f64), to: (f64, f64), effect: vectorcraft_doc::PathEffect) -> TextObject { + let mut t = vertical(text); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new(from, to).to_path(0.1)), start: 0.0, end: None }; + t.path_effect = effect; + t +} + +/// Glyph `i`'s top (its ascender direction) and its own advance direction in text space, as unit +/// vectors. +fn top_and_ahead(l: &TextLayout, i: usize) -> (Vec2, Vec2) { + let g = &l.glyphs[i]; + let pen = g.xf * Point::ZERO; + let unit = |v: Vec2| v / v.hypot(); + (unit(g.xf * Point::new(0.0, -500.0) - pen), unit(g.xf * Point::new(500.0, 0.0) - pen)) +} + +/// On a vertical path, an upright glyph's top faces the path's start, and a letter lying on its side +/// is a quarter turn clockwise from it: its top faces the path's left and its baseline runs along +/// the path. Both turn with the path when it runs the other way. +#[test] +fn on_a_vertical_path_letters_lie_a_quarter_turn_clockwise_from_upright_glyphs() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0), (-1000.0, 0.0), (700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§L", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (upright, _) = top_and_ahead(&l, 0); + let (side, ahead) = top_and_ahead(&l, 1); + assert!((upright + tangent).hypot() < 1e-6, "{to:?}: the upright top faces the start: {upright:?}"); + // A clockwise quarter turn with y down takes (x, y) to (-y, x). + assert!((side - Vec2::new(-upright.y, upright.x)).hypot() < 1e-6, "{to:?}: {side:?} against {upright:?}"); + assert!((side - left).hypot() < 1e-6 && (ahead - tangent).hypot() < 1e-6, "{to:?}: {side:?} {ahead:?}"); + } +} + +/// On a vertical path, letters lying on their side are set as horizontal type on the same path sets +/// them, with every path effect and on a path running either way, and they follow one another along +/// the path without overlapping where the effect keeps them square to it. +#[test] +fn on_a_vertical_path_letters_keep_the_horizontal_path_pose() { + use vectorcraft_doc::PathEffect; + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0), (700.0, 300.0)] { + let mut vertical = on_vertical_path("LLl", (0.0, 0.0), to, effect); + let v = layout(FontDb::global(), &vertical); + vertical.vertical = false; + let h = layout(FontDb::global(), &vertical); + for i in 0..3 { + let (a, b) = (v.glyphs[i].xf.as_coeffs(), h.glyphs[i].xf.as_coeffs()); + assert!(a.iter().zip(b).take(4).all(|(a, b)| (a - b).abs() < 1e-9), "{effect:?} {to:?} glyph {i}: {a:?} against {b:?}"); + } + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let span = |i: usize| { + let along = v.glyphs[i].outline.elements().iter().filter_map(|el| el.end_point()).map(|p| p.to_vec2().dot(tangent)); + along.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d))) + }; + // Skew slants the letters, Stair Step keeps them level and Gravity fans them toward the + // path's center, so their ink can reach past the next letter's. + if matches!(effect, PathEffect::Rainbow | PathEffect::Ribbon3d) { + assert!((0..2).all(|i| span(i).1 <= span(i + 1).0 + 1e-6), "{effect:?} {to:?}: {:?}", (0..3).map(span).collect::>()); + } + } + } +} + +/// On a vertical path, the column is centered on the path: the em boxes of upright glyphs, of letters +/// lying on their side and of a tate-chu-yoko block straddle it, their centers on the path line, on +/// a path running any way. +#[test] +fn on_a_vertical_path_the_column_is_centered_on_the_path() { + use vectorcraft_doc::PathEffect; + let Some(face) = FontDb::global().face("Source Sans 3", "Regular") else { panic!("the bundled face") }; + let (em, centre) = (face.units_per_em(), face.ideographic_centre()); + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0), (-700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§H12§", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let across = |p: Point| p.to_vec2().dot(Vec2::new(tangent.y, -tangent.x)); + // An upright glyph (the shaper centers a narrow one in its em box, as off a path) has its + // ink centered on the path. + for i in [0, 4] { + let mid = across(ink(&l, i).center()); + assert!(mid.abs() < 1.0, "{to:?}: upright glyph {i} is {mid} off the path"); + } + // A letter lying on its side: its em box's center is `centre` em above its baseline. + let mid = across(l.glyphs[1].xf * Point::new(0.0, -centre * em)); + assert!(mid.abs() < 1e-6, "{to:?}: the letter's em box is {mid} off the path"); + // The digits of the block stand side by side across the path, the block centered on it. + let block = (across(ink(&l, 2).center()) + across(ink(&l, 3).center())) * 0.5; + assert!(block.abs() < 1.5, "{to:?}: the block is {block} off the path"); + } +} + +/// With Skew on a curved vertical path, every glyph's axis along the path follows the tangent and +/// its axis across the path stays upright on the page: an upright glyph's top runs back along the +/// tangent and its own x axis points up the page, and a letter lying on its side keeps its top up +/// the page and its baseline along the tangent. +#[test] +fn on_a_curved_vertical_path_skew_keeps_the_axis_across_the_path_upright() { + use vectorcraft_doc::PathEffect; + let mut arc = kurbo::BezPath::new(); + arc.move_to((0.0, 0.0)); + arc.curve_to((40.0, 0.0), (80.0, 40.0), (80.0, 120.0)); + let mut t = vertical("§L§L§"); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&arc), start: 0.0, end: None }; + t.path_effect = PathEffect::Skew; + let l = layout(FontDb::global(), &t); + let page_up = Vec2::new(0.0, -1.0); + for (i, g) in l.glyphs.iter().enumerate() { + let tangent = Vec2::new(g.angle.cos(), g.angle.sin()); + let (top, ahead) = top_and_ahead(&l, i); + if i % 2 == 0 { + assert!((top + tangent).hypot() < 1e-6 && (ahead - page_up).hypot() < 1e-6, "upright glyph {i}: {top:?} {ahead:?} at {tangent:?}"); + } else { + assert!((top - page_up).hypot() < 1e-6 && (ahead - tangent).hypot() < 1e-6, "letter {i}: {top:?} {ahead:?} at {tangent:?}"); + } + } + let turns = l.glyphs.iter().map(|g| g.angle).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), a| (lo.min(a), hi.max(a))); + assert!(turns.1 - turns.0 > 0.3, "the glyphs sit on the curve: {turns:?}"); +} + +/// A tate-chu-yoko block whose characters differ in size stays one block: every character stands on +/// the block's baseline in the em of its first character, in vertical type and on a vertical path. +#[test] +fn a_tate_chu_yoko_block_of_mixed_sizes_shares_its_first_characters_em() { + let run = |text: &str, size: f64| TextRun { text: text.into(), style: CharStyle { size, ..CharStyle::default() }, inline: None }; + let mut t = vertical(""); + t.runs = vec![run("§", 20.0), run("1", 20.0), run("2", 10.0), run("§", 20.0)]; + let mut on_path = t.clone(); + on_path.kind = + TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 1000.0)).to_path(0.1)), start: 0.0, end: None }; + for (name, t) in [("vertical", &t), ("on a path", &on_path)] { + let l = layout(FontDb::global(), t); + assert!(l.glyphs[2].advance == 0.0, "{name}: 12 is one block: {:?}", l.glyphs.iter().map(|g| g.advance).collect::>()); + let (one, two) = (ink(&l, 1), ink(&l, 2)); + assert!((one.y1 - two.y1).abs() < 0.5 && two.center().x > one.center().x, "{name}: on one baseline: {one:?} {two:?}"); + } +} + +/// On a vertical path, Tate-chu-yoko Settings Up/Down move a marked block toward the path's start +/// and Left/Right move it to the right of its upright characters (the path's left), with every +/// effect on a path running any way. +#[test] +fn on_a_vertical_path_tate_chu_yoko_settings_keep_their_directions() { + use vectorcraft_doc::PathEffect; + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0), (0.0, 1000.0), (-700.0, -700.0)] { + let at = |up: f64, right: f64| { + let marked = CharStyle { size: 20.0, tate_chu_yoko: true, tcy_up_down: up, tcy_left_right: right, ..CharStyle::default() }; + let mut t = on_vertical_path("", (0.0, 0.0), to, effect); + t.runs = vec![ + TextRun { text: "§".into(), style: CharStyle { size: 20.0, ..CharStyle::default() }, inline: None }, + TextRun { text: "12".into(), style: marked, inline: None }, + ]; + ink(&layout(FontDb::global(), &t), 1).center().to_vec2() + }; + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (plain, up, right) = (at(0.0, 0.0), at(4.0, 0.0), at(0.0, 3.0)); + assert!((up - plain + tangent * 4.0).hypot() < 1e-6, "{effect:?} {to:?}: Up/Down moved it {:?}", up - plain); + assert!((right - plain - left * 3.0).hypot() < 1e-6, "{effect:?} {to:?}: Left/Right moved it {:?}", right - plain); + } + } +} + +/// On a vertical path, a tate-chu-yoko block stands upright like the glyphs around it: its digits +/// read across the column, their tops toward the path's start, centered on the column. +#[test] +fn on_a_vertical_path_tate_chu_yoko_stands_upright() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§12§", (0.0, 0.0), to, PathEffect::Rainbow)); + assert!(l.glyphs[1].outline.elements().len() > 1, "{to:?}: the 1 draws"); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (upright, _) = top_and_ahead(&l, 0); + for i in [1, 2] { + let (top, ahead) = top_and_ahead(&l, i); + assert!((top - upright).hypot() < 1e-6 && (ahead - left).hypot() < 1e-6, "{to:?} digit {i}: {top:?} {ahead:?}"); + } + let centre = |i: usize| ink(&l, i).center().to_vec2(); + let (one, two) = (centre(1), centre(2)); + assert!((two - one).dot(left) > 3.0 && (two - one).dot(tangent).abs() < 1.0, "{to:?}: 12 side by side: {one:?} {two:?}"); + let across = |v: Vec2| v.dot(left); + let block = (across(one) + across(two)) * 0.5; + assert!((block - across(centre(0))).abs() < 2.0, "{to:?}: the block is centered on the column: {block} against {}", across(centre(0))); + let (before, after) = ((centre(0)).dot(tangent), (centre(3)).dot(tangent)); + assert!(before < one.dot(tangent) && one.dot(tangent) < after, "{to:?}: the block stands between the marks"); + } + // On a curve the block stays whole: both digits turn alike and stand on one baseline. + let mut arc = kurbo::BezPath::new(); + arc.move_to((0.0, 0.0)); + arc.curve_to((0.0, 40.0), (20.0, 60.0), (60.0, 60.0)); + let mut t = vertical("§12§"); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&arc), start: 0.0, end: None }; + let l = layout(FontDb::global(), &t); + let (a, b) = (l.glyphs[1].xf.as_coeffs(), l.glyphs[2].xf.as_coeffs()); + assert!(a.iter().zip(b).take(4).all(|(a, b)| (a - b).abs() < 1e-9), "{a:?} against {b:?}"); + let (top, ahead) = top_and_ahead(&l, 1); + let (p1, p2) = (l.glyphs[1].xf * Point::ZERO, l.glyphs[2].xf * Point::ZERO); + assert!((p2 - p1).dot(top).abs() < 1e-6 && (p2 - p1).dot(ahead) > 3.0, "{p1:?} {p2:?}"); + // With every effect, on a path running either way, the block's top faces the path's start. + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§12§", (0.0, 0.0), to, effect)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + for i in [1, 2] { + let (top, _) = top_and_ahead(&l, i); + assert!(top.dot(tangent) < -0.5, "{effect:?} {to:?} digit {i}: {top:?}"); + } + } + } +} + #[test] fn three_digits_stand_across_the_column_squeezed_into_one_em() { let l = layout(FontDb::global(), &vertical("§100§")); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c15e19cda6..562574cde0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1165,7 +1165,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Tabs ruler's upper first-line marker and lower left-indent marker show absolute positions and set paragraph indents (`text.setFormat`). Dragging the lower marker keeps the upper position, while Ctrl-dragging it (Command on macOS) moves both; marker drags snap like tab stops, and each release is one undo step. With differing left indents, only the upper marker is shown and its absolute target applies to every touched paragraph. When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them in the same column, which is centered on the path); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. From 75fc513a6fb54f8125f1c60a13fc4d2de8b16f22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:37:49 -0800 Subject: [PATCH 25/83] Native files: a document past a read budget is refused after one read When the pass that reads the document and the saved PDF preference together failed with a data error, open read the whole document a second time without the preference. A document past a read budget, or with any other data error, was then read up to the budget again before it was refused. Open now reads it again only when the first pass stopped at a pdfCompatible that is not a boolean, which it tells by reading the preference alone over the bytes up to the first pass's error position. --- crates/format/src/lib.rs | 91 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 4 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 1da653311a..667b39aad2 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -511,6 +511,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the // PDF are skipped without being kept. fn within_budgets(max_nodes: usize, max_values: usize, read: impl FnOnce() -> T) -> T { + #[cfg(test)] + DOCUMENT_READS.with(|n| n.set(n.get() + 1)); vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, || { vectorcraft_doc::node::with_node_budget(max_nodes, || vectorcraft_doc::node::with_buffered_value_budget(max_values, read)) }) @@ -527,9 +529,10 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result let (mut f, pdf_compatible) = match within_budgets(max_nodes, max_values, || Contents::::read_with_pdf_preference(file.json())) { Ok(read) => read, // That pass refuses a `pdfCompatible` that is not a boolean, and any other data error. - // The file is read again without the preference, and only then is its JSON scanned for - // the preference a second time, so such a file opens as before. - Err(ReadError::Json(e)) if e.is_data() => { + // When it stopped at the preference, the file is read again without it, and only then is + // its JSON scanned for the preference a second time, so such a file opens as before. Any + // other error, such as a document past a budget, is returned without a second read. + Err(ReadError::Json(e)) if e.is_data() && refused_preference_at(file.json(), &e) => { let f = within_budgets(max_nodes, max_values, || Contents::::read(file.json())).map_err(read_error)?; let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; (f, pdf_compatible) @@ -631,6 +634,51 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result thread_local! { /// Tests: how many times a file's JSON was scanned again for its PDF preference on this thread. static PDF_MEMBER_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times a file's document was read on this thread. + static DOCUMENT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether reading `json`'s `pdfCompatible` as a boolean or null fails with a data error at the +/// line and column of `e`, that is, whether the read that gave `e` stopped at the preference. Only +/// the bytes up to that position, and the one there, are read, and they are skipped without being +/// kept. +fn refused_preference_at(json: &[u8], e: &serde_json::Error) -> bool { + // serde_json gives a 1-based line and the bytes before the position on that line. + let Some(line_start) = (match e.line() { + 0 => None, + 1 => Some(0), + n => json.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(n - 2).map(|(i, _)| i + 1), + }) else { + return false; + }; + let end = line_start.saturating_add(e.column()).saturating_add(1).min(json.len()); + struct StrictPreference; + impl<'de> Visitor<'de> for StrictPreference { + type Value = (); + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a native file envelope") + } + + fn visit_map>(self, mut map: A) -> Result<(), A::Error> { + while let Some(key) = map.next_key::()? { + if key == "pdfCompatible" { + map.next_value::>()?; + } else { + map.next_value::()?; + } + } + Ok(()) + } + + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while seq.next_element::()?.is_some() {} + Ok(()) + } + } + serde_json::Deserializer::from_slice(&json[..end]) + .deserialize_any(StrictPreference) + .is_err_and(|s| s.is_data() && s.line() == e.line() && s.column() == e.column()) } /// The saved PDF preference, falling back to the presence of its payload without retaining or @@ -842,9 +890,44 @@ mod tests { value["pdfCompatible"] = odd.clone(); assert_eq!(scans_for(&serde_json::to_vec(&value).unwrap()), (false, 1), "{odd}"); } - // A document that can't be read still fails, after the second read. + // A document that can't be read still fails. Read before the preference, it is not read + // a second time. value["document"] = serde_json::json!("not a document"); + DOCUMENT_READS.with(|n| n.set(0)); assert!(load_info(&serde_json::to_vec(&value).unwrap()).is_err()); + assert_eq!(DOCUMENT_READS.with(|n| n.get()), 1); + // Read after a preference that is not a boolean, it fails on the second read, which is + // the first to reach it. + let mut first = serde_json::to_vec(&value).unwrap(); + assert!(first.starts_with(br#"{"document""#)); + first.splice(1..1, br#""pdfCompatible":"yes","#.iter().copied()); + DOCUMENT_READS.with(|n| n.set(0)); + assert!(load_info(&first).is_err()); + assert_eq!(DOCUMENT_READS.with(|n| n.get()), 2); + } + + /// A document past a read budget is refused after one read, also in a file whose preference + /// is not a boolean. + #[test] + fn a_document_past_a_budget_is_read_once() { + let mut d = Document::new(100.0, 100.0); + let l = d.add_layer(None); + for i in 0..20 { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); + } + let n = d.node_count(); + let mut value: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + for preference in [serde_json::Value::Null, serde_json::json!(true), serde_json::json!("yes")] { + value["pdfCompatible"] = preference.clone(); + let bytes = serde_json::to_vec(&value).unwrap(); + DOCUMENT_READS.with(|r| r.set(0)); + let Err(FormatError::NotVectorcraft(why)) = load_file_within(&bytes, n - 1, vectorcraft_doc::node::MAX_BUFFERED_VALUES) else { + panic!("one object past the budget must be refused") + }; + assert!(why.contains(&format!("more than {} objects", n - 1)), "{why}"); + assert_eq!(DOCUMENT_READS.with(|r| r.get()), 1, "{preference}"); + } } #[test] From 5452b516f64e65d95b5fd9e996c72c4971a25b53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:39:36 -0800 Subject: [PATCH 26/83] Render: type in a document's own composite font draws in its definition Raster renders, ink renders, thumbnails and node renders now lend the document's composite fonts to the font database while they draw, as the PDF, SVG and EPS writers already do. A document that is not in front, a document read from a file (library thumbnails, save previews) and a placed document's art drew such type in the fallback font or in another definition of that name. --- crates/render/src/renderer.rs | 8 ++++- crates/render/src/tests/fontchange.rs | 44 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index a5bfcbf26e..205d4d73c3 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -105,8 +105,11 @@ impl Renderer { } } - /// Render `doc` into a `width`×`height` image using `view` (document → pixel transform). + /// Render `doc` into a `width`×`height` image using `view` (document → pixel transform). Type + /// set in one of the document's composite fonts draws in the document's definition, also when + /// no session has registered it (a document that is not in front, or read from a file). pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); self.render_as(doc, width, height, view, opts, false, 1) } @@ -340,6 +343,7 @@ impl Renderer { pub fn render_region_inks(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Vec { let (w, h) = region_pixels(region, scale); let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); self.render_as(doc, w, h, view, opts, true, 1).pixels } @@ -356,6 +360,7 @@ impl Renderer { /// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]). pub fn render_node_with(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); let inv = view.inverse(); @@ -395,6 +400,7 @@ impl Renderer { background: Option<[u8; 4]>, opts: &RenderOptions, ) -> Option { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); let b = brush_fx::cull_bounds(&doc.symbol_boxes(), n)?; diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 82c5c77ff7..4ead4a5c1c 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -138,6 +138,50 @@ fn composite_font_parts_are_not_highlighted_as_substituted_glyphs() { assert!(g.substituted_glyphs.elements().is_empty() && g.substituted_fonts.elements().is_empty()); } +/// Type in one of a document's composite fonts draws in the document's definition when nothing has +/// registered it: in a render, an ink render, a thumbnail and a placed document's art, as type set +/// in the part's font draws. +/// The font database is left without it afterwards. +#[test] +fn a_documents_own_composite_font_draws_without_being_registered() { + use vectorcraft_doc::{CompositeFont, CompositePart, CompositeParts}; + let _adding = adding_fonts(); + const NAME: &str = "CF Unregistered"; + let db = vectorcraft_text::FontDb::global(); + let typed = |family: &str| { + let mut d = Document::new(300.0, 150.0); + let style = CharStyle { size: 60.0, font_family: family.into(), ..Default::default() }; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 100.0), "Hamburg", style)))); + let l = d.layers[0].id; + let id = d.insert(Some(l), 0, n).unwrap(); + (d, id) + }; + let (mut composite, id) = typed(NAME); + let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular")); + parts.roman = CompositePart::new("JetBrains Mono", "Regular"); + composite.composite_fonts.push(CompositeFont { name: NAME.into(), parts }); + let (plain, plain_id) = typed("JetBrains Mono"); + assert!(db.composite_font(NAME).is_none()); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::IDENTITY; + assert_eq!( + Renderer::new().render(&composite, 300, 150, view, &opts).pixels, + Renderer::new().render(&plain, 300, 150, view, &opts).pixels, + "rendered" + ); + let region = Rect::new(0.0, 0.0, 300.0, 150.0); + assert_eq!( + Renderer::new().render_region_inks(&composite, region, 1.0, &opts), + Renderer::new().render_region_inks(&plain, region, 1.0, &opts), + "rendered as ink amounts" + ); + let thumbnail = |d: &Document, id| Renderer::new().render_thumbnail(d, id, 64).map(|r| r.pixels); + assert_eq!(thumbnail(&composite, id), thumbnail(&plain, plain_id), "thumbnail"); + let placed = |d: &Document| crate::placed_document::render_inside(&mut Renderer::new(), d, &d.layers[0], 300, 150, view).map(|r| r.pixels); + assert_eq!(placed(&composite), placed(&plain), "a placed document's art"); + assert!(db.composite_font(NAME).is_none(), "given back after each render"); +} + /// Type at 80% opacity, in Multiply and with a drop shadow redraws in a font that becomes /// available: the glyph geometry kept for it is laid out again. #[test] From 693031c5093d349de1815c1b5760b4ececfb5cb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 21:59:21 -0800 Subject: [PATCH 27/83] Scripts: #include and the other preprocessor lines run, and $.evalFile runs a file Before a script runs, `script.run` reads its preprocessor lines (`#` or `//@` at the start of a line, outside strings and comments): - `#include` and `//@include` put another file's text in place of the line, looked for beside the including file, then in each `#includepath` folder, then in each `JSINCLUDE` folder. A later `#includepath` replaces the list. - `#script` names the run unless `name` is given; `#target` takes any value; `#strict off` is taken. `#strict on`, `#targetengine` and `#engine` are refused as unsupported, and any other `#name` as unknown. `$.evalFile(path, timeout?)` runs a file in the same global environment and returns its last value, `$.fileName` is the file being run and `$.includePath` the include folders. A script run from a file reads these files only in its folder and the folders below it. Paths with a `..` name, links or junctions that lead out, device names, streams and network paths are refused; a script given as text reads none. A run reads at most 64 files 16 levels deep, 32 MiB of source in all and 1,024 paths looked up. An error in an included or evaluated file is reported at that file's line and column, and the report's new `file` field names it. Docs: docs/mcp.md (script.run, Script Console), docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 7 +- crates/engine/src/file_access.rs | 85 +++++ crates/engine/src/script/include.rs | 431 ++++++++++++++++++++++ crates/engine/src/script/mod.rs | 218 +++++++++-- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_include.rs | 327 ++++++++++++++++ crates/engine/src/tests/script_run.rs | 11 +- crates/js/src/builtins.rs | 4 +- crates/js/src/bytecode.rs | 2 + crates/js/src/heap.rs | 4 +- crates/js/src/host.rs | 69 +++- crates/js/src/interp.rs | 12 +- crates/js/src/interp_tests.rs | 2 +- crates/js/src/lib.rs | 2 +- crates/js/src/realm.rs | 26 +- docs/mcp.md | 43 ++- docs/target-app-parity.md | 1 + 17 files changed, 1194 insertions(+), 51 deletions(-) create mode 100644 crates/engine/src/script/include.rs create mode 100644 crates/engine/src/tests/script_include.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 1ed75194bd..aac077bb89 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict off is taken; #strict on, #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Script Console", [], None, - "{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message, its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)", + "{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message (name: file:line:column: message when it is in another file), its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)", always, console_lines ), @@ -153,7 +153,8 @@ fn run(s: &mut Session, p: &Value) -> Result { _ => return Err(param("give exactly one of `path` and `source`")), }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); - s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?; + let request = script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), source: text, args, fuel }; + let name = s.script_start(request)?; if s.script_frames { return Ok(json!({"running": true, "name": name})); } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c6daff9e41..3f0a641e2e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -23,6 +23,9 @@ //! A path is checked, then opened: a process that can change the folders in between (swapping in //! a link) can still win that race. The roots keep an agent to the files it was given; they don't //! guard against other programs on the computer. +//! +//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) +//! are read from, inside the roots. use std::cell::RefCell; use std::ffi::OsString; @@ -347,6 +350,88 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> { }) } +/// The folders a running script's own files are read from: the files its `#include` lines name and +/// the files it passes to `$.evalFile` (`Scope::Script`'s reads). VectorCraft's own rules: a script +/// run from a file may read inside that file's folder and the folders below it, and a script given as +/// text may read none. A path is refused when it has a `..` component, a Windows device name or +/// stream, or names a computer on the network, or when it leads (through its links, junctions +/// included) out of every granted folder. The automation roots ([`check_read`]) apply as well. +/// +/// The file opened is the path with its links followed, and after reading, the path is followed +/// again and must still lead to the same place: a process that changes the folders twice in between +/// can still win that race. +#[derive(Clone, Debug, Default)] +pub(crate) struct ScriptScope { + /// The granted folders, made absolute with their links followed. + roots: Vec, +} + +/// Why a script's file was not read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum ScriptRead { + /// There is no such file. + Missing, + /// The scope does not let the script read it. + Refused, + /// The file has more than the bytes asked for. + TooLarge, + /// The file system gave this error. + Failed(String), +} + +impl ScriptScope { + /// The scope of a script run from a file in folder `dir`: that folder. + pub(crate) fn of_folder(dir: &Path) -> Self { + Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() } + } + + /// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or + /// stream, or a computer on the network? + fn refused_by_name(path: &Path) -> bool { + let text = path.to_string_lossy(); + text.contains('\0') + || path.components().any(|c| c == Component::ParentDir) + || (cfg!(windows) && (windows_name_refusal(&text).is_some() || network_path(&text))) + } + + /// The real path of the file at `path` and its first `max` bytes, at most. + pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { + use std::io::Read; + if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + let real = match std::fs::canonicalize(path) { + Ok(real) => real, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + // A link whose target is missing is there all the same: it is not followed. + return Err(if std::fs::symlink_metadata(path).is_ok() { ScriptRead::Refused } else { ScriptRead::Missing }); + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + }; + if !self.roots.iter().any(|r| inside(&real, r)) { + return Err(ScriptRead::Refused); + } + let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; + let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?; + if !meta.is_file() { + return Err(ScriptRead::Missing); + } + if meta.len() > max as u64 { + return Err(ScriptRead::TooLarge); + } + let mut bytes = Vec::new(); + // One byte more than asked for shows a file that grew while it was read. + file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| ScriptRead::Failed(e.to_string()))?; + if bytes.len() > max { + return Err(ScriptRead::TooLarge); + } + if std::fs::canonicalize(path).ok().as_ref() != Some(&real) { + return Err(ScriptRead::Refused); + } + Ok((real, bytes)) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs new file mode 100644 index 0000000000..df7702d771 --- /dev/null +++ b/crates/engine/src/script/include.rs @@ -0,0 +1,431 @@ +//! A script's preprocessor lines, read before it runs, as the public guide lists them +//! (): +//! `#include` and `//@include` put the text of another file in place of the line, `#includepath` +//! sets the folders `#include` looks in, `#script` names the run, and `#target` and `#strict off` +//! are accepted. The same lines are read in a file `$.evalFile` runs. +//! +//! VectorCraft's own rules: +//! +//! - A line counts only at the start of a line (blanks before it), outside strings and comments, as +//! the lexer reads it, and each file must be a whole script on its own. +//! - An included file is looked for beside the file that includes it, then in each `#includepath` +//! folder in turn (a relative one is relative to that same file's folder), then in each folder of +//! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list. +//! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a +//! `JSINCLUDE` folder outside the scope, which is passed over. +//! - `#target` takes any value and changes nothing. `#targetengine`, `#engine` and `#strict on` are +//! refused as unsupported, and any other `#name` as unknown; `//@name` with another name stays a +//! comment. +//! - A run reads at most [`MAX_DEPTH`] levels of nested files, [`MAX_FILES`] files, +//! [`MAX_TOTAL_BYTES`] of source in all (the script's own included) and 8 MiB a file, and looks up +//! at most [`MAX_PROBES`] paths. A file may be included again once its earlier inclusion has +//! ended; one that includes itself, directly or not, is an error. +//! +//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of +//! the file it is in. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use vectorcraft_js::{DirectiveName, Options}; + +use crate::file_access::{ScriptRead, ScriptScope}; + +/// The most files nested inside each other, below the script. +pub const MAX_DEPTH: usize = 16; +/// The most files a run includes or evaluates. +pub const MAX_FILES: usize = 64; +/// The most bytes of source a run reads, its own included. +pub const MAX_TOTAL_BYTES: usize = 32 << 20; +/// The most paths a run looks up for its files. +pub const MAX_PROBES: usize = 1024; +/// The longest value a preprocessor line may have, in bytes. +const MAX_VALUE_BYTES: usize = 4096; + +/// Where the lines of an expanded source came from: file 0 is the file expanded, the others the +/// files it included. +#[derive(Clone, Debug, Default)] +pub(crate) struct SourceMap { + files: Vec>, + segments: Vec, +} + +/// From line `out_line` of the expanded source on, the lines are those of file `file` from line +/// `line`; on `out_line` itself the columns are `shift` units further right. +#[derive(Clone, Copy, Debug)] +struct Segment { + out_line: u32, + file: usize, + line: u32, + shift: u32, +} + +impl SourceMap { + /// Line `line`, column `column` of the expanded source → the file it is in (its index and name) + /// and the line and column there. + pub(crate) fn locate(&self, line: u32, column: u32) -> (usize, Arc, u32, u32) { + let at = self.segments.partition_point(|s| s.out_line <= line); + let Some(seg) = at.checked_sub(1).and_then(|i| self.segments.get(i)) else { + return (0, self.files.first().cloned().unwrap_or_else(|| Arc::from("")), line, column); + }; + let column = if line == seg.out_line { column.saturating_sub(seg.shift).max(1) } else { column }; + let name = self.files.get(seg.file).cloned().unwrap_or_else(|| Arc::from("")); + (seg.file, name, seg.line.saturating_add(line - seg.out_line), column) + } +} + +/// How a preprocessor failure ends the run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FailKind { + /// A line that is not a valid preprocessor line, or a file that is not a valid script. + Syntax, + /// A file that is missing, refused or unreadable, or a cycle. + Error, + /// One of the run's limits. + Limit, +} + +/// A preprocessor failure, at line `line`, column `column` of the file `file` (index `index` of +/// the expansion's [`SourceMap`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Failure { + pub kind: FailKind, + pub message: String, + pub index: usize, + pub file: Arc, + pub line: u32, + pub column: u32, +} + +/// A source with its preprocessor lines read: the text to run, where its lines came from, and the +/// name its `#script` line gave. +pub(crate) struct Expanded { + pub source: String, + pub map: SourceMap, + pub name: Option, +} + +/// A file being run: its name for people and the folder its relative paths start from (none for a +/// script given as text). +struct Frame { + shown: Arc, + dir: Option, +} + +/// The files of one run: its scope, the `#includepath` list, what it has read and the files open +/// now, innermost last. +pub(crate) struct Files { + scope: ScriptScope, + jsinclude: Vec, + include_path: Vec, + files: usize, + bytes: usize, + probes: usize, + /// The real paths of the files open now, for cycles. + chain: Vec, + /// How many of them are below the script. + levels: usize, + /// The files `$.evalFile` is running, the script first. + frames: Vec, +} + +/// The output being built: its UTF-16 text, the line it is on, the units since that line began, +/// and whether its last unit is a carriage return. +struct Out { + units: Vec, + line: u32, + column: u32, + after_cr: bool, + map: SourceMap, +} + +impl Out { + fn emit(&mut self, text: &[u16]) { + for &u in text { + match u { + 0x0A if self.after_cr => self.column = 0, + 0x0A | 0x0D | 0x2028 | 0x2029 => { + self.line = self.line.saturating_add(1); + self.column = 0; + } + _ => self.column = self.column.saturating_add(1), + } + self.after_cr = u == 0x0D; + } + self.units.extend_from_slice(text); + } + + /// The lines from here on come from file `file`, from its line `line`. + fn begin(&mut self, file: usize, line: u32) { + self.map.segments.push(Segment { out_line: self.line, file, line, shift: self.column }); + } + + /// Ends the line the output is on, unless it has just ended. + fn end_line(&mut self) { + if self.after_cr || !matches!(self.units.last(), Some(0x0A | 0x2028 | 0x2029)) { + self.emit(&[0x0A]); + } + } +} + +/// A file's text read as a script: a byte order mark is left out, and compiled scripts and bytes +/// that are not UTF-8 are refused. +fn decode(bytes: &[u8], value: &str) -> Result { + if bytes.starts_with(b"@JSXBIN@") { + return Err(format!("script file is compiled: {value}")); + } + let text = std::str::from_utf8(bytes).map_err(|_| format!("script file is not UTF-8 text: {value}"))?; + Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string()) +} + +/// `value` without the single or double quotes around it, or `None` when a quote is not closed. +fn unquote(value: &str) -> Option<&str> { + match value.chars().next() { + Some(q @ ('"' | '\'')) => value.get(1..).and_then(|v| v.strip_suffix(q)), + _ => Some(value), + } +} + +/// The folder the file at `path` is in, without Windows' `\\?\` prefix: under that prefix `..` and +/// `/` in the names joined to it would be read as plain characters. +fn folder_of(path: &Path) -> Option { + path.parent().map(|p| crate::cmd::findfiles::plain(p.to_path_buf())) +} + +/// Does the path `p` have a `..` name, with `/` or `\` between names? +fn has_parent(p: &str) -> bool { + p.split(['/', '\\']).any(|name| name == "..") +} + +/// A real path as people read it. +fn display(path: &Path) -> Arc { + Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref()) +} + +impl Files { + /// The files of a run of the script at `path` (`None` for a script given as text), with the + /// `JSINCLUDE` folders `jsinclude`. + pub(crate) fn new(path: Option<&str>, jsinclude: Vec) -> Self { + let real = path.and_then(|p| std::fs::canonicalize(p).ok()); + let dir = real.as_deref().and_then(folder_of); + Self { + scope: dir.as_deref().map(ScriptScope::of_folder).unwrap_or_default(), + jsinclude, + include_path: Vec::new(), + files: 0, + bytes: 0, + probes: 0, + chain: real.into_iter().collect(), + levels: 0, + frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], + } + } + + /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. + pub(crate) fn jsinclude_env() -> Vec { + #[cfg(test)] + if let Some(list) = super::TEST_JSINCLUDE.with(|t| t.borrow().clone()) { + return list; + } + std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default() + } + + /// The file being run now, as `$.fileName` gives it (empty for a script given as text). + pub(crate) fn file_name(&self) -> String { + self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default() + } + + /// The `#includepath` list, as `$.includePath` gives it. + pub(crate) fn include_path(&self) -> String { + self.include_path.join(";") + } + + /// The script's own text, `text`, with its preprocessor lines read. + pub(crate) fn expand_script(&mut self, text: &str) -> Result { + self.bytes = self.bytes.saturating_add(text.len()); + let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); + let dir = self.frames.first().and_then(|f| f.dir.clone()); + self.expand(shown, dir, text, true) + } + + /// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its + /// preprocessor lines read. It becomes the file being run until [`Files::end_eval`]. + pub(crate) fn eval_file(&mut self, path: &str) -> Result { + let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); + let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 }; + let dir = self.frames.last().and_then(|f| f.dir.clone()); + let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?; + let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?; + let shown = display(&real); + self.chain.push(real.clone()); + self.levels += 1; + self.frames.push(Frame { shown: shown.clone(), dir: folder_of(&real) }); + let r = self.expand(shown, folder_of(&real), &text, false); + if r.is_err() { + self.end_eval(); + } + r + } + + /// The file `$.evalFile` ran has ended. + pub(crate) fn end_eval(&mut self) { + if self.frames.len() > 1 { + self.frames.pop(); + self.chain.pop(); + self.levels = self.levels.saturating_sub(1); + } + } + + /// Checks a file read at `real` against the run's limits and the files open now, and decodes + /// it. `value` is the path as the script wrote it. + fn admit(&mut self, real: &Path, bytes: Vec, value: &str) -> Result { + if self.chain.iter().any(|p| p == real) { + return Err((FailKind::Error, format!("include cycle: {value}"))); + } + if self.levels >= MAX_DEPTH { + return Err((FailKind::Limit, format!("include depth limit ({MAX_DEPTH}) reached"))); + } + if self.files >= MAX_FILES { + return Err((FailKind::Limit, format!("include file limit ({MAX_FILES}) reached"))); + } + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err((FailKind::Limit, "script source limit reached (32 MiB)".to_string())); + } + self.files += 1; + self.bytes += bytes.len(); + decode(&bytes, value).map_err(|m| (FailKind::Error, m)) + } + + /// Finds and reads the file `value` names, from the file in folder `dir`; with `search`, also in + /// the `#includepath` and `JSINCLUDE` folders. + fn open(&mut self, value: &str, dir: Option<&Path>, search: bool) -> Result<(PathBuf, Vec), (FailKind, String)> { + let path = Path::new(value); + let refused = || (FailKind::Error, format!("script file read refused: {value}")); + // A script given as text has no folder, and so no file it may read. + let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) }; + // Each candidate, and whether the scope's refusal passes it over. + let mut candidates: Vec<(Option, bool)> = vec![(Some(dir.join(path)), false)]; + if search && !path.is_absolute() { + candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false))); + candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true))); + } + for (candidate, passed_over_when_refused) in candidates { + let Some(candidate) = candidate else { return Err(refused()) }; + self.probes += 1; + if self.probes > MAX_PROBES { + return Err((FailKind::Limit, format!("include search limit ({MAX_PROBES} paths) reached"))); + } + match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + Ok(found) => return Ok(found), + Err(ScriptRead::Missing) => {} + Err(ScriptRead::Refused) if passed_over_when_refused => {} + Err(ScriptRead::Refused) => return Err(refused()), + Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))), + Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))), + } + } + Err((FailKind::Error, format!("include file not found: {value}"))) + } + + /// `text`, the file `shown` in folder `dir`, with its preprocessor lines read. With `script`, + /// its `#script` line names the run. + fn expand(&mut self, shown: Arc, dir: Option, text: &str, script: bool) -> Result { + let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default() }; + let mut name = None; + self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?; + let source = String::from_utf16(&out.units).map_err(|_| Failure { + kind: FailKind::Syntax, + message: "the script is not valid text".into(), + index: 0, + file: out.map.files.first().cloned().unwrap_or_else(|| Arc::from("")), + line: 0, + column: 0, + })?; + Ok(Expanded { source, map: out.map, name }) + } + + /// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place + /// of their lines. + fn file( + &mut self, + out: &mut Out, + shown: Arc, + dir: Option<&Path>, + text: &str, + script: bool, + name: &mut Option, + ) -> Result<(), Failure> { + let index = out.map.files.len(); + out.map.files.push(shown.clone()); + let units: Vec = text.encode_utf16().collect(); + out.begin(index, 1); + // A source with neither `#` nor `@` has no preprocessor line. + if !units.iter().any(|&u| u == u16::from(b'#') || u == u16::from(b'@')) { + out.emit(&units); + return Ok(()); + } + let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column }; + let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() }; + let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?; + let mut cursor = 0usize; + for d in &program.directives { + let (start, end) = (d.span.start as usize, d.span.end as usize); + let line_start = + units.get(..start).and_then(|u| u.iter().rposition(|&c| matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029))).map_or(0, |i| i + 1); + let column = u32::try_from(start - line_start + 1).unwrap_or(u32::MAX); + let at = |kind, message: String| fail(kind, message, d.line, column); + out.emit(units.get(cursor..start).unwrap_or_default()); + cursor = end; + let label = format!("{}{}", d.form, d.name); + if d.value.len() > MAX_VALUE_BYTES { + return Err(at(FailKind::Syntax, format!("the value of {label} is too long"))); + } + let value = unquote(&d.value).ok_or_else(|| at(FailKind::Syntax, format!("unterminated quote in {label}")))?; + match d.known { + Some(DirectiveName::Include) => { + if value.is_empty() { + return Err(at(FailKind::Syntax, format!("{label} needs a file name"))); + } + let (real, bytes) = self.open(value, dir, true).map_err(|(kind, message)| at(kind, message))?; + let included = self.admit(&real, bytes, value).map_err(|(kind, message)| at(kind, message))?; + self.chain.push(real.clone()); + self.levels += 1; + let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, name); + self.chain.pop(); + self.levels -= 1; + r?; + out.end_line(); + out.begin(index, d.line); + } + Some(DirectiveName::IncludePath) => { + self.include_path = value.split(';').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect(); + } + Some(DirectiveName::Script) => { + if value.is_empty() { + return Err(at(FailKind::Syntax, format!("{label} needs a name"))); + } + if script && index == 0 { + *name = Some(value.to_string()); + } + } + Some(DirectiveName::Target) => { + if value.is_empty() { + return Err(at(FailKind::Syntax, format!("{label} needs a value"))); + } + } + Some(DirectiveName::Strict) => match value.to_ascii_lowercase().as_str() { + "off" => {} + "on" => return Err(at(FailKind::Syntax, format!("unsupported strict checking: {label} on"))), + _ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))), + }, + Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))), + None if d.name.eq_ignore_ascii_case("engine") => { + return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))); + } + None => return Err(at(FailKind::Syntax, format!("unknown script directive: {label}"))), + } + } + out.emit(units.get(cursor..).unwrap_or_default()); + Ok(()) + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 772f2c0164..8f19187584 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -23,12 +23,18 @@ //! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default, //! and the console's ([`console`]). //! +//! Before a run starts, its preprocessor lines are read ([`include`]): included files take the +//! place of their lines, and an error in one is reported at its own file, line and column. +//! `$.evalFile(path)` runs another file in the same global environment and gives its last value, +//! `$.fileName` is the file being run and `$.includePath` the `#includepath` list. +//! //! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line //! there too. The session's console gets a start line, the run's output, its uncaught error, an end //! line and a report line; the run's report holds its own output and error, its time, its host //! calls by kind and its slowest commands. pub mod console; +pub mod include; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -131,7 +137,11 @@ pub(crate) fn refused_text(id: &str) -> String { /// A request to run a script. pub(crate) struct Request { + /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, + pub name_given: bool, + /// The file the script was read from, which its included files are read beside. + pub file: Option, pub source: String, pub args: Map, pub fuel: u64, @@ -468,8 +478,20 @@ struct Host { commands: RefCell>, /// The time the run's slices took, in nanoseconds. run_nanos: Cell, + /// The files the run reads: its includes and `$.evalFile`'s. + files: RefCell, + /// Where the lines of the script's expanded source came from. + script_map: RefCell, + /// The same for each source `$.evalFile` gave, in order. + eval_maps: RefCell>, + /// The last error `$.evalFile` raised for a file it could not run, with the file, line and + /// column that error is at. + eval_failure: RefCell>, } +/// An error `$.evalFile` raised, as thrown, and the file, line and column it is at. +type EvalFailure = (String, Arc, u32, u32); + /// A run's host calls by kind, as its report gives them in `hostCallCounts`. #[derive(Default)] struct Counts { @@ -899,6 +921,8 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) { /// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)` /// gives them, one after another, and `$.writeln(...values)` does the same and ends the line. +/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file +/// being run and `$.includePath` the `#includepath` list. fn dollar_object(host: &Rc) -> Vec<(String, HostItem)> { let writer = |end: bool| { let h = host.clone(); @@ -910,7 +934,67 @@ fn dollar_object(host: &Rc) -> Vec<(String, HostItem)> { Ok(Data::Undefined) })) }; - vec![("write".into(), writer(false)), ("writeln".into(), writer(true))] + let getter = |read: fn(&include::Files) -> String| { + let h = host.clone(); + HostItem::Getter(function(move |_| { + let text = read(&h.files.borrow()); + h.charge_call(text.len() as u64 + 2)?; + Ok(Data::String(text)) + })) + }; + let eval_file = { + let h = host.clone(); + let end = host.clone(); + HostItem::Evaluator { source: function(move |a| eval_file(&h, a)), end: Rc::new(move || end.files.borrow_mut().end_eval()) } + }; + vec![ + ("write".into(), writer(false)), + ("writeln".into(), writer(true)), + ("evalFile".into(), eval_file), + ("fileName".into(), getter(include::Files::file_name)), + ("includePath".into(), getter(include::Files::include_path)), + ] +} + +/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being +/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in +/// milliseconds, is taken and not waited on: the file is read at once. +fn eval_file(host: &Host, args: Vec) -> std::result::Result { + let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else { + return Err(HostError::Type(EVAL_NO_PATH.to_string())); + }; + match args.get(1) { + None | Some(Data::Undefined) => {} + Some(Data::Number(ms)) if ms.is_finite() && *ms >= 0.0 => {} + Some(Data::Number(_)) => return Err(HostError::Range(EVAL_TIMEOUT.to_string())), + Some(_) => return Err(HostError::Type(EVAL_TIMEOUT.to_string())), + } + if args.len() > 2 { + return Err(HostError::Type(EVAL_ARGUMENTS.to_string())); + } + host.charge_call(path.len() as u64 + 2)?; + let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| { + let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message }; + if f.line > 0 { + *host.eval_failure.borrow_mut() = Some((message.clone(), f.file.clone(), f.line, f.column)); + } + match f.kind { + include::FailKind::Limit => HostError::Abort(message), + include::FailKind::Syntax => HostError::Syntax(message), + include::FailKind::Error => HostError::Error(message), + } + })?; + // A file without preprocessor lines is parsed here first, so its syntax error names its place. + let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() }; + if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) { + host.files.borrow_mut().end_eval(); + let (_, file, line, column) = expanded.map.locate(e.line, e.column); + let message = format!("{file}:{line}:{column}: {}", e.message); + *host.eval_failure.borrow_mut() = Some((message.clone(), file, line, column)); + return Err(HostError::Syntax(message)); + } + host.eval_maps.borrow_mut().push(expanded.map); + Ok(Data::String(expanded.source)) } fn function(f: impl Fn(Vec) -> std::result::Result + 'static) -> HostFunction { @@ -974,21 +1058,67 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { } /// `message`, with what to do about a failure that comes from a script written for another program. -fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String { +fn explained(kind: &RunErrorKind, message: &str) -> String { const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - let directive = - *kind == RunErrorKind::Syntax && line > 0 && source.lines().nth(line as usize - 1).is_some_and(|l| l.trim_start().starts_with('#')); if *kind == RunErrorKind::Thrown && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") - } else if directive { - format!("{message} (preprocessor lines such as `#target` and `#include` are not read yet)") } else { message.to_string() } } +/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own. +fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { + let (kind, message) = match f.kind { + include::FailKind::Syntax if f.line > 0 => { + (RunErrorKind::Syntax, format!("SyntaxError: {} (line {}, column {})", f.message, f.line, f.column)) + } + include::FailKind::Syntax => (RunErrorKind::Syntax, format!("SyntaxError: {}", f.message)), + include::FailKind::Error => (RunErrorKind::Thrown, format!("Error: {}", f.message)), + include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message), + }; + let file = (f.index > 0).then_some(f.file); + (RunError { kind, message, line: f.line, column: f.column }, file) +} + +/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]), at the line and column of +/// the file it is in, with that file's name unless it is the script's own. +fn located(host: &Host, tag: u32, e: &RunError) -> (RunError, Option>) { + let map = |m: &include::SourceMap, own: bool| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file)) + }; + // An error `$.evalFile` raised for a file it could not run is at that file's place. + if let Some((_, file, line, column)) = host.eval_failure.borrow().as_ref().filter(|(thrown, ..)| e.message.contains(thrown.as_str())) { + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, *line, *column) } else { e.message.clone() }; + return (RunError { kind: e.kind.clone(), message, line: *line, column: *column }, Some(file.clone())); + } + if e.line == 0 { + return (e.clone(), None); + } + match tag { + 0 => map(&host.script_map.borrow(), true), + n if n != vectorcraft_js::UNKNOWN_SOURCE => match host.eval_maps.borrow().get(n as usize - 1) { + Some(m) => map(m, false), + None => (e.clone(), None), + }, + _ => (e.clone(), None), + } +} + +/// A syntax error's `message`, which ends with its place `(line L, column C)`, with the place +/// given as `line`, `column`. +fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u32) -> String { + let old = format!(" (line {old_line}, column {old_column})"); + match message.strip_suffix(&old) { + Some(m) => format!("{m} (line {line}, column {column})"), + None => message.to_string(), + } +} + impl Session { /// Is a script running? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { @@ -1091,8 +1221,8 @@ impl Session { Ok(()) } - /// Begins a run of `request`. - pub(crate) fn script_start(&mut self, request: Request) -> Result<()> { + /// Begins a run of `request`. → the run's name. + pub(crate) fn script_start(&mut self, request: Request) -> Result { self.settle_for_script()?; // In a build where a fault ends the program, every unsaved document has a copy first. if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { @@ -1103,8 +1233,14 @@ impl Session { self.script_high_water.retain(|uid, _| open.contains(uid)); self.script_stop.clear(); self.script_report = None; + let mut files = include::Files::new(request.file.as_deref(), include::Files::jsinclude_env()); + let expanded = files.expand_script(&request.source); + let name = match &expanded { + Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), + _ => request.name, + }; let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() }; - let options = Options { max_source_units: MAX_SOURCE_BYTES.saturating_mul(2), ..Options::default() }; + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; let mut realm = Realm::with_options(options, limits); realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); @@ -1126,34 +1262,45 @@ impl Session { log_bytes: Cell::new(0), written: RefCell::new(Vec::new()), run: self.script_runs, - name: console::line_name(&request.name), + name: console::line_name(&name), console: RefCell::default(), pending: RefCell::default(), counts: Counts::default(), commands: RefCell::default(), run_nanos: Cell::new(0), + files: RefCell::new(files), + script_map: RefCell::default(), + eval_maps: RefCell::default(), + eval_failure: RefCell::default(), }); let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start }; self.script_console.push(line, false); - let started = realm - .define_host_object("vc", vc_object(&host, args)) - .and_then(|()| realm.define_host_object("$", dollar_object(&host))) - .and_then(|()| realm.start(&request.source)); - if let Err(e) = started { - let mut report = failure_report(&request.name, &e, &request.source, &host, 0, 0); + let started = match expanded { + Err(f) => Err(preprocessor_error(f)), + Ok(expanded) => { + *host.script_map.borrow_mut() = expanded.map; + realm + .define_host_object("vc", vc_object(&host, args)) + .and_then(|()| realm.define_host_object("$", dollar_object(&host))) + .and_then(|()| realm.start(&expanded.source)) + .map_err(|e| located(&host, realm.error_source(), &e)) + } + }; + if let Err((e, file)) = started { + let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); self.script_report = Some(report); return Err(EngineError::Other(message)); } let scope = crate::file_access::ScopeHandle::capture(); - let job = Job { realm, host, world: World::working(self), start_uids: open, name: request.name, scope }; + let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope }; let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); self.script_key = Some(JobKey(id)); - Ok(()) + Ok(name) } /// Advances the running script by one slice. `None` while it is still running; otherwise the @@ -1194,7 +1341,8 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result { let fuel_left = job.realm.fuel_left(); - let mut report = failure_report(&job.name, e, "", &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); + let (e, file) = located(&job.host, job.realm.error_source(), e); + let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); drop(job); raise_ids(self); @@ -1308,13 +1456,16 @@ const TOO_MANY_ARGUMENTS: &str = "vc.run: takes a command id and an object of pa const PARAMS_NOT_OBJECT: &str = "vc.run: the parameters must be an object"; const LOG_FULL: &str = "vc.log: the log of this run is full"; const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run"; +const EVAL_NO_PATH: &str = "$.evalFile requires a file path"; +const EVAL_TIMEOUT: &str = "$.evalFile: the timeout must be a finite number of milliseconds, 0 or more"; +const EVAL_ARGUMENTS: &str = "$.evalFile: takes a file path and a timeout"; -/// The report of a run that failed. -fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { - json!({ +/// The report of a run that failed; `file` is the included file the error is in. +fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { + let mut report = json!({ "ok": false, "kind": kind_id(&e.kind), - "message": explained(&e.kind, &e.message, source, e.line), + "message": explained(&e.kind, &e.message), "name": name, "line": e.line, "column": e.column, @@ -1323,7 +1474,11 @@ fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left "fuelLeft": fuel_left, "fuelUsed": fuel_used, "hostCalls": host.calls.get(), - }) + }); + if let (Some(file), Some(o)) = (file, report.as_object_mut()) { + o.insert("file".into(), json!(file)); + } + report } /// How the run that failed with `kind` ended, as its console end line gives it. @@ -1361,8 +1516,11 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: if report["ok"] == false { let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); let message = report["message"].as_str().unwrap_or_default(); - let text = - if line > 0 { format!("{}:{line}:{column}: {message}", host.name) } else { format!("{}: location unavailable: {message}", host.name) }; + let text = match report["file"].as_str() { + Some(file) if line > 0 => format!("{}: {file}:{line}:{column}: {message}", host.name), + _ if line > 0 => format!("{}:{line}:{column}: {message}", host.name), + _ => format!("{}: location unavailable: {message}", host.name), + }; each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } let timing = clock().is_some(); @@ -1386,7 +1544,11 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: fn failure_text(report: &Value) -> String { let s = |k: &str| report[k].as_str().unwrap_or_default(); let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); - let at = if line > 0 { format!(" line {line}, column {column}") } else { String::new() }; + let at = match report["file"].as_str() { + Some(file) if line > 0 => format!(" line {line}, column {column} of {file}"), + _ if line > 0 => format!(" line {line}, column {column}"), + _ => String::new(), + }; let written = report["written"].as_array().map_or(0, Vec::len); let kept = if written > 0 { let paths: Vec<&str> = report["written"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); @@ -1454,4 +1616,6 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the `JSINCLUDE` folders in place of the environment's. + pub(crate) static TEST_JSINCLUDE: RefCell>> = const { RefCell::new(None) }; } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 72b6d3ea80..c55327895b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -151,6 +151,7 @@ mod save; mod saveoptions; mod scalestrokes; mod script_console; +mod script_include; mod script_run; mod scripts; mod select_ids_first; diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs new file mode 100644 index 0000000000..f0cf7a7535 --- /dev/null +++ b/crates/engine/src/tests/script_include.rs @@ -0,0 +1,327 @@ +//! A script's preprocessor lines: `#include` and `//@include` in place, the folders they are looked +//! for in, the run's limits and scope, the other lines, `$.evalFile`, `$.fileName`, and errors at the +//! line of the file they are in. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::script::TEST_JSINCLUDE; +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-include-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, text: &str) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +/// Runs `main/main.jsx` in `base`, with the text `text`. +fn run(base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, text); + Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// The report of the run that failed with `e`. +fn failed(base: &Path, text: &str) -> Value { + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, text); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + assert!(e.is_err(), "the run failed: {e:?}"); + s.script_report().unwrap().clone() +} + +#[test] +fn script_include_sibling_runs_in_place() { + let base = folder("sibling"); + write(&base.join("main/lib.jsxinc"), "var b = a + 1;"); + write(&base.join("main/two.jsxinc"), "b = b * 10;\r\n"); + let r = run(&base, "var a = 1;\n #include \"lib.jsxinc\"\n//@include 'two.jsxinc'\nvc.log(a + b);").unwrap(); + assert_eq!(r["log"], json!([21])); + // A file may be included again once its earlier inclusion has ended. + let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include \"three.jsxinc\"\nvc.log(n);"); + assert!(r.is_err(), "three.jsxinc is missing"); + write(&base.join("main/three.jsxinc"), "n++;"); + let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include three.jsxinc\nvc.log(n);").unwrap(); + assert_eq!(r["log"], json!([2])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_nested_include_uses_including_folder() { + let base = folder("nested"); + write(&base.join("main/sub/one.jsxinc"), "#include \"two.jsxinc\"\nvar one = two + 1;"); + write(&base.join("main/sub/two.jsxinc"), "var two = 2;"); + write(&base.join("main/two.jsxinc"), "var two = 200;"); + let r = run(&base, "#include \"sub/one.jsxinc\"\nvc.log(one);").unwrap(); + assert_eq!(r["log"], json!([3]), "two.jsxinc beside one.jsxinc, not beside the script"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_missing_include_reports_origin() { + let base = folder("missing"); + let report = failed(&base, "vc.log(1);\n\t#include \"nope.jsxinc\"\n"); + assert_eq!(report["kind"], "thrown"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(2))); + assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}"); + assert_eq!(report["log"], json!([]), "nothing ran before the include was read"); + assert!(report.get("file").is_none(), "the line is the script's own"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_includepath_searches_in_order() { + let base = folder("includepath"); + write(&base.join("main/a/x.jsxinc"), "var x = 'a';"); + write(&base.join("main/b/x.jsxinc"), "var x = 'b';"); + write(&base.join("main/b/y.jsxinc"), "var y = 'b';"); + let r = run(&base, "#includepath \"a; b\"\n#include \"x.jsxinc\"\n#include \"y.jsxinc\"\nvc.log(x + y + $.includePath);").unwrap(); + assert_eq!(r["log"], json!(["aba;b"])); + // A later #includepath replaces the list. + let report = failed(&base, "#includepath \"b\"\n#includepath \"a\"\n#include \"y.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("include file not found: y.jsxinc"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_include_cycle_and_depth_stop() { + let base = folder("cycle"); + write(&base.join("main/a.jsxinc"), "#include \"b.jsxinc\""); + write(&base.join("main/b.jsxinc"), "\n#include \"a.jsxinc\""); + let report = failed(&base, "#include \"a.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("include cycle: a.jsxinc"), "{report}"); + assert_eq!(report["line"], 2); + assert!(report["file"].as_str().unwrap().ends_with("b.jsxinc"), "{report}"); + // A script that includes itself. + let report = failed(&base, "#include \"main.jsx\""); + assert!(report["message"].as_str().unwrap().contains("include cycle"), "{report}"); + for i in 0..20 { + write(&base.join(format!("main/d{i}.jsxinc")), &format!("#include \"d{}.jsxinc\"", i + 1)); + } + let report = failed(&base, "#include \"d0.jsxinc\""); + assert_eq!(report["kind"], "limit"); + assert!(report["message"].as_str().unwrap().contains("include depth limit (16) reached"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("d15.jsxinc"), "the 17th level is refused: {report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere. +/// `false` when the system does not allow it here. +fn link_folder(target: &Path, link: &Path) -> bool { + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok() + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + +#[test] +fn script_include_link_out_of_the_folder_is_refused() { + let base = folder("junction"); + write(&base.join("outside/x.jsxinc"), "var leaked = 1;"); + // `mklink` reads a `/` in its paths as a switch, so each name is joined on its own. + if !link_folder(&base.join("outside"), &base.join("main").join("away")) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(std::fs::canonicalize(base.join("main/away/x.jsxinc")).unwrap().starts_with(std::fs::canonicalize(base.join("outside")).unwrap())); + let report = failed(&base, "#include \"away/x.jsxinc\"\nvc.log(leaked);"); + assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}"); + let report = failed(&base, "$.evalFile('away/x.jsxinc');"); + assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_include_parent_component_refused() { + let base = folder("parent"); + write(&base.join("outside.jsxinc"), "var leaked = 1;"); + write(&base.join("main/sub/x.jsxinc"), "var x = 1;"); + let report = failed(&base, "#include \"../outside.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused: ../outside.jsxinc"), "{report}"); + // Refused even where the path would come back inside the folder. + let report = failed(&base, "#include \"sub/../sub/x.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused"), "{report}"); + let report = failed(&base, "#includepath \"..\"\n#include \"outside.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused: outside.jsxinc"), "{report}"); + let absolute = base.join("outside.jsxinc").to_string_lossy().replace('\\', "/"); + let report = failed(&base, &format!("#include \"{absolute}\"")); + assert!(report["message"].as_str().unwrap().contains("script file read refused"), "an absolute path outside: {report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_jsinclude_outside_grants_ignored() { + let base = folder("jsinclude"); + write(&base.join("outside/x.jsxinc"), "var x = 'outside';"); + write(&base.join("main/lib/y.jsxinc"), "var y = 'lib';"); + TEST_JSINCLUDE.with(|t| *t.borrow_mut() = Some(vec![base.join("outside"), base.join("main/lib")])); + let report = failed(&base, "#include \"x.jsxinc\""); + let r = run(&base, "#include \"y.jsxinc\"\nvc.log(y);"); + TEST_JSINCLUDE.with(|t| *t.borrow_mut() = None); + assert!(report["message"].as_str().unwrap().contains("include file not found: x.jsxinc"), "passed over, not refused: {report}"); + assert_eq!(r.unwrap()["log"], json!(["lib"]), "a JSINCLUDE folder inside the script's folder is searched"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_target_other_app_does_not_route() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "#target someapp-12\n#target \"other\"\n//@target x\n#strict off\nvc.log(1);"})).unwrap(); + assert_eq!(r["log"], json!([1])); + for (source, message) in [ + ("#target\nvc.log(1);", "#target needs a value"), + ("#targetengine \"session\"", "unsupported script directive: #targetengine"), + ("#engine \"main\"", "unsupported script directive: #engine"), + ("#strict on", "unsupported strict checking: #strict on"), + ("#strict maybe", "#strict takes on or off"), + ("#frobnicate 1", "unknown script directive: #frobnicate"), + ("#include \"x.jsxinc", "unterminated quote in #include"), + ("#include \"x.jsxinc\"", "script file read refused: x.jsxinc"), + ] { + let e = s.execute("script.run", &json!({"source": format!("vc.log(0);\n{source}")})).unwrap_err().to_string(); + assert!(e.contains(message), "{source}: {e}"); + assert_eq!(s.script_report().unwrap()["line"], 2, "{source}"); + assert_eq!(s.script_report().unwrap()["log"], json!([]), "{source}"); + } + // An unknown `//@` name stays a comment. + assert_eq!(s.execute("script.run", &json!({"source": "//@frobnicate 1\nvc.log(2);"})).unwrap()["log"], json!([2])); +} + +#[test] +fn script_name_comes_from_the_script_line() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "#script \"First\"\n#script Second\nvc.log($.fileName);"})).unwrap(); + assert_eq!((r["name"].as_str(), r["log"].clone()), (Some("Second"), json!([""]))); + let r = s.execute("script.run", &json!({"source": "#script Second\n", "name": "given.js"})).unwrap(); + assert_eq!(r["name"], "given.js", "a name given to script.run wins"); + let base = folder("name"); + write(&base.join("main/lib.jsxinc"), "#script Inner\n"); + let r = run(&base, "#include \"lib.jsxinc\"").unwrap(); + assert_eq!(r["name"], "main.jsx", "an included file's #script line does not rename the run"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_strict_on_is_refused() { + let mut s = Session::new(); + let e = s.execute("script.run", &json!({"source": "#strict on\nvc.log(1);"})).unwrap_err().to_string(); + assert!(e.contains("unsupported strict checking: #strict on"), "{e}"); + assert_eq!(s.script_report().unwrap()["kind"], "syntax"); +} + +#[test] +fn script_eval_file_returns_last_value_and_shares_globals() { + let base = folder("evalfile"); + write(&base.join("main/sub/e.jsx"), "var inner = $.fileName;\nfunction h(x) { return x * g; }\n#include \"f.jsxinc\"\ng + f;"); + write(&base.join("main/sub/f.jsxinc"), "var f = 40;"); + write(&base.join("main/empty.jsx"), ""); + let r = run( + &base, + "var g = 2;\nvar r = $.evalFile('sub/e.jsx', 1000);\nvc.log(r);\nvc.log(h(3));\nvc.log(/e\\.jsx$/.test(inner));\nvc.log(/main\\.jsx$/.test($.fileName));\nvc.log($.evalFile('empty.jsx') === undefined);", + ) + .unwrap(); + assert_eq!(r["log"], json!([42, 6, true, true, true])); + // Its errors can be caught; a file is evaluated again after it has returned. + let r = run( + &base, + "var g = 1; var out = [];\ntry { $.evalFile(''); } catch (e) { out.push(e.name); }\ntry { $.evalFile('nope.jsx'); } catch (e) { out.push(String(e)); }\ntry { $.evalFile('sub/e.jsx', -1); } catch (e) { out.push(e.name); }\ntry { $.evalFile('sub/e.jsx', Infinity); } catch (e) { out.push(e.name); }\nout.push($.evalFile('sub/e.jsx') + $.evalFile('sub/e.jsx'));\nvc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["TypeError", "Error: include file not found: nope.jsx", "RangeError", "TypeError", 82]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_eval_file_outside_scope_refused() { + let base = folder("evaloutside"); + write(&base.join("outside.jsx"), "1;"); + let absolute = base.join("outside.jsx").to_string_lossy().replace('\\', "/"); + let script = format!( + "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile('{absolute}'); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" + ); + let r = run(&base, &script).unwrap(); + let out = r["log"][0].as_array().unwrap(); + assert_eq!(out.len(), 2); + for e in out { + assert!(e.as_str().unwrap().starts_with("Error: script file read refused"), "{e}"); + } + // A script given as text has no folder to read from. + let e = Session::new().execute("script.run", &json!({"source": "$.evalFile('x.jsx');"})).unwrap_err().to_string(); + assert!(e.contains("script file read refused: x.jsx"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_directives_in_strings_and_block_comments_are_inert() { + let mut s = Session::new(); + let source = "#target x\nvar a = '#include \"nope.jsxinc\"';\n/*\n#include \"nope.jsxinc\"\n//@include \"nope.jsxinc\"\n*/\nvar b = 1; // #include \"nope.jsxinc\"\nvar c = 2; #include\nvc.log(a.length + b);"; + let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string(); + // `#` after code on a line is not a preprocessor line: the script has a syntax error there. + assert!(e.contains("line 8"), "{e}"); + let source = source.replace("var c = 2; #include\n", ""); + assert_eq!(s.execute("script.run", &json!({"source": source})).unwrap()["log"], json!([23])); +} + +#[test] +fn script_included_error_has_local_file_and_line() { + let base = folder("errors"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\n\n throw new Error('boom');\n"); + write(&base.join("main/bad.jsxinc"), "var y = 1;\nvar = 2;\n"); + write(&base.join("main/five.jsxinc"), "1;\n2;\n3;\n4;\n5;"); + write(&base.join("main/sub/thrower.jsx"), "\n\nthrow new Error('deep');"); + let mut s = Session::new(); + let report = failed(&base, "var z = 0;\n#include \"lib.jsxinc\""); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(5)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("lib.jsxinc"), "{report}"); + let report = failed(&base, "#include \"bad.jsxinc\""); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("bad.jsxinc"), "{report}"); + // A line of the script after an include keeps its own number. + let report = failed(&base, "#include \"five.jsxinc\"\n throw new Error('after');"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(3)), "{report}"); + assert!(report.get("file").is_none(), "{report}"); + let report = failed(&base, "#include \"five.jsxinc\"\nvar = 1;"); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + // An uncaught error in a file $.evalFile ran is at that file's line. + let report = failed(&base, "var a = 1;\n$.evalFile('sub/thrower.jsx');"); + assert_eq!(report["line"], 3, "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("thrower.jsx"), "{report}"); + // So is a file $.evalFile could not run: a syntax error, or a bad preprocessor line. + write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;"); + write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1"); + for (file, line) in [("broken.jsx", 3), ("directive.jsx", 2)] { + let report = failed(&base, &format!("var a = 1;\n$.evalFile('sub/{file}');")); + assert_eq!(report["line"], line, "{report}"); + assert!(report["file"].as_str().unwrap().ends_with(file), "{report}"); + } + // The console's error line names the file. + let main = base.join("main/main.jsx"); + write(&main, "#include \"lib.jsxinc\""); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err()); + let console = s.execute("script.console", &json!({})).unwrap(); + let error = console["lines"].as_array().unwrap().iter().find(|l| l["kind"] == "error").unwrap()["text"].as_str().unwrap().to_string(); + assert!(error.starts_with("main.jsx: ") && error.contains("lib.jsxinc:3:5: Error: boom"), "{error}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index eba254116a..8294aa638a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -166,7 +166,7 @@ fn an_error_names_the_script_its_place_and_kind() { let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); - assert!(run(&mut s, "#target x\n1").unwrap_err().to_string().contains("#target")); + assert!(run(&mut s, "#targetengine x\n1").unwrap_err().to_string().contains("unsupported script directive: #targetengine")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -989,6 +989,15 @@ fn source_text() -> impl proptest::strategy::Strategy { Just("{".to_string()), Just("try {".to_string()), Just("} catch (e) {}".to_string()), + Just("\n#include \"x.jsxinc\"\n".to_string()), + Just("\n//@include 'x\n".to_string()), + Just("\n#includepath \";;..;\"\n".to_string()), + Just("\n#script \"\"\n".to_string()), + Just("\n#target\n".to_string()), + Just("\n#strict on\n".to_string()), + Just("\n#\u{0}\n".to_string()), + Just("try { $.evalFile('x.jsx', NaN); } catch (e) {}".to_string()), + "\n#[a-z]{0,12}[ -~]{0,20}\n", "[ -~]{0,30}", "\\PC{0,10}", ]; diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index d420b94b31..62f6ade7a9 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -472,7 +472,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), }; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag }); let code = match compile_constructed_function(&program, &source) { Ok(Some(code)) => code, Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), @@ -501,7 +501,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> return Ok(Value::String(Str::from_units(units.to_vec()))); } Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), - Some(Func::Host { name, .. } | Func::Data { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), }; diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index b23d9a525d..0a666d1f25 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -171,6 +171,8 @@ pub(crate) struct Handler { pub(crate) struct Source { pub(crate) lines: LineTable, pub(crate) text: Rc<[u16]>, + /// Which source this is, as [`crate::Realm::error_source`] gives it. + pub(crate) tag: u32, } #[derive(Debug)] diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 1399c05701..b229ce6e6c 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -176,13 +176,15 @@ pub(crate) enum NativeKind { /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. /// `Data` is a host function given [`crate::Data`]; with `text`, each argument arrives as the -/// string `String(value)` gives. +/// string `String(value)` gives. `Eval` is a host function that gives source to run as global code +/// ([`crate::HostItem::Evaluator`]); `end` is called when that code ends. #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, text: bool }, + Eval { f: DataFn, end: Rc, name: Rc }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 888fb3d95b..b725245ce8 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -55,6 +55,8 @@ pub enum HostError { Type(String), /// Thrown to the script as a `RangeError`. Range(String), + /// Thrown to the script as a `SyntaxError`. + Syntax(String), /// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it. Abort(String), } @@ -74,6 +76,16 @@ pub enum HostItem { Getter(HostFunction), /// A frozen object with these members. Object(Vec<(String, HostItem)>), + /// A function whose host function gives JavaScript source as a string, which then runs as + /// global code in the realm, as an indirect `eval` runs it, with the run's fuel and limits: + /// the call gives that code's completion value, and its declarations become globals. A result + /// that is not a string is the call's result. `end` is called when the source has run, + /// normally or not. Each source given has the next tag of [`crate::Realm::error_source`], + /// from 1. + Evaluator { + source: HostFunction, + end: Rc, + }, } enum Step { @@ -280,6 +292,39 @@ impl Interp { /// Calls host function `f`: reads its arguments (with `text`, each as the string `String(value)` /// gives), runs it, and gives its result to the script. pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], text: bool) -> JsResult { + let data = self.read_args(name, args, text)?; + match f(data) { + Ok(d) => self.write_data(d, 0, false), + Err(e) => Err(self.host_error(e)?), + } + } + + /// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the + /// source it gives as global code, as an indirect `eval` does, giving that code's completion + /// value. A result that is not a string is given to the script as it is. `end` is called once + /// the source has run, normally or not. + pub(crate) fn call_evaluator(&mut self, f: &crate::heap::DataFn, end: &Rc, name: &Rc, args: &[Value]) -> JsResult { + let data = self.read_args(name, args, false)?; + let source = match f(data) { + Ok(Data::String(source)) => source, + Ok(d) => return self.write_data(d, 0, false), + Err(e) => return Err(self.host_error(e)?), + }; + self.evaluated = self.evaluated.saturating_add(1); + let tag = std::mem::replace(&mut self.source_tag, self.evaluated); + let code = self.encode_source(&source).and_then(|units| self.compile_source(&units, false, crate::bytecode::CodeKind::Eval)); + self.source_tag = tag; + let r = match code { + Ok(code) => self.run_global(code, true), + Err(e) => Err(self.compile_error_to_abrupt(e)), + }; + end(); + r + } + + /// The arguments of host function `name` as [`Data`] (with `text`, each as the string + /// `String(value)` gives). + fn read_args(&mut self, name: &Rc, args: &[Value], text: bool) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. @@ -302,15 +347,20 @@ impl Interp { } self.temp_roots.truncate(mark); read?; - match f(data) { - Ok(d) => self.write_data(d, 0, false), - Err(HostError::Abort(message)) => { + Ok(data) + } + + /// What host error `e` throws, or the limit it ends the run with. + fn host_error(&mut self, e: HostError) -> JsResult { + match e { + HostError::Abort(message) => { self.host_abort = Some(message); - Err(Abrupt::Limit(LimitKind::Host)) + Ok(Abrupt::Limit(LimitKind::Host)) } - Err(HostError::Error(message)) => Err(self.throw_host(ErrorType::Error, &message)?), - Err(HostError::Type(message)) => Err(self.throw_host(ErrorType::Type, &message)?), - Err(HostError::Range(message)) => Err(self.throw_host(ErrorType::Range, &message)?), + HostError::Error(message) => self.throw_host(ErrorType::Error, &message), + HostError::Type(message) => self.throw_host(ErrorType::Type, &message), + HostError::Range(message) => self.throw_host(ErrorType::Range, &message), + HostError::Syntax(message) => self.throw_host(ErrorType::Syntax, &message), } } @@ -361,6 +411,11 @@ impl Interp { HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE }, HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, + HostItem::Evaluator { source, end } => { + let proto = self.intrinsics.function_proto; + let f = self.heap.alloc_object(Object::new(Class::Function(Func::Eval { f: source, end, name: full.into() }), Some(proto))); + Prop::Data { value: Value::Object(f), flags: ENUMERABLE } + } }; self.define(o, key(&name), prop) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ee711ffb3a..22bbb6c0d3 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -185,6 +185,12 @@ pub(crate) struct Interp { pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. pub(crate) data_limits: crate::DataLimits, + /// The tag the source compiled next gets ([`crate::Realm::error_source`]). + pub(crate) source_tag: u32, + /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. + pub(crate) evaluated: u32, + /// The tag of the source the last run's error was raised in. + pub(crate) error_tag: u32, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -376,6 +382,9 @@ impl Interp { pause: Rc::default(), host_abort: None, data_limits: crate::DataLimits::default(), + source_tag: crate::realm::UNKNOWN_SOURCE, + evaluated: 0, + error_tag: crate::realm::UNKNOWN_SOURCE, }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -1851,6 +1860,7 @@ impl Interp { // keeps itself reachable. return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?)); } + Func::Eval { f, end, name } => return Ok(Prepared::Done(self.call_evaluator(&f, &end, &name, &args)?)), Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); return match host(&js_args) { @@ -2123,7 +2133,7 @@ impl Interp { let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); let options = Options { strict, max_source_units: remaining, ..self.options.clone() }; let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag }); compile_program(&program, &source, kind).map_err(|e| match e { CompileFail::Syntax(s) => CompileError::Syntax(s), CompileFail::Internal(m) => CompileError::Internal(m), diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 03d9e6639f..c7f69ec9b6 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -774,7 +774,7 @@ fn deep_nesting_compiles_on_a_small_stack() { // ---- the verifier ---- fn code(ops: Vec) -> Code { - let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()) }); + let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()), tag: 0 }); Code { positions: vec![0; ops.len()], ops, diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a95a4b8847..67ee2712c9 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -69,7 +69,7 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Data, DataLimits, HostError, HostFunction, HostItem}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a28b150a52..beaad25574 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -58,6 +58,10 @@ pub enum LimitKind { Host, } +/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an +/// evaluator's: code that `eval` or `Function` compiled, or an error with no place. +pub const UNKNOWN_SOURCE: u32 = u32::MAX; + /// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run /// it cannot pause. pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; @@ -218,10 +222,17 @@ impl Realm { interp.throw_site = None; interp.last_thrown = Value::Undefined; interp.host_abort = None; + interp.error_tag = UNKNOWN_SOURCE; let strict = interp.options.strict; - match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { + interp.source_tag = 0; + let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); + interp.source_tag = UNKNOWN_SOURCE; + match code { Ok(code) => Ok(code), - Err(CompileError::Syntax(e)) => Err(e.into()), + Err(CompileError::Syntax(e)) => { + interp.error_tag = 0; + Err(e.into()) + } Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), } } @@ -229,7 +240,9 @@ impl Realm { /// The end of a run: its completion value or error, with the interpreter's stacks emptied. fn outcome(&mut self, result: Result) -> Result { let interp = &mut self.interp; - let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc)); + let site = interp.throw_site.take(); + interp.error_tag = site.as_ref().map_or(UNKNOWN_SOURCE, |(code, _)| code.source.tag); + let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc)); interp.stack.clear(); interp.frames.clear(); interp.temp_roots.clear(); @@ -299,6 +312,13 @@ impl Realm { self.interp.interrupt = interrupt.0.clone(); } + /// Which source the last error's `line` and `column` are in: 0 for the script given to + /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a + /// [`crate::HostItem::Evaluator`] gave in this realm, and [`UNKNOWN_SOURCE`] otherwise. + pub fn error_source(&self) -> u32 { + self.interp.error_tag + } + /// Fuel the run has left. pub fn fuel_left(&self) -> u64 { self.interp.fuel diff --git a/docs/mcp.md b/docs/mcp.md index 19f16205cd..5edb74d7e7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1549,7 +1549,7 @@ describes that menu item. Pass exactly one of `path` and `source`. A `path` must case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through the global object `vc`, and writes to the Script Console through `$`: +app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -1561,9 +1561,41 @@ app through the global object `vc`, and writes to the Script Console through `$` - `vc.log(value)` adds a value to the report and a line to the Script Console. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. +- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global + environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty + file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file + is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a + missing file and a refused path throw errors the script can catch. +- `$.fileName` is the file being run, which is the file `$.evalFile` is running while it runs, and is empty for a + script given as `source`. `$.includePath` is the current `#includepath` list, separated by `;`. - `vc.args` is the `args` object. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +Before any of the script runs, its preprocessor lines are read. The help page +https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and +https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` +and `$.includePath`. A line counts when it starts with `#` or `//@`, after blanks only, outside strings and comments. +VectorCraft reads them by these rules of its own: + +- `#include "file"` and `//@include "file"` put the text of that file in place of the line. A value with spaces or + punctuation goes in single or double quotes. The file is looked for beside the file that includes it, then in each + `#includepath` folder in turn, then in each folder of the `JSINCLUDE` environment variable (absolute folders + separated by `;`). The included file must be a whole script on its own. A file may be included again after its + earlier inclusion has ended, and a file that includes itself, directly or through others, is an error. +- `#includepath "a;b"` sets the folders `#include` looks in, separated by `;`. A relative folder is relative to the + folder of the file that includes. A later `#includepath` replaces the list. +- `#script "name"` names the run in the report and the Script Console, unless `name` is given. A `#script` line in an + included file does not rename the run. +- `#target` takes any value and does not change how the script runs. `#strict off` is taken. +- `#strict on`, `#targetengine` and `#engine` end the run with an unsupported-directive error, and any other `#name` + with an unknown-directive error. A `//@` line with another name is a comment. +- A script run from a file reads its included files and the files `$.evalFile` runs only in that file's folder and + the folders below it. A path with a `..` name, a path that leads out of the folder through a link or a junction, a + Windows device name or stream, and a computer on the network are refused, and so is every path for a script given as + `source`. A `JSINCLUDE` folder outside the script's folder is passed over. +- A missing or refused included file ends the run before any of it runs. An error in an included file or a file `$.evalFile` + ran is reported at that file's line and column, and the report's `file` names the file. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app @@ -1590,7 +1622,8 @@ VectorCraft sets these limits itself: | Limit | Value | |-------|-------| -| Source text | 8 MiB | +| Source text | 8 MiB a file, 32 MiB in all | +| Included and evaluated files | 64 in all, 16 levels deep, 1,024 paths looked up | | Heap | 256 MiB (128 MiB on the web) | | Host calls | 2,000,000 | | `maxFuel`, instructions in all | 1 to 100,000,000,000; 1,000,000,000 by default | @@ -1607,7 +1640,8 @@ In the app, a script past the growth limit stops at a question to continue or to with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console}`. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same -fields after `kind`, `message`, `line`, `column` and `fuelLeft`. `answers` takes only an empty object, since scripts +fields after `kind`, `message`, `line`, `column`, `file` (when the error is in another file than the script) and +`fuelLeft`. `answers` takes only an empty object, since scripts have no prompts yet. - `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are @@ -1626,7 +1660,8 @@ vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args" ``` Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and -`$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message`, its end, and a report of +`$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another +file), its end, and a report of its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, carriage returns and the two together break lines, and other control characters show as their Unicode Control Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8fc74c474..b8e15f7b2a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -728,6 +728,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, and `#strict on`, `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). From df0373aa266428f3e0b574c81b86b6581a10d98d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:14:01 -0800 Subject: [PATCH 28/83] Scripts: alert, confirm and prompt open dialogs with Stop, and headless runs take their answers from script.run alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) are globals in a script run. In the app the run waits at the call for the person's answer, spends no instructions while it waits, and every dialog has Stop, which ends the run and puts every document back. A run over MCP or the command line takes its answers in order from script.run's answers, a list of {kind, value} records; a missing, mismatched or unused answer ends the run. The report lists each dialog with its answer in dialogs, with dialogCount and dialogsTruncated. The interpreter gains a host call that waits at the call for its result, from the script's own code only; a dialog called in a callback of a built-in, a getter or a conversion throws in the app. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 11 +- crates/engine/src/script/console.rs | 2 +- crates/engine/src/script/dialogs.rs | 364 +++++++++++++++++++++ crates/engine/src/script/mod.rs | 58 +++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dialogs.rs | 289 ++++++++++++++++ crates/js/src/heap.rs | 5 +- crates/js/src/host.rs | 86 ++++- crates/js/src/host_tests.rs | 78 +++++ crates/js/src/interp.rs | 15 +- crates/js/src/lib.rs | 2 +- crates/js/src/realm.rs | 52 ++- crates/ui-egui/src/app.rs | 6 +- crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/script_run.rs | 179 +++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/script_runs.rs | 37 ++- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_dialogs.rs | 256 +++++++++++++++ docs/mcp.md | 57 +++- docs/target-app-parity.md | 1 + 47 files changed, 1482 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/script/dialogs.rs create mode 100644 crates/engine/src/tests/script_dialogs.rs create mode 100644 crates/ui-egui/src/tests/script_dialogs.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 1ed75194bd..525d6d3a4a 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter or a conversion and throws there, and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's text (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -122,10 +122,9 @@ fn run(s: &mut Session, p: &Value) -> Result { if serde_json::to_vec(&args).map_or(true, |b| b.len() > script::MAX_ARGS_BYTES) { return Err(param("`args` is larger than 1 MiB")); } - match p.get("answers") { - None => {} - Some(Value::Object(o)) if o.is_empty() => {} - Some(_) => return Err(param("`answers` must be an empty object: scripts cannot ask questions yet")), + let answers = script::dialogs::parse_answers(p.get("answers")).map_err(param)?; + if s.script_frames && !answers.is_empty() { + return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog")); } let fuel = max_fuel(p)?; let text = match (path, source) { @@ -153,7 +152,7 @@ fn run(s: &mut Session, p: &Value) -> Result { _ => return Err(param("give exactly one of `path` and `source`")), }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); - s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?; + s.script_start(script::Request { name: name.clone(), source: text, args, fuel, answers })?; if s.script_frames { return Ok(json!({"running": true, "name": name})); } diff --git a/crates/engine/src/script/console.rs b/crates/engine/src/script/console.rs index eda6feeb42..5a3b40ffe3 100644 --- a/crates/engine/src/script/console.rs +++ b/crates/engine/src/script/console.rs @@ -207,7 +207,7 @@ impl Console { /// `c` as the console shows it: a control character as its Control Picture, a line or paragraph /// separator as U+2424, anything else as it is. -fn shown(c: char) -> char { +pub(crate) fn shown(c: char) -> char { match c { '\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'), '\u{7f}' => '\u{2421}', diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs new file mode 100644 index 0000000000..8800c47a02 --- /dev/null +++ b/crates/engine/src/script/dialogs.rs @@ -0,0 +1,364 @@ +//! `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and +//! `prompt(message, preset[, title])`: the dialogs a script opens while it runs. +//! +//! A message and a preset arrive as the string `String(value)` gives, a title the same way unless +//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the +//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and +//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! +//! In the app the run waits at the call for the person's answer, and spends no fuel while it +//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with +//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no +//! answer left, or with the next answer for another kind of dialog, ends the run. The report's +//! `dialogs` lists each dialog and its answer. +//! +//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], +//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and +//! [`MAX_RECORD_BYTES`]. + +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; + +use super::{Host, console}; + +/// The most bytes (UTF-8) of a dialog's message. +pub const MAX_MESSAGE_BYTES: usize = 16 << 10; +/// The most bytes (UTF-8) of a dialog's title. +pub const MAX_TITLE_BYTES: usize = 256; +/// The most bytes (UTF-8) of a prompt's preset and of the text it returns. +pub const MAX_PROMPT_BYTES: usize = 16 << 10; +/// The most answers `script.run` takes. +pub const MAX_ANSWERS: usize = 10_000; +/// The most bytes of `answers`, as JSON. +pub const MAX_ANSWERS_BYTES: usize = 1 << 20; +/// The most dialogs a report lists. +pub const MAX_RECORDS: usize = 10_000; +/// The most bytes of the dialogs a report lists, as JSON. +pub const MAX_RECORD_BYTES: usize = 1 << 20; +/// A dialog's title when the script gives none, in English; the app translates it when it shows it. +pub const DEFAULT_TITLE: &str = "Script Alert"; + +/// Which dialog a script opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DialogKind { + Alert, + Confirm, + Prompt, +} + +impl DialogKind { + /// The function's name, which is also the `kind` of an answer and of a report's dialog. + pub fn id(self) -> &'static str { + match self { + Self::Alert => "alert", + Self::Confirm => "confirm", + Self::Prompt => "prompt", + } + } +} + +/// A dialog a script opened, which waits for its answer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScriptDialog { + pub kind: DialogKind, + pub message: String, + /// `None`: the script gave no title ([`DEFAULT_TITLE`]). + pub title: Option, + /// `alert`: show the error icon. + pub error_icon: bool, + /// `confirm`: No is the default button. + pub no_as_default: bool, + /// `prompt`: the text its field starts with. + pub preset: String, +} + +/// The answer to a [`ScriptDialog`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DialogAnswer { + /// OK, for `alert`. + Ok, + /// Yes (`true`) or No, for `confirm`. + Confirm(bool), + /// OK with the field's text, or Cancel (`None`), for `prompt`. + Prompt(Option), +} + +impl DialogAnswer { + pub fn kind(&self) -> DialogKind { + match self { + Self::Ok => DialogKind::Alert, + Self::Confirm(_) => DialogKind::Confirm, + Self::Prompt(_) => DialogKind::Prompt, + } + } + + /// What the function returns. + fn data(&self) -> Data { + match self { + Self::Ok => Data::Undefined, + Self::Confirm(b) => Data::Bool(*b), + Self::Prompt(Some(t)) => Data::String(t.clone()), + Self::Prompt(None) => Data::Null, + } + } + + /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + fn json(&self) -> Value { + match self { + Self::Ok => json!("ok"), + Self::Confirm(b) => json!(b), + Self::Prompt(t) => json!(t), + } + } +} + +/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together +/// is a line break; every other control character, and with `lines` false every line break too, +/// shows as its Unicode Control Picture, as the Script Console shows it. +pub fn shown_text(text: &str, lines: bool) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '\r' if lines => { + chars.next_if_eq(&'\n'); + out.push('\n'); + } + '\n' if lines => out.push('\n'), + c => out.push(console::shown(c)), + } + } + out +} + +/// The longest start of `text` that is at most `max` bytes, cut at a character boundary. +pub fn cut_to(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + text.get(..end).unwrap_or_default() +} + +/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: +/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// took before dialogs existed, is an empty list. +pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { + let list = match v { + None => return Ok(Vec::new()), + Some(Value::Object(o)) if o.is_empty() => return Ok(Vec::new()), + Some(Value::Array(a)) => a, + Some(_) => return Err("`answers` must be a list of answers".into()), + }; + if list.len() > MAX_ANSWERS { + return Err(format!("`answers` has more than {MAX_ANSWERS} answers")); + } + if serde_json::to_vec(list).map_or(true, |b| b.len() > MAX_ANSWERS_BYTES) { + return Err("`answers` is larger than 1 MiB".into()); + } + list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() +} + +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; + if o.len() != 2 || !o.contains_key("value") { + return Err("must have exactly `kind` and `value`"); + } + match (o.get("kind").and_then(Value::as_str), &o["value"]) { + (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), + (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), + (Some("confirm"), Value::Bool(b)) => Ok(DialogAnswer::Confirm(*b)), + (Some("confirm"), _) => Err("is a confirm's answer, whose `value` must be true or false"), + (Some("prompt"), Value::Null) => Ok(DialogAnswer::Prompt(None)), + (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), + (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), + (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), + _ => Err("must have `kind` alert, confirm or prompt"), + } +} + +/// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits +/// for the person's answer, and the list the report gives. +pub(crate) struct Dialogs { + /// Answers come from the person, not from `answers`. + framed: bool, + /// The realm's [`Realm::wait_flag`]. + can_wait: Rc>, + answers: RefCell>, + waiting: RefCell>, + /// The error that ended the run when an answer could not reach the script. + failed: RefCell>, + records: RefCell>, + record_bytes: Cell, + count: Cell, + truncated: Cell, +} + +impl Dialogs { + pub(crate) fn new(framed: bool, realm: &Realm, answers: Vec) -> Self { + Self { + framed, + can_wait: realm.wait_flag(), + answers: RefCell::new(answers.into()), + waiting: RefCell::default(), + failed: RefCell::default(), + records: RefCell::default(), + record_bytes: Cell::new(0), + count: Cell::new(0), + truncated: Cell::new(false), + } + } + + /// The dialog that waits for its answer. + pub(crate) fn waiting(&self) -> Option { + self.waiting.borrow().clone() + } + + pub(crate) fn is_waiting(&self) -> bool { + self.waiting.borrow().is_some() + } + + /// The error that ended the run when its answer could not reach the script. + pub(crate) fn take_failure(&self) -> Option { + self.failed.borrow_mut().take() + } + + /// How many of `answers` the run did not use. + pub(crate) fn unused(&self) -> usize { + self.answers.borrow().len() + } + + /// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most + /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. + pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool { + let fits = match &answer { + DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES, + _ => true, + }; + let mut waiting = self.waiting.borrow_mut(); + let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; + self.record(d, answer.json()); + *waiting = None; + if let Err(e) = realm.answer(answer.data()) { + *self.failed.borrow_mut() = Some(e); + } + true + } + + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. + pub(crate) fn stopped(&self) { + if let Some(d) = self.waiting.borrow_mut().take() { + self.record(&d, json!("stop")); + } + } + + fn record(&self, d: &ScriptDialog, answer: Value) { + self.count.set(self.count.get().saturating_add(1)); + let mut r = Map::new(); + r.insert("kind".into(), json!(d.kind.id())); + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + match d.kind { + DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), + DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), + DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + }; + r.insert("answer".into(), answer); + let r = Value::Object(r); + let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); + let mut records = self.records.borrow_mut(); + if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { + self.truncated.set(true); + return; + } + self.record_bytes.set(self.record_bytes.get() + bytes); + records.push(r); + } + + /// Adds `dialogs`, `dialogCount` and `dialogsTruncated` to a report. + pub(crate) fn report(&self, report: &mut Map) { + report.insert("dialogs".into(), Value::Array(self.records.borrow().clone())); + report.insert("dialogCount".into(), json!(self.count.get())); + report.insert("dialogsTruncated".into(), json!(self.truncated.get())); + } +} + +/// Adds `alert`, `confirm` and `prompt` to the realm. +pub(super) fn install(realm: &mut Realm, host: &Rc) -> Result<(), RunError> { + use Arg::{Bool, Text, TextOrUndefined}; + let call = |kind: DialogKind| -> HostFunction { + let h = host.clone(); + Rc::new(move |args| open(&h, kind, &args)) + }; + realm.define_host_function("alert", vec![Text, TextOrUndefined, Bool], call(DialogKind::Alert))?; + realm.define_host_function("confirm", vec![Text, Bool, TextOrUndefined], call(DialogKind::Confirm))?; + realm.define_host_function("prompt", vec![Text, Text, TextOrUndefined], call(DialogKind::Prompt)) +} + +fn text(args: &[Data], i: usize) -> Option { + match args.get(i) { + Some(Data::String(s)) => Some(s.clone()), + _ => None, + } +} + +fn flag(args: &[Data], i: usize) -> bool { + matches!(args.get(i), Some(Data::Bool(true))) +} + +/// A call of `alert`, `confirm` or `prompt`. +fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result { + let name = kind.id(); + host.charge_call(args.iter().map(super::data_size).sum())?; + let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; + let (title, error_icon, no_as_default, preset) = match kind { + DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), + DialogKind::Prompt => { + let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; + (text(args, 2), false, false, preset) + } + }; + if message.len() > MAX_MESSAGE_BYTES { + return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); + } + if title.as_ref().is_some_and(|t| t.len() > MAX_TITLE_BYTES) { + return Err(HostError::Range(format!("{name}: the title is longer than 256 bytes"))); + } + if preset.len() > MAX_PROMPT_BYTES { + return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); + } + let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + let d = &host.dialogs; + if d.framed { + if !d.can_wait.get() { + return Err(HostError::Error(format!( + "{name}: a dialog cannot open inside a callback of a built-in function, a getter or a conversion; call it from the script's own code" + ))); + } + *d.waiting.borrow_mut() = Some(dialog); + return Err(HostError::Wait); + } + let next = d.answers.borrow_mut().pop_front(); + match next { + Some(a) if a.kind() == kind => { + d.record(&dialog, a.json()); + Ok(a.data()) + } + Some(a) => { + d.record(&dialog, json!("missing")); + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + } + None => { + d.record(&dialog, json!("missing")); + Err(HostError::Abort(format!("{name}: `answers` has no answer left for this dialog"))) + } + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 772f2c0164..2ca777096b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -27,8 +27,14 @@ //! there too. The session's console gets a start line, the run's output, its uncaught error, an end //! line and a report line; the run's report holds its own output and error, its time, its host //! calls by kind and its slowest commands. +//! +//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the +//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. pub mod console; +pub mod dialogs; + +pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -80,7 +86,7 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30; /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -135,6 +141,8 @@ pub(crate) struct Request { pub source: String, pub args: Map, pub fuel: u64, + /// The answers to the dialogs of a run with nobody to ask, in order. + pub answers: Vec, } thread_local! { @@ -468,6 +476,8 @@ struct Host { commands: RefCell>, /// The time the run's slices took, in nanoseconds. run_nanos: Cell, + /// `alert`, `confirm` and `prompt`: their answers and the list the report gives. + dialogs: dialogs::Dialogs, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -975,7 +985,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `message`, with what to do about a failure that comes from a script written for another program. fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String { - const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["app", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); let directive = @@ -1031,6 +1041,23 @@ impl Session { !self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false) } + /// The dialog (`alert`, `confirm` or `prompt`) the running script waits at for the person's + /// answer. A run asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_dialog(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten() + } + + /// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`] + /// goes on from the call. → false when nothing waits, the answer is for another kind of + /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. + pub fn script_answer(&mut self, answer: DialogAnswer) -> bool { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; + with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) + } + /// The name of the running script. pub fn script_name(&self) -> Option { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone())) @@ -1132,6 +1159,7 @@ impl Session { counts: Counts::default(), commands: RefCell::default(), run_nanos: Cell::new(0), + dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers), }); let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; @@ -1140,6 +1168,7 @@ impl Session { let started = realm .define_host_object("vc", vc_object(&host, args)) .and_then(|()| realm.define_host_object("$", dollar_object(&host))) + .and_then(|()| dialogs::install(&mut realm, &host)) .and_then(|()| realm.start(&request.source)); if let Err(e) = started { let mut report = failure_report(&request.name, &e, &request.source, &host, 0, 0); @@ -1163,11 +1192,20 @@ impl Session { let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else { return Some(Err(EngineError::Other(JOB_GONE.to_string()))); }; - if job.host.waiting.get() && !self.script_stop.is_set() { + if let Some(e) = job.host.dialogs.take_failure() { + return Some(self.script_failed(job, &e)); + } + if (job.host.waiting.get() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job)); self.script_key = Some(key); return None; } + // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. + if job.realm.waits() { + let kind = LimitKind::Interrupted; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + return Some(self.script_failed(job, &e)); + } if vectorcraft_doc::cancel::check().is_err() { self.script_stop.set(); } @@ -1184,6 +1222,12 @@ impl Session { self.script_key = Some(key); None } + Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { + let n = job.host.dialogs.unused(); + let kind = LimitKind::Host; + let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" }); + Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) + } Ok(Ok(Progress::Done(_))) => { let r = self.script_commit(job); self.trim_histories(); @@ -1193,6 +1237,7 @@ impl Session { } fn script_failed(&mut self, job: Job, e: &RunError) -> Result { + job.host.dialogs.stopped(); let fuel_left = job.realm.fuel_left(); let mut report = failure_report(&job.name, e, "", &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); @@ -1288,7 +1333,7 @@ impl Session { if let Some(result) = self.script_pump() { return result; } - if self.script_waiting() { + if self.script_waiting() || self.script_dialog().is_some() { self.script_stop.set(); } } @@ -1347,8 +1392,8 @@ fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) { /// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run /// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report -/// line in the session's console. Adds the run's time, host calls by kind, slowest commands and -/// console to `report`. +/// line in the session's console. Adds the run's time, host calls by kind, slowest commands, +/// console and dialogs to `report`. fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::Ending) { let mut pending = std::mem::take(&mut *host.pending.borrow_mut()); if !pending.is_empty() { @@ -1379,6 +1424,7 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: o.insert("hostCallCounts".into(), host.counts.json()); o.insert("slowestCommands".into(), Value::Array(slow_json)); o.insert("console".into(), host.console.borrow().report()); + host.dialogs.report(o); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7f0d450c7a..f1f77160c9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -151,6 +151,7 @@ mod save; mod saveoptions; mod scalestrokes; mod script_console; +mod script_dialogs; mod script_run; mod scripts; mod select_ids_first; diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs new file mode 100644 index 0000000000..7572ca52f0 --- /dev/null +++ b/crates/engine/src/tests/script_dialogs.rs @@ -0,0 +1,289 @@ +//! `alert`, `confirm` and `prompt` in a script: their arguments and results, the answers a run with +//! nobody to ask takes from `answers`, the wait in the app, Stop, and the report's `dialogs`. + +use serde_json::{Value, json}; + +use crate::script::{DialogAnswer, DialogKind, ScriptDialog, dialogs}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn answers(list: &[Value]) -> Value { + Value::Array(list.to_vec()) +} + +#[test] +fn notification_signatures_and_returns() { + let mut s = one_doc(); + let source = "vc.log(typeof alert('a')); alert(42, 'Title', 1);\ + vc.log(confirm('c')); vc.log(confirm('n', true, undefined));\ + vc.log(prompt('p', 'pre')); vc.log(prompt({toString: function () { return 'own'; }}, '', 'T'));"; + let r = headless( + &mut s, + source, + answers(&[ + json!({"kind": "alert", "value": "ok"}), + json!({"kind": "alert", "value": "ok"}), + json!({"kind": "confirm", "value": true}), + json!({"kind": "confirm", "value": false}), + json!({"kind": "prompt", "value": "typed"}), + json!({"kind": "prompt", "value": null}), + ]), + ) + .unwrap(); + assert_eq!(r["log"], json!(["undefined", true, false, "typed", null]), "{r}"); + assert_eq!( + r["dialogs"], + json!([ + {"kind": "alert", "message": "a", "title": "Script Alert", "errorIcon": false, "answer": "ok"}, + {"kind": "alert", "message": "42", "title": "Title", "errorIcon": true, "answer": "ok"}, + {"kind": "confirm", "message": "c", "title": "Script Alert", "noAsDefault": false, "answer": true}, + {"kind": "confirm", "message": "n", "title": "Script Alert", "noAsDefault": true, "answer": false}, + {"kind": "prompt", "message": "p", "title": "Script Alert", "preset": "pre", "answer": "typed"}, + {"kind": "prompt", "message": "own", "title": "T", "preset": "", "answer": null}, + ]) + ); + assert_eq!((r["dialogCount"].clone(), r["dialogsTruncated"].clone()), (json!(6), json!(false))); + let has = headless(&mut s, "vc.log(vc.api.has('dialogs'));", json!([])).unwrap(); + assert_eq!(has["log"], json!([true])); +} + +#[test] +fn headless_answers_follow_call_order() { + let mut s = one_doc(); + let source = "var out = []; [1, 2].forEach(function (i) { out.push(confirm('q' + i)); }); out.push(prompt('r', 'x')); vc.log(out.join());"; + let r = headless( + &mut s, + source, + answers(&[json!({"kind": "confirm", "value": false}), json!({"kind": "confirm", "value": true}), json!({"kind": "prompt", "value": "z"})]), + ) + .unwrap(); + assert_eq!(r["log"], json!(["false,true,z"]), "a callback of a built-in takes its answer too: {r}"); + assert_eq!(headless(&mut s, "1", json!({})).unwrap()["dialogCount"], 0, "an empty object is an empty list"); +} + +#[test] +fn missing_or_mismatched_answer_rolls_back() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (source, given, says) in [ + (format!("{edit} try {{ alert('x'); }} catch (e) {{ vc.log('caught'); }}"), json!([]), "no answer left"), + (format!("{edit} alert('x');"), answers(&[json!({"kind": "confirm", "value": true})]), "is for confirm, not alert"), + (format!("{edit} alert('x');"), answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})]), "1 answer"), + ] { + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains(says), "{e}"); + assert_eq!(art(&s), before, "{source}"); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "limit", "{report}"); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogCount"], 1); + } + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "ok"); + headless(&mut s, "alert('x')", json!([])).unwrap_err(); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing"); +} + +#[test] +fn invalid_answers_are_rejected_before_run() { + let mut s = one_doc(); + let before = art(&s); + let many: Vec = (0..=dialogs::MAX_ANSWERS).map(|_| json!({"kind": "alert", "value": "ok"})).collect(); + let big: Vec = (0..80).map(|_| json!({"kind": "prompt", "value": "x".repeat(16_000)})).collect(); + for given in [ + json!({"a": 1}), + json!("ok"), + json!([1]), + json!([{"kind": "alert"}]), + json!([{"kind": "alert", "value": true}]), + json!([{"kind": "confirm", "value": "yes"}]), + json!([{"kind": "prompt", "value": 3}]), + json!([{"kind": "prompt", "value": "x".repeat(dialogs::MAX_PROMPT_BYTES + 1)}]), + json!([{"kind": "other", "value": "ok"}]), + json!([{"kind": "alert", "value": "ok", "extra": 1}]), + Value::Array(many), + Value::Array(big), + ] { + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + let r = s.execute("script.run", &json!({"source": source, "answers": given})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); + assert_eq!(art(&s), before); + } + s.script_frames = true; + let r = s.execute("script.run", &json!({"source": "1", "answers": [{"kind": "alert", "value": "ok"}]})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "a run in the app takes no answers: {r:?}"); + assert!(!s.script_running()); +} + +#[test] +fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { + let mut s = one_doc(); + framed( + &mut s, + "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); var a = confirm('Go?', true, 'Ask'); var b = prompt('Name', 'n'); vc.log([a, b]);", + ); + let want = ScriptDialog { + kind: DialogKind::Confirm, + message: "Go?".into(), + title: Some("Ask".into()), + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + assert_eq!(s.script_dialog(), Some(want)); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert!(!s.script_answer(DialogAnswer::Confirm(true)), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().preset, "n"); + assert!(!s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES + 1))))); + assert!(s.script_answer(DialogAnswer::Prompt(Some("Ann".into())))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, "Ann"]])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); + assert_eq!(r["dialogs"][1]["answer"], "Ann"); +} + +#[test] +fn prompt_cancel_returns_null() { + let mut s = one_doc(); + framed(&mut s, "vc.log(prompt('Name', '') === null);"); + assert!(s.script_answer(DialogAnswer::Prompt(None))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true])); +} + +#[test] +fn dialog_loop_stops_or_exhausts() { + let mut s = one_doc(); + let before = art(&s); + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); while (1) { alert('x'); }"; + let three: Vec = (0..3).map(|_| json!({"kind": "alert", "value": "ok"})).collect(); + let e = headless(&mut s, source, Value::Array(three)).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(s.script_report().unwrap()["dialogCount"], 4); + assert_eq!(art(&s), before); + framed(&mut s, source); + for _ in 0..3 { + assert!(s.script_answer(DialogAnswer::Ok)); + assert!(pump(&mut s).is_none()); + } + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_dialog(), None, "a run asked to stop no longer waits"); + assert!(!s.script_answer(DialogAnswer::Ok)); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), report["dialogCount"].as_u64()), (Some("stopped"), Some(4)), "{report}"); + assert_eq!(report["dialogs"][3]["answer"], "stop"); + assert_eq!(art(&s), before, "Stop at the first or any later dialog leaves no undo step"); + framed(&mut s, source); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); +} + +#[test] +fn dialog_text_limits_and_controls() { + let mut s = one_doc(); + let source = format!( + "var out = [];\ + function t(f) {{ try {{ f(); out.push('opened'); }} catch (e) {{ out.push(e.name); }} }}\ + t(function () {{ alert('x'); }});\ + t(function () {{ alert(new Array({m}).join('m')); }});\ + t(function () {{ alert('m', new Array({t}).join('t')); }});\ + t(function () {{ prompt('m', new Array({m}).join('p')); }});\ + t(function () {{ alert(); }});\ + t(function () {{ prompt('m'); }});\ + t(function () {{ alert({{toString: function () {{ throw new Error('no'); }}}}); }});\ + t(function () {{ alert(undefined); }});\ + vc.log(out.join());", + m = dialogs::MAX_MESSAGE_BYTES + 2, + t = dialogs::MAX_TITLE_BYTES + 2, + ); + let r = headless(&mut s, &source, answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})])).unwrap(); + assert_eq!(r["log"], json!(["opened,RangeError,RangeError,RangeError,TypeError,TypeError,Error,opened"]), "{r}"); + assert_eq!(r["dialogs"][1]["message"], "undefined", "an explicit undefined message is a message"); + assert_eq!(dialogs::shown_text("a\r\nb\rc\nd\te\u{7}\u{7f}", true), "a\nb\nc\nd\u{2409}e\u{2407}\u{2421}"); + assert_eq!(dialogs::shown_text("a\nb", false), "a\u{240a}b", "a title stays on one line"); + assert_eq!(dialogs::cut_to("aé", 2), "a", "a cut keeps whole characters"); +} + +#[test] +fn dialog_transcript_on_success_and_failure() { + let mut s = one_doc(); + let r = headless(&mut s, "alert('one'); throw new Error('later');", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap_err(); + assert!(r.to_string().contains("later")); + let report = s.script_report().unwrap(); + assert_eq!(report["dialogs"], json!([{"kind": "alert", "message": "one", "title": "Script Alert", "errorIcon": false, "answer": "ok"}])); + let ok = headless(&mut s, "1", json!([])).unwrap(); + assert_eq!((ok["dialogs"].clone(), ok["dialogCount"].clone()), (json!([]), json!(0))); +} + +#[test] +fn dialog_wait_does_not_spend_fuel() { + let mut s = one_doc(); + framed(&mut s, "alert('x'); 1"); + for _ in 0..20 { + assert!(s.script_pump().is_none(), "the run waits"); + } + assert!(s.script_answer(DialogAnswer::Ok)); + let r = pump(&mut s).unwrap().unwrap(); + let mut t = one_doc(); + let plain = headless(&mut t, "alert('x'); 1", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap(); + assert_eq!((r["fuelUsed"].clone(), r["hostCalls"].clone()), (plain["fuelUsed"].clone(), plain["hostCalls"].clone()), "{r}"); +} + +#[test] +fn second_run_is_busy_while_dialog_waits() { + let mut s = one_doc(); + framed(&mut s, "alert('x');"); + assert!(s.execute("script.run", &json!({"source": "1"})).is_err()); + assert!(s.script_dialog().is_some(), "the first run still waits"); + assert!(s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 1, "height": 1})).is_err(), "edits are refused while it waits"); +} + +#[test] +fn a_dialog_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var m = ''; [1].forEach(function () { try { alert('x'); } catch (e) { m = e.message; } }); vc.log(m);"; + s.execute("script.run", &json!({"source": source})).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); + assert_eq!(r["dialogCount"], 0); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 1399c05701..b5ed7419b6 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -175,14 +175,13 @@ pub(crate) enum NativeKind { /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. -/// `Data` is a host function given [`crate::Data`]; with `text`, each argument arrives as the -/// string `String(value)` gives. +/// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, - Data { f: DataFn, name: Rc, text: bool }, + Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 888fb3d95b..475b4f6f29 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -57,11 +57,38 @@ pub enum HostError { Range(String), /// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it. Abort(String), + /// Pauses the run at this call: [`crate::Realm::advance`] returns [`crate::Progress::Paused`], + /// and the call's result is the value [`crate::Realm::answer`] gives it. A function may return + /// it only while [`crate::Realm::wait_flag`] is set; otherwise the run ends with an internal + /// error. + Wait, } /// A function the host gives a script, with its arguments converted. pub type HostFunction = Rc) -> Result>; +/// How one argument of a [`HostItem::Converted`] function is read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Arg { + /// The string `String(value)` gives. + Text, + /// `undefined` as [`Data::Undefined`], any other value as the string `String(value)` gives. + TextOrUndefined, + /// The boolean `Boolean(value)` gives. + Bool, +} + +/// How the arguments of a host function are read. +#[derive(Clone)] +pub(crate) enum ArgRead { + /// Each as [`Data`]. + Data, + /// Each as the string `String(value)` gives. + Text, + /// One by one as the list says; those past its end are not read. + Each(Rc<[Arg]>), +} + /// A member of an object the host adds to the global environment. #[derive(Clone)] pub enum HostItem { @@ -70,6 +97,9 @@ pub enum HostItem { Function(HostFunction), /// A function whose arguments arrive as strings, each the string `String(value)` gives. TextFunction(HostFunction), + /// A function whose arguments arrive converted one by one as the list says. Arguments past the + /// end of the list are not read and do not reach the function. + Converted(Vec, HostFunction), /// A property whose value the function gives each time it is read. Getter(HostFunction), /// A frozen object with these members. @@ -277,20 +307,32 @@ impl Interp { Ok(Value::Object(id)) } - /// Calls host function `f`: reads its arguments (with `text`, each as the string `String(value)` - /// gives), runs it, and gives its result to the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], text: bool) -> JsResult { + /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to + /// the script. + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let args = match how { + ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), + _ => args, + }; let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if text { + if !matches!(how, ArgRead::Data) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); - let d = if text { self.read_text(a, &mut reading) } else { self.read_data(a, &mut reading) }; + let d = match how { + ArgRead::Data => self.read_data(a, &mut reading), + ArgRead::Text => self.read_text(a, &mut reading), + ArgRead::Each(list) => match list.get(i) { + Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), + Some(Arg::Bool) => Ok(Data::Bool(a.truthy())), + _ => self.read_text(a, &mut reading), + }, + }; match d { Ok(d) => data.push(d), Err(e) => { @@ -302,8 +344,19 @@ impl Interp { } self.temp_roots.truncate(mark); read?; - match f(data) { + // Only the script's own code, in a run that can pause, can wait for a result. + let can_wait = self.in_slice && self.reentry == 0; + self.can_wait.set(can_wait); + let result = f(data); + self.can_wait.set(false); + match result { Ok(d) => self.write_data(d, 0, false), + Err(HostError::Wait) if can_wait => { + self.waiting = true; + self.pause.set(true); + Ok(Value::Undefined) + } + Err(HostError::Wait) => Err(Abrupt::Internal(format!("{name} waited for its result where the run cannot pause"))), Err(HostError::Abort(message)) => { self.host_abort = Some(message); Err(Abrupt::Limit(LimitKind::Host)) @@ -357,17 +410,28 @@ impl Interp { let full = format!("{path}.{name}"); let prop = match item { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, - HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, false)), flags: ENUMERABLE }, - HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE }, - HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE }, + HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, + HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE }, + HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE }, + HostItem::Converted(list, f) => { + Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } + } }; self.define(o, key(&name), prop) } - fn host_function(&mut self, f: HostFunction, name: &str, text: bool) -> ObjId { + /// Adds the global function `name` with its arguments converted as `args` says. A script may + /// replace or delete it, as it may a built-in function. + pub(crate) fn install_host_function(&mut self, name: &str, args: Vec, f: HostFunction) -> JsResult<()> { + let o = self.host_function(f, name, ArgRead::Each(args.into())); + let global = self.global; + self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: crate::heap::HIDDEN }) + } + + fn host_function(&mut self, f: HostFunction, name: &str, read: ArgRead) -> ObjId { let proto = self.intrinsics.function_proto; - self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), text }), Some(proto))) + self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read }), Some(proto))) } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 93875f6d1f..3492cf653f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -277,6 +277,84 @@ fn advancing_without_a_run_is_an_error() { assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "no run to advance")); } +/// A realm with the global `ask(question)`, which waits for its answer where it can and throws an +/// `Error` where it cannot. → how many times it was called. +fn with_ask(r: &mut Realm) -> Rc> { + let calls: Rc> = Rc::default(); + let (count, can_wait) = (calls.clone(), r.wait_flag()); + let f: HostFunction = Rc::new(move |_| { + count.set(count.get() + 1); + if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) } + }); + r.define_host_function("ask", vec![Arg::Text], f).unwrap(); + calls +} + +#[test] +fn a_waiting_call_pauses_at_the_call_and_takes_its_answer_once() { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var a = ask('first'); var b = ask('second'); a + '|' + b").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + let fuel = r.fuel_left(); + let e = r.advance(1_000).unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "the run waits for a host function's result")); + assert_eq!(r.fuel_left(), fuel, "no fuel is spent while the call waits"); + r.answer(Data::String("one".into())).unwrap(); + assert!(!r.waits()); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(Data::Null).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("one|null".into())); + assert_eq!(calls.get(), 2, "each call ran once"); + let e = r.answer(Data::Null).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Internal); +} + +#[test] +fn only_the_scripts_own_code_in_a_resumable_run_can_wait() { + let mut r = realm(1_000_000); + with_ask(&mut r); + let caught = "var out = []; [1].forEach(function () { try { ask('x'); } catch (e) { out.push(e.message); } }); \ + var o = {}; Object.defineProperty(o, 'g', {get: function () { try { ask('y'); } catch (e) { out.push(e.message); } }}); o.g; \ + try { String({toString: function () { return ask('z'); }}); } catch (e) { out.push(e.message); } out.join()"; + r.start(caught).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("cannot wait here,cannot wait here,cannot wait here".into())); + let e = r.run("ask('q')").unwrap_err(); + assert!(e.message.contains("cannot wait here"), "a run that cannot pause cannot wait: {}", e.message); + r.start("var f = ask; ask.call(null, 'q'); f.apply(null, ['r'])").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits(), "call and apply from the script's own code wait"); +} + +#[test] +fn a_host_function_that_waits_where_it_cannot_ends_the_run() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Err(HostError::Wait)); + r.define_host_function("ask", vec![], f).unwrap(); + let e = r.run("try { ask(); } catch (e) { 'caught' }").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Internal); +} + +#[test] +fn a_converted_function_reads_each_argument_as_its_list_says() { + let mut r = realm(1_000_000); + let seen: Rc>>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().push(args); + Ok(Data::Undefined) + }); + r.define_host_function("conv", vec![Arg::Text, Arg::TextOrUndefined, Arg::Bool], f).unwrap(); + r.run("conv(42, undefined, 'x', function () {}); conv(undefined, null, 0); conv({toString: function () { return 'own'; }}); conv()").unwrap(); + let s = |t: &str| Data::String(t.into()); + let want = vec![vec![s("42"), Data::Undefined, Data::Bool(true)], vec![s("undefined"), s("null"), Data::Bool(false)], vec![s("own")], vec![]]; + assert_eq!(*seen.borrow(), want, "arguments past the list are not read"); + let out = r.run("var a = typeof conv; conv = 1; a + ' ' + conv").unwrap(); + assert_eq!(out, JsValue::String("function 1".into()), "a script may replace the function"); +} + proptest::proptest! { /// A slice size does not change what a script computes. #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ee711ffb3a..4fd4a038ae 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -181,6 +181,12 @@ pub(crate) struct Interp { pub(crate) held: Rc, /// Set by the host to end the current slice of a resumable run at the next safe point. pub(crate) pause: Rc>, + /// The outermost loop of a resumable run is running ([`crate::Realm::advance`]). + pub(crate) in_slice: bool, + /// True while a host function runs where it may wait ([`crate::HostError::Wait`]). + pub(crate) can_wait: Rc>, + /// A host function's call waits for its result: the value on top of the stack stands in for it. + pub(crate) waiting: bool, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -374,6 +380,9 @@ impl Interp { date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), pause: Rc::default(), + in_slice: false, + can_wait: Rc::default(), + waiting: false, host_abort: None, data_limits: crate::DataLimits::default(), }; @@ -414,7 +423,7 @@ impl Interp { // ---- the operand stack ---- - fn push(&mut self, v: Value) -> JsResult<()> { + pub(crate) fn push(&mut self, v: Value) -> JsResult<()> { self.stack.push(v); Ok(()) } @@ -1846,10 +1855,10 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } - Func::Data { f, name, text } => { + Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a95a4b8847..a92de47b34 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -66,7 +66,7 @@ pub use ast::{ PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, }; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use host::{Data, DataLimits, HostError, HostFunction, HostItem}; +pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind}; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a28b150a52..9e2e95b4a9 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -218,6 +218,7 @@ impl Realm { interp.throw_site = None; interp.last_thrown = Value::Undefined; interp.host_abort = None; + interp.waiting = false; let strict = interp.options.strict; match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { Ok(code) => Ok(code), @@ -234,6 +235,7 @@ impl Realm { interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); + interp.waiting = false; match result { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { @@ -263,16 +265,22 @@ impl Realm { /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned - /// [`Progress::Done`] or an error, the run is over. + /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its + /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; if interp.frames.is_empty() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); } + if interp.waiting { + return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 }); + } let total = interp.fuel; let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; + interp.in_slice = true; let r = interp.execute_slice(cap - slice.min(cap)); + interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; match r { @@ -294,6 +302,38 @@ impl Realm { self.interp.pause.clone() } + /// The flag that is set while a host function runs where it may return + /// [`crate::HostError::Wait`]: called by the script's own code in a run [`Realm::advance`] + /// carries on, and not from a getter, a conversion or a built-in's callback. + pub fn wait_flag(&self) -> std::rc::Rc> { + self.interp.can_wait.clone() + } + + /// Does a host function's call wait for the result [`Realm::answer`] gives it? + pub fn waits(&self) -> bool { + self.interp.waiting + } + + /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next + /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// limit, and with no call waiting this gives an internal error. + pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { + let interp = &mut self.interp; + if !interp.waiting { + return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 }); + } + interp.waiting = false; + // The value on top of the stack stood in for the result. + let r = interp.write_data(d, 0, false).and_then(|v| { + interp.stack.pop(); + interp.push(v) + }); + match r { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Has this realm stop when `interrupt` is set, in place of its own flag. pub fn share_interrupt(&mut self, interrupt: &Interrupt) { self.interp.interrupt = interrupt.0.clone(); @@ -319,6 +359,16 @@ impl Realm { } } + /// Defines the global function `name`, whose arguments arrive converted as `args` says + /// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as + /// it may a built-in function. + pub fn define_host_function(&mut self, name: &str, args: Vec, f: crate::HostFunction) -> Result<(), RunError> { + match self.interp.install_host_function(name, args, f) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Defines the global variable `name` holding the exception the last run did not catch /// (`undefined` if there was none). pub fn bind_last_thrown(&mut self, name: &str) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 80614f9091..a0fc524055 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -341,7 +341,7 @@ impl VectorcraftApp { screen_color::poll(self, ctx); self.poll_finished_work(); crate::script_runs::poll(self); - if self.session.script_running() && !self.session.script_waiting() { + if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { ctx.request_repaint(); } #[cfg(not(target_arch = "wasm32"))] @@ -370,9 +370,7 @@ impl VectorcraftApp { unsaved::finish_pending(self); if self.session.script_running() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - if self.ui.dialog.is_none() { - self.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, serde_json::json!({}))); - } + dialogs::script_run::ask_to_close(self); } else if self.file_sheet_open() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.status(picks::busy()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index edea838ecc..c13a230a94 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -410,6 +410,7 @@ registry! { ScriptRun: [script_run::KIND] => script_run::SPEC, ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, + ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -588,6 +589,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::GROWTH_KIND { app.session.script_request_stop(); } + if d.kind == script_run::NOTICE_KIND { + script_run::notice_cancel(app, &d); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 2ef43cb8fe..eb89bd174d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -1,16 +1,25 @@ //! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs -//! (`script.run` runs it), the question a run that keeps adding art asks, and the question quitting -//! asks while a script runs. +//! (`script.run` runs it), the question a run that keeps adding art asks, the question quitting +//! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: //! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). +//! +//! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt), +//! `message`, `title` (null: Script Alert), `errorIcon`, `noAsDefault` and `value` (the prompt's +//! text), and takes `answer`: `ok` (alert, prompt), `yes` or `no` (confirm), `cancel` (prompt) or +//! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. +//! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. +//! Stop ends the run and puts back everything it did. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; +use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; -use super::DialogSpec; +use super::{DialogAction, DialogSpec}; use crate::state::Dialog; use crate::theme::{self, Tokens}; use crate::{FilePick, VectorcraftApp, widgets}; @@ -21,6 +30,19 @@ pub const KIND: &str = "scriptRun"; pub const GROWTH_KIND: &str = "scriptGrowth"; /// The dialog kind of the question quitting asks while a script runs. pub const CLOSE_KIND: &str = "scriptClose"; +/// The dialog kind of a script's `alert`, `confirm` and `prompt`. +pub const NOTICE_KIND: &str = "scriptDialog"; + +pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { + heading: notice_heading, + body_with_actions: Some(notice_body), + confirm: notice_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 360.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Run Script").into(), @@ -145,3 +167,154 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result } Ok(Value::Null) } + +/// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which +/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + if app.ui.dialog.is_some() { + return; + } + let mut fields = json!({}); + if let Some(notice) = notice { + fields[super::PARENT] = serde_json::to_value(notice).unwrap_or_default(); + } + app.ui.dialog = Some(Dialog::new(CLOSE_KIND, fields)); +} + +/// Shows the dialog the running script waits at. +pub(crate) fn open_notice(app: &mut VectorcraftApp, d: &ScriptDialog) { + let fields = json!({ + "kind": d.kind.id(), + "message": d.message, + "title": d.title, + "errorIcon": d.error_icon, + "noAsDefault": d.no_as_default, + "value": d.preset, + }); + app.ui.dialog = Some(Dialog::new(NOTICE_KIND, fields)); +} + +/// The dialog's heading: the script's title on one line, or Script Alert. +pub(crate) fn notice_heading(d: &Dialog) -> String { + match d.fields.get("title").and_then(Value::as_str) { + Some(title) => shown_text(title, false), + None => tl!("Script Alert").into(), + } +} + +/// The answer of the default button: OK, or for a confirm Yes, or No with `noAsDefault`. +fn default_answer(d: &Dialog) -> &'static str { + match (d.str("kind").as_str(), d.bool("noAsDefault")) { + ("confirm", true) => "no", + ("confirm", false) => "yes", + _ => "ok", + } +} + +/// A button that is the primary one when it is the default. +fn answer_button(ui: &mut egui::Ui, label: &str, default: bool) -> bool { + if default { widgets::primary_button_enabled(ui, label, true).clicked() } else { widgets::secondary_button(ui, label).clicked() } +} + +fn notice_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let kind = d.str("kind"); + let message = shown_text(&d.str("message"), true); + ui.horizontal_top(|ui| { + if d.bool("errorIcon") { + ui.label(egui::RichText::new("!").font(theme::semibold(22.0)).color(t.error)); + ui.add_space(8.0); + } + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| ui.label(&message)); + }); + if kind == "prompt" { + ui.add_space(8.0); + let name = cut_to(&shown_text(&message, false), 200).to_string(); + super::form::text_edit_named(ui, d, "value", &name, ui.available_width()); + let value = d.str("value"); + if value.len() > MAX_PROMPT_BYTES { + d.fields.insert("value".into(), json!(cut_to(&value, MAX_PROMPT_BYTES))); + } + } + ui.add_space(16.0); + let default = default_answer(d); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + let buttons: &[(&str, &str)] = match kind.as_str() { + "confirm" => &[("yes", "Yes"), ("no", "No")], + "prompt" => &[("ok", "OK"), ("cancel", "Cancel")], + _ => &[("ok", "OK")], + }; + for (id, label) in buttons { + if answer_button(ui, tl!(label), *id == default) { + answer = Some(*id); + } + ui.add_space(8.0); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + if answer.is_none() && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some(default); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// Gives the running script the dialog's `answer`, or the default button's. +fn notice_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or(default_answer(d)); + give(app, d, answer) +} + +/// Escape or Cancel: Cancel for a prompt, No for a confirm and Stop for an alert. +pub(super) fn notice_cancel(app: &mut VectorcraftApp, d: &Dialog) { + let answer = match d.str("kind").as_str() { + "prompt" => "cancel", + "confirm" => "no", + _ => "stop", + }; + let _ = give(app, d, answer); +} + +fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result { + let given = match (d.str("kind").as_str(), answer) { + (_, "stop") => None, + ("alert", "ok") => Some(DialogAnswer::Ok), + ("confirm", "yes") => Some(DialogAnswer::Confirm(true)), + ("confirm", "no") => Some(DialogAnswer::Confirm(false)), + ("prompt", "ok") => Some(DialogAnswer::Prompt(Some(d.str("value")))), + ("prompt", "cancel") => Some(DialogAnswer::Prompt(None)), + (kind, _) => return Err(format!("`answer` for this {kind} dialog must be one of: {}", answers_for(kind))), + }; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + // Refused while the dialog still waits: the text is too long, and the dialog stays open. + if !app.session.script_answer(a) && app.session.script_dialog().is_some() { + return Err(format!("the prompt's text is longer than {MAX_PROMPT_BYTES} bytes")); + } + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == NOTICE_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + +fn answers_for(kind: &str) -> &'static str { + match kind { + "confirm" => "yes, no, stop", + "prompt" => "ok, cancel, stop", + _ => "ok, stop", + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ee32cee33f..44399fad1e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3976,6 +3976,7 @@ axis Both И двете Stop Script Спри скрипта Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт + Script Alert Известие от скрипт A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0970a70929..6ffc452976 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4341,6 +4341,7 @@ imageTrace Outline Obris Stop Script Zaustavi skriptu Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava + Script Alert Upozorenje skripte A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 84b6833c4e..849c82a78d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5188,6 +5188,7 @@ digits Malayalam Malaiàlam Stop Script Atura l'script Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script + Script Alert Avís de l'script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 733a3e813b..d4d311216c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4399,6 +4399,7 @@ imageTrace Outline Obrys Stop Script Zastavit skript Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript + Script Alert Upozornění skriptu A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d1871b2ed9..2da5515c5a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4095,6 +4095,7 @@ imageTrace Outline Kontur Stop Script Stop script Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører + Script Alert Scriptadvarsel A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8c75b25b6b..ce56630317 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4005,6 +4005,7 @@ theme Appearance Erscheinungsbild Stop Script Skript stoppen Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt + Script Alert Skriptmeldung A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7813ee6cf8..008671206e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2245,6 +2245,7 @@ axis Both Και τα δύο Stop Script Διακοπή σεναρίου Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο + Script Alert Ειδοποίηση σεναρίου A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d8bcecbc6e..3853617ca8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4089,6 +4089,7 @@ axis Both Ambos Stop Script Detener script Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script + Script Alert Aviso del script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d3b9fb3260..2c821f843f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4313,6 +4313,7 @@ imageTrace Outline Ääriviiva Stop Script Pysäytä komentosarja Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä + Script Alert Komentosarjan ilmoitus A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6db5062046..59e8642e38 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4078,6 +4078,7 @@ axis Both Les deux Stop Script Arrêter le script Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution + Script Alert Alerte de script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3fa2269085..92c7d6ad16 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6178,6 +6178,7 @@ antiAlias Sharp शार्प Stop Script स्क्रिप्ट रोकें Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है + Script Alert स्क्रिप्ट सूचना A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27e22d0ad0..9bb1ae49ec 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4886,6 +4886,7 @@ imageTrace Outline Körvonal Stop Script Parancsfájl leállítása Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut + Script Alert Parancsfájl-értesítés A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c4e97482a8..7225ff3e99 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4095,6 +4095,7 @@ imageTrace Outline Kontur Stop Script Hentikan Skrip Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan + Script Alert Peringatan Skrip A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 987505a43c..a697c54224 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4132,6 +4132,7 @@ axis Both Entrambi Stop Script Interrompi script Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script + Script Alert Avviso dello script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d3c0b6603d..1ccd7b55ae 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4862,6 +4862,7 @@ swatch Bright Violet ビビッドバイオレット Stop Script スクリプトを停止 Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 + Script Alert スクリプトの通知 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5a05ccec34..cf0ce6f35b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5177,6 +5177,7 @@ imageTrace Outline კონტური Stop Script სკრიპტის შეჩერება Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს + Script Alert სკრიპტის შეტყობინება A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b0fc26d1fe..51dd2528d9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4789,6 +4789,7 @@ theme Appearance 외관 Stop Script 스크립트 중지 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 + Script Alert 스크립트 알림 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c30a50e71d..d604b6165d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4109,6 +4109,7 @@ imageTrace Outline Contour Stop Script Script stoppen Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd + Script Alert Scriptmelding A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8450cb6540..5980dfccfa 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4222,6 +4222,7 @@ imageTrace Outline Kontur Stop Script Zatrzymaj skrypt Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony + Script Alert Komunikat skryptu A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00d9a89484..ce0dfcfec4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5066,6 +5066,7 @@ axis Both Ambos Stop Script Parar script Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução + Script Alert Alerta do script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 24a6c74d5b..3963b9e519 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4126,6 +4126,7 @@ axis Both Оба Stop Script Остановить скрипт Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт + Script Alert Сообщение скрипта A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c038612c18..e5603a14c4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3999,6 +3999,7 @@ axis Both Båda Stop Script Stoppa skript Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs + Script Alert Skriptmeddelande A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 282990771a..57517c4a3d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3881,6 +3881,7 @@ axis Both Her İkisi Stop Script Betiği Durdur Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor + Script Alert Betik Uyarısı A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 88bcb4702a..ccaba51b6d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4116,6 +4116,7 @@ axis Both Обидві Stop Script Зупинити скрипт Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт + Script Alert Повідомлення скрипту A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 90c292bc92..7f00d9db51 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4535,6 +4535,7 @@ theme Appearance Giao diện Stop Script Dừng tập lệnh Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài A Script Is Running Một tập lệnh đang chạy + Script Alert Thông báo của tập lệnh A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 77578eec12..7467c61267 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4569,6 +4569,7 @@ imageTrace Outline 轮廓 Stop Script 停止脚本 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 + Script Alert 脚本提示 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bdec63590f..650984daa3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2397,6 +2397,7 @@ file-filter Templates 範本 Stop Script 停止指令碼 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 + Script Alert 指令碼提示 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 042e24cd31..65a9dc9eb6 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,6 +1,7 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar -//! shows it with a Stop button; a run that has added a great deal waits for the person's answer. +//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with +//! `alert`, `confirm` or `prompt`, waits for the person's answer. use serde_json::json; @@ -14,15 +15,16 @@ pub fn poll(app: &mut VectorcraftApp) { if !app.session.script_running() { return; } - if app.session.script_waiting() { - if app.ui.dialog.is_none() { - app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); - } + if ask(app) { return; } let name = app.session.script_name().unwrap_or_default(); let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); - let Some(result) = app.session.script_pump() else { return }; + let Some(result) = app.session.script_pump() else { + // The app draws no more frames while the run waits: its question opens in this one. + ask(app); + return; + }; if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { app.canvas.hover_cursor = None; } @@ -36,6 +38,29 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the +/// question about its growth. Closes the script's dialog when the run no longer waits at it. +/// → true while the run waits. +fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(dialog) = app.session.script_dialog() { + if app.ui.dialog.is_none() { + script_run::open_notice(app, &dialog); + } + return true; + } + // A run asked to stop no longer waits at its dialog. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { + app.ui.dialog = None; + } + if app.session.script_waiting() { + if app.ui.dialog.is_none() { + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); + } + return true; + } + false +} + /// Shows why a run ended without its changes. A stopped run that wrote no file says only that it /// was stopped; any other failure shows its error, which names the files left written. pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 261a250542..bc4251ea6a 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -39,6 +39,7 @@ mod saveext; mod screenmode; mod screenshots; mod script_check; +mod script_dialogs; mod script_run; mod scrub; mod selectall; diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs new file mode 100644 index 0000000000..da09c777ba --- /dev/null +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -0,0 +1,256 @@ +//! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, +//! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers +//! given by a run with nobody to ask. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::dialogs::script_run::{CLOSE_KIND, NOTICE_KIND}; +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "d.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its dialog is open (true). +fn until_dialog(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == NOTICE_KIND) { + return true; + } + } + panic!("the script neither ended nor opened a dialog"); +} + +fn answer(app: &mut VectorcraftApp, answer: &str) { + app.ui.dialog.as_mut().unwrap().fields.insert("answer".into(), json!(answer)); + dialogs::confirm(app).unwrap(); +} + +thread_local! { + // One context per test, so frames follow one another as in the app. + static CTX: egui::Context = { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; +} + +/// One headless frame of the dialog layer and the shortcuts, in a window of `size`. Each key pressed +/// in it is let go in a second frame, as a person lets go of it. +fn frame(app: &mut VectorcraftApp, events: Vec, size: egui::Vec2) { + let ctx = CTX.with(Clone::clone); + let released: Vec = events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, physical_key, modifiers, pressed: true, .. } => { + Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + } + _ => None, + }) + .collect(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)); + let pressed = !released.is_empty(); + for events in std::iter::once(events).chain(pressed.then_some(released)) { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + dialogs::show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +const WINDOW: egui::Vec2 = egui::vec2(1200.0, 800.0); + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn alert_waits_and_stop_rolls_back_first_dialog() { + for stop_with_escape in [false, true] { + let mut app = app(); + start(&mut app, &format!("{DRAW} while (1) {{ alert('x'); }}")); + assert!(until_dialog(&mut app)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["kind"].as_str(), d.fields["message"].as_str(), d.fields["title"].clone()), (Some("alert"), Some("x"), Value::Null)); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the run waits at the dialog"); + assert_eq!(objects(&app), 0); + if stop_with_escape { + frame(&mut app, vec![key(egui::Key::Escape)], WINDOW); + } else { + answer(&mut app, "stop"); + } + assert!(app.ui.dialog.is_none()); + assert!(!until_dialog(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + } +} + +#[test] +fn confirm_enter_uses_no_as_default() { + for (no_as_default, want) in [(true, false), (false, true)] { + let mut app = app(); + start(&mut app, &format!("vc.log(confirm('Go?', {no_as_default}));")); + assert!(until_dialog(&mut app)); + frame(&mut app, vec![], WINDOW); + frame(&mut app, vec![key(egui::Key::Enter)], WINDOW); + assert!(app.ui.dialog.is_none(), "Enter answers the dialog: noAsDflt {no_as_default}"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([want]), "noAsDflt {no_as_default}"); + } + let mut app = app(); + start(&mut app, "vc.log(confirm('Go?'));"); + assert!(until_dialog(&mut app)); + frame(&mut app, vec![key(egui::Key::Escape)], WINDOW); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([false]), "Escape is No"); +} + +#[test] +fn prompt_ok_and_cancel_return_values() { + let mut app = app(); + start(&mut app, "vc.log(prompt('Name', 'pre', 'Ask')); vc.log(prompt('Again', 'x'));"); + assert!(until_dialog(&mut app)); + assert_eq!(dialogs::script_run::notice_heading(app.ui.dialog.as_ref().unwrap()), "Ask"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["value"], "pre"); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("typed")); + dialogs::confirm(&mut app).unwrap(); + assert!(until_dialog(&mut app)); + dialogs::cancel(&mut app); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!(["typed", null])); + let mut app = self::app(); + start(&mut app, "vc.log(prompt('Name', ''));"); + assert!(until_dialog(&mut app)); + let e = { + app.ui.dialog.as_mut().unwrap().fields.insert("answer".into(), json!("yes")); + dialogs::confirm(&mut app).unwrap_err() + }; + assert!(e.contains("ok, cancel, stop"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND, "a wrong answer leaves the dialog open"); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([""]), "OK with an empty field gives an empty string"); +} + +#[test] +fn the_dialog_opens_in_the_frame_the_run_waits() { + let mut app = app(); + start(&mut app, "alert('x');"); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(NOTICE_KIND), "no later frame is drawn while the run waits"); +} + +#[test] +fn a_prompt_text_past_the_limit_keeps_the_dialog_open() { + let mut app = app(); + start(&mut app, "vc.log(prompt('Name', ''));"); + assert!(until_dialog(&mut app)); + let long = "x".repeat(vectorcraft_engine::script::dialogs::MAX_PROMPT_BYTES + 1); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!(long)); + assert!(dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND, "the refused answer leaves the dialog open"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("ok")); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!(["ok"])); +} + +#[test] +fn dialog_wait_survives_another_modal() { + let mut app = app(); + start(&mut app, "alert('x');"); + script_runs::poll(&mut app); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); + let other = app.ui.dialog.clone(); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.clone()), other.map(|d| d.kind), "the open dialog stays"); + assert!(app.session.script_running()); + app.ui.dialog = None; + assert!(until_dialog(&mut app), "the script's dialog opens once the other one closes"); +} + +#[test] +fn close_while_notification_waits_abandons_or_resumes() { + let mut app = app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("half")); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND, "the run goes on waiting"); + dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["value"].as_str()), (NOTICE_KIND, Some("half")), "Cancel shows the dialog again as it was"); + dialogs::script_run::ask_to_close(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn notification_layout_with_long_text_and_small_window() { + let mut app = app(); + let long = "word ".repeat(3_000); + start(&mut app, &format!("alert({long:?} + '\\u0007\\r\\n', 'T\\nitle', true);")); + assert!(until_dialog(&mut app)); + for _ in 0..3 { + frame(&mut app, vec![], egui::vec2(320.0, 240.0)); + } + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND); + assert_eq!(dialogs::script_run::notice_heading(app.ui.dialog.as_ref().unwrap()), "T\u{240a}itle"); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["errorIcon"], true); +} + +#[test] +fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { + let source = "vc.log(confirm('a', true, 'T')); vc.log(prompt('b', 'p')); alert('c', undefined, false); vc.log('done');"; + let mut app = app(); + start(&mut app, source); + for a in ["yes", "ok", "ok"] { + assert!(until_dialog(&mut app)); + answer(&mut app, a); + } + assert!(!until_dialog(&mut app)); + let framed = app.session.script_report().unwrap().clone(); + let mut s = Session::new(); + let given = json!([{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "p"}, {"kind": "alert", "value": "ok"}]); + let headless = s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": given})).unwrap(); + assert_eq!(framed["log"], headless["log"]); + assert_eq!(framed["dialogs"], headless["dialogs"]); + assert_eq!(framed["log"], json!([true, "p", "done"])); +} diff --git a/docs/mcp.md b/docs/mcp.md index 069e13be45..596d0270f3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1561,6 +1561,8 @@ app through the global object `vc`, and writes to the Script Console through `$` - `vc.log(value)` adds a value to the report and a line to the Script Console. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. +- `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and `prompt(message, preset[, title])` + open a dialog, described below. `vc.api.has("dialogs")` is true. - `vc.args` is the `args` object. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. @@ -1600,15 +1602,17 @@ VectorCraft sets these limits itself: | `args` as JSON | 1 MiB | | Log | 10,000 entries and 4 MiB | | Script Console | 2,048 lines and 1 MiB of text; 4,096 bytes a line; 256 bytes of a script's name | +| A dialog's message, title and prompt text | 16 KiB, 256 bytes and 16 KiB | +| `answers` | 10,000 answers and 1 MiB as JSON | +| `dialogs` in the report | 10,000 dialogs and 1 MiB as JSON | | Growth before a person is asked | 100,000 objects and 512 MiB of new document data | In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, -runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console}`. In the app the reply is `{running: true, -name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same -fields after `kind`, `message`, `line`, `column` and `fuelLeft`. `answers` takes only an empty object, since scripts -have no prompts yet. +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The +report of a failed run has the same fields after `kind`, `message`, `line`, `column` and `fuelLeft`. - `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are left out. `timingAvailable` is false on the web, where `runTimeMs` is 0. @@ -1616,6 +1620,11 @@ have no prompts yet. - `slowestCommands` lists at most 5 commands as `{id, calls, totalMs, maxMs}`, the longest in all first, then by id. - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. +- `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` + for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the + run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + `dialogsTruncated` is true when the list stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -1625,6 +1634,46 @@ have no prompts yet. vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' ``` +The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/user-notification-dialogs/ +describes the three dialog functions. A script calls them as globals: + +- `alert(message[, title, errorIcon])` shows the message with OK, and an error icon when `errorIcon` is true. It + returns `undefined`. +- `confirm(message[, noAsDflt, title])` shows the message with Yes and No. Yes is the default button, and No is the + default when `noAsDflt` is true. It returns `true` for Yes and `false` for No. +- `prompt(message, preset[, title])` shows the message and a text field that starts with `preset`, with OK and + Cancel. It returns the field's text for OK, an empty string included, and `null` for Cancel. + +The message, the preset and a given title are read as `String(value)` gives them, and `errorIcon` and `noAsDflt` as +`Boolean(value)` gives them. A title that is left out or `undefined` is Script Alert. A call without a message, or a +`prompt` without a preset, throws a `TypeError`. A message or prompt text longer than 16 KiB, or a title longer than +256 bytes, throws a `RangeError` and opens no dialog. The dialog shows line feeds, carriage returns and the two +together as line breaks, and other control characters as their Unicode Control Pictures. The title stays on one +line, with line breaks shown as Control Pictures too. + +In the app, the run waits at the call until the person answers, and spends no instructions while it waits. Enter +gives the default button's answer. Escape gives Cancel for a prompt, No for a confirm and Stop for an alert. Every +dialog also has Stop, which ends the run as `script.stop` does and puts back every document. A dialog can open only +from the script's own code: called inside a callback of a built-in function such as `Array.prototype.forEach`, a +getter or a `toString` conversion, it throws an `Error`. Quitting while a dialog waits asks whether to stop the +script, and Cancel shows the dialog again with the text typed so far. In the app, `ui.dialog.confirm` answers the +open dialog (kind `scriptDialog`) with its `answer` field (`ok`, `yes`, `no`, `cancel` or `stop`), or with the +default button's answer when `answer` is left out. A prompt's `value` longer than 16 KiB is an error, and the +dialog stays open. + +A run with nobody to ask takes its answers from `answers`, a list of `{kind: "alert", value: "ok"}`, `{kind: +"confirm", value: true}` or `{kind: "confirm", value: false}`, and `{kind: "prompt", value: text}` or `{kind: +"prompt", value: null}` for Cancel. Each dialog takes the next answer in order, callbacks of built-in functions +included. The run ends with an error that the script cannot catch, and every document goes back, when no answer is +left, when the next answer is for another kind of dialog, or when the script ends with answers it did not use. +`script.run` refuses a list that is malformed, longer than 10,000 answers or larger than 1 MiB before the run starts, +and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an +empty object are the same. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' +``` + Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message`, its end, and a report of its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 30743351e4..6c08aa5d43 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -728,6 +728,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. + - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). From feda950bc867469ee9a24db611efa471ead004a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:16:00 -0800 Subject: [PATCH 29/83] Plug-ins: live effects of a document's first view share a 2,000 ms budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While the app draws a document on screen, the live-effect plug-in runs of its first view share a 2,000 ms budget (VectorCraft's own value); each run takes the lesser of its 5,000 ms limit and what is left. A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input art unchanged and is deferred, and the status bar says how many. Later drawings leave a deferred stage as it is until its input or parameters change. - effect.deferredStatus lists the deferred stages with object, effect index, fill or stroke, plug-in and reason, objects in symbol, pattern, brush and opacity-mask art included. - Effect › Refresh Deferred Effects (effect.refreshDeferred {ids?}) runs them again with a fresh budget and returns {refreshed, stillDeferred, failed}. - Each document has its own budget and deferred stages; exports, Expand Appearance and commands run every stage under the per-call limit. - The web build has no clock for the budget: its first view runs no plug-in effect, and a refresh runs them. Docs: docs/mcp.md, docs/plugins.md, docs/target-app-parity.md. --- crates/effects/src/bake.rs | 2 +- crates/effects/src/geometry.rs | 20 +- crates/effects/src/group.rs | 6 +- crates/effects/src/params.rs | 5 +- crates/effects/src/reshape.rs | 80 +-- crates/engine/src/cmd/effectcmd.rs | 146 ++++++ crates/engine/src/doc_state.rs | 4 + crates/engine/src/tests/plugins.rs | 168 +++++++ crates/plugins/src/deferred.rs | 724 +++++++++++++++++++++++++++ crates/plugins/src/effect.rs | 279 ++++++++++- crates/plugins/src/host.rs | 5 +- crates/plugins/src/lib.rs | 1 + crates/ui-egui/src/caches.rs | 6 +- crates/ui-egui/src/canvas.rs | 34 +- crates/ui-egui/src/canvas/fill.rs | 2 + crates/ui-egui/src/canvas/tests.rs | 47 ++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/menus/submenus.rs | 1 + crates/ui-egui/src/render_worker.rs | 5 +- docs/mcp.md | 21 +- docs/plugins.md | 13 + docs/target-app-parity.md | 1 + 48 files changed, 1651 insertions(+), 71 deletions(-) create mode 100644 crates/plugins/src/deferred.rs diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index afe256e596..3cc85ab1ea 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -395,7 +395,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { if !kept { return None; } - reshape_leaves(&mut m, &fx, Some(d)); + reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d)); m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id)); m.appearance.items.clear(); m.appearance.contents_index = None; diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 85248e08cf..a2e5478b28 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -26,6 +26,10 @@ pub struct GeomContext<'a> { /// The document that the swatches and patterns named by a live-effect plug-in that paints its /// pieces are looked up in. Without one, a result that names any is refused. pub doc: Option<&'a Document>, + /// The object, fill or stroke and effect index a deferred live-effect plug-in is listed by + /// ([`vectorcraft_plugins::deferred`]). When `None`, it is the object `seed` names, `item` and + /// the effect's index in the list being applied. + pub stage: Option, } impl<'a> GeomContext<'a> { @@ -36,7 +40,17 @@ impl<'a> GeomContext<'a> { _ => FillRule::NonZero, }; let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0); - Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None } + Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None, stage: None } + } + + /// The context of effect `e`, one of `list`: unless [`Self::stage`] is set, a live-effect + /// plug-in there is listed by `e`'s index in `list`. + pub(crate) fn at(self, list: &[Effect], e: &Effect) -> Self { + let stage = self.stage.or_else(|| { + let effect = list.iter().position(|x| std::ptr::eq(x, e))?; + Some(vectorcraft_plugins::deferred::Stage { object: self.seed, effect, item: self.item }) + }); + Self { stage, ..self } } /// The context of the effects on `item`, one of the same object's appearance items: a @@ -335,7 +349,7 @@ pub(crate) fn apply_geometry_carrying_within( } let p = merged_params(&e.id, &e.params); let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path))); - if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) { + if let Some(next) = apply_one(&e.id, &p, &cur, b, &ctx.at(effects, e), limit) { if let Some(c) = carry.as_deref_mut() { c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed)); } @@ -377,7 +391,7 @@ fn builds_within(id: &str) -> bool { fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData { use util::{join, num}; if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { - let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item }; + let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage }; return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone()); } match id { diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index d04982d98a..73d7266c31 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -209,7 +209,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod Some(area) => Some(reshaped(&area, n, doc)), None => { let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes); - let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc); + let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes follow the effects as its members do. if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); @@ -225,7 +225,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod let art = h(n).filter(|art| nodes.charge(art))?; let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); - let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, doc); + let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { carry.apply(&mut art.appearance); @@ -738,7 +738,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); - let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc); + let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. if paint && carry.moves(&m.appearance) { diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 5c06fae8fc..7785aff335 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -161,7 +161,8 @@ pub fn any_plugin_paints_output() -> bool { vectorcraft_plugins::registry::list().iter().any(|p| vectorcraft_plugins::effect::paints_output(&p.manifest().id)) } -/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed. +/// Changes whenever a plug-in is installed or removed (the registry's revision), and when deferred +/// live-effect plug-in stages give results ([`vectorcraft_plugins::deferred::revision`]). pub fn plugin_revision() -> u64 { - vectorcraft_plugins::registry::revision() + vectorcraft_plugins::registry::revision() ^ vectorcraft_plugins::deferred::revision().rotate_left(32) } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index f6c5cf2aea..0bdc134625 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -573,7 +573,7 @@ fn as_art_opts( } _ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?, }; - reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart, paint_doc); + reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc); if apart { hoist_copies(&mut art); } @@ -636,21 +636,22 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> { /// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The /// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path /// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns -/// that live-effect plug-ins painting their pieces name are looked up in `doc` -/// ([`reshape_leaves_apart`]). -pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) { - reshape_leaves_within(art, fx, Budget::EFFECTS, doc); +/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one +/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]). +pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) { + reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc); } /// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and /// strokes) follow the effects ([`crate::Carry`]). -pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) -> crate::Carry { - reshape_leaves_within(art, fx, Budget::EFFECTS, doc) +pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry { + reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc) } /// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost. +#[cfg(test)] pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry { - reshape_leaves_apart(art, fx, budget, false, doc) + reshape_leaves_apart(art, fx, &[], budget, false, doc) } /// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding @@ -669,12 +670,15 @@ fn hoist_copies(art: &mut Node) { } } -/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects +/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with +/// `apart`, a Transform effect's copies of each path are objects /// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect /// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]), /// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused). -/// Returns how gradients that paint the art as a whole follow the effects. -fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry { +/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect +/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when +/// `owner` does not hold it. +fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry { let mut whole = crate::Carry::default(); if fx.is_empty() { return whole; @@ -693,6 +697,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b }); let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); let style_safe = leaves_safe && !art_stroke; + let listed = fx; let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe); let fx = opt_fx.as_slice(); let seed = art.id.0; @@ -703,12 +708,15 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b for e in fx { let Some(bounds) = art.geometric_bounds() else { break }; let params = merged_params(&e.id, &e.params); + // Where a live-effect plug-in sits, which it is listed by when it is deferred. + let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); if let Some(plugin) = painted_plugin(e) { + let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); for_each_leaf(art, &mut |leaf| { let Some((path, _)) = leaf_geometry(leaf) else { return }; let before = Budget::of(&path); let room = max.minus(used.minus(before)); - if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc) { + if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc, at) { used = used.minus(before).plus(made); } }); @@ -778,7 +786,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b return; } } - let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else { + let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); + let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else { kept_ids.insert(leaf.id); return; }; @@ -1056,10 +1065,18 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling /// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces /// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost /// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are -/// refused, or they would pass `budget`. -fn paint_leaf(leaf: &mut Node, plugin: &str, params: &serde_json::Value, bounds: Rect, budget: Budget, doc: Option<&Document>) -> Option { +/// refused, or they would pass `budget`. A deferred run is listed by `at`. +fn paint_leaf( + leaf: &mut Node, + plugin: &str, + params: &serde_json::Value, + bounds: Rect, + budget: Budget, + doc: Option<&Document>, + at: Option, +) -> Option { let (path, rule) = leaf_geometry(leaf)?; - let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None }; + let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { @@ -1097,18 +1114,18 @@ fn piece_cost(path: &PathData) -> Budget { /// other fills and strokes; one that gives none keeps the leaf's. Returns /// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, /// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass -/// `budget`. +/// `budget`. A deferred run is listed by `at`. fn paint_piece( leaf: &mut Node, item: &AppearanceItem, - plugin: &str, - params: &serde_json::Value, + (plugin, params): (&str, &serde_json::Value), bounds: Rect, budget: Budget, doc: Option<&Document>, + at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; - let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0) }; + let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { @@ -1241,6 +1258,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt }; let Some(tb) = g.bounds() else { continue }; let params = merged_params(&fx[at].id, &fx[at].params); + // Where each effect the piece keeps sits among the item's effects. + let kept: Vec = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect(); if let Some(plugin) = painted_plugin(&fx[at]) { let mut it = item.clone(); let rest: Vec = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect(); @@ -1250,7 +1269,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt carry.apply(&mut one); } let it = one.items.pop().unwrap_or(it); - let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i) }; + let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) }; + let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) }; let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc) .map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::>()) .filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus))); @@ -1264,7 +1284,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt group.push(Arc::new(p)); } let mut p = Node::group(leaf.id, group); - transform_piece(&mut p, ctx.seed, limit, used, doc); + transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc); pieces.push(Arc::new(p)); continue; } @@ -1281,7 +1301,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt set_geometry(&mut p, g.clone(), rule); let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room); *used = used.plus(made); - transform_piece(&mut p, ctx.seed, limit, used, doc); + transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc); pieces.push(Arc::new(p)); } if !plain.is_empty() { @@ -1297,14 +1317,17 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt /// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a /// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece: /// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's -/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of +/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of /// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with /// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does. /// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path /// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and /// strokes; their other effects stay. The paths keep to `max` together with the rest of the art -/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. -fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: Option<&Document>) { +/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. `(seed, source, +/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the +/// piece was made from, and the index among that item's effects of each effect the piece kept, +/// which a deferred live-effect plug-in is listed by. +fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) { let mut count = 0; for_each_leaf(p, &mut |l| { if let Some(item) = l.appearance.items.first() { @@ -1320,8 +1343,9 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: // What the other paths leave of the budget. let before = Budget::of(&path); let room = max.minus(used.minus(before)); + let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; if let Some(plugin) = painted_plugin(&e) { - if let Some(made) = paint_piece(leaf, &item, plugin, &merged_params(&e.id, &e.params), bounds, room, doc) { + if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) { *used = used.minus(before).plus(made); } return; @@ -1340,7 +1364,7 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: AppearanceItem::Stroke(s) => Some(s), AppearanceItem::Fill(_) => None, }; - let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc }; + let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) }; let mut carry = crate::Carry::default(); let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry)); *used = used.minus(before).plus(Budget::of(&out)); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8bf5c9a3d7..a6850ab700 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -109,9 +109,155 @@ pub fn specs() -> Vec { has_doc, move_effect ), + cmd!( + query "effect.deferredStatus", + "Deferred Effects", + [], + None, + "{} the live-effect plug-in stages the active document left undrawn: while a document is drawn on screen, the plug-in effects of its first view share a 2,000 ms budget (each run also keeps to its own 5,000 ms limit); a stage left out for want of time, or one that times out, fails or has no plug-in, draws its input art unchanged and stays listed until it gives a result (Effect › Refresh Deferred Effects, an edit to its input or parameters, or an export, which runs every stage under the per-call limit), or until its object is deleted or its effect is removed, moved or hidden (or its fill or stroke is hidden) → {budgetMs: 2000, effects: [{objectId (also an object in the art of a symbol, pattern, brush or opacity mask), effectIndex (in the object's effects, or in the fill's or stroke's), item? (the fill or stroke whose effect it is), pluginId, reason: budget|timeout|missing|failed|safeMode}]} (empty: none)", + has_doc, + deferred_status + ), + cmd!( + "effect.refreshDeferred", + "Refresh Deferred Effects", + ["Effect"], + None, + "{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}", + has_deferred, + refresh_deferred + ), ] } +/// The active document has deferred live-effect plug-in stages ([`deferred_status`]). +fn has_deferred(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if deferred_effects(&st.doc, &st.plugin_effects).is_empty() { Err("no plug-in effect is deferred".into()) } else { Ok(()) } +} + +/// The objects the deferred stages of `fx` name, by id, each with whether it is in `d`'s layers. +/// An object that is not is looked for in the art `d` draws from elsewhere, where live-effect +/// plug-ins run too: the art of its symbols, patterns and brushes, and opacity masks. +fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap, bool)> { + let mut out = std::collections::HashMap::new(); + let mut rest = Vec::new(); + for object in fx.list().into_iter().map(|x| x.stage.object) { + match d.node_arc(NodeId(object)) { + Some(n) => { + out.insert(object, (n.clone(), true)); + } + None => rest.push(object), + } + } + if rest.is_empty() { + return out; + } + let brushes = vectorcraft_brush::library(d); + let symbols = d.symbols.iter().map(|s| &*s.art); + let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)); + let layers = d.layers.iter().map(|a| &**a); + let mut look = |n: &Node| { + if rest.contains(&n.id.0) { + out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false)); + } + }; + for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) { + vectorcraft_doc::swatches::walk_with_masks(a, &mut look); + } + out +} + +/// Is plug-in `plugin`'s effect at `stage`'s place in `n` (`None`: no such object), and visible, +/// on a visible fill or stroke when it is one's? +fn stage_holds(n: Option<&Node>, stage: vectorcraft_plugins::deferred::Stage, plugin: &str) -> bool { + let Some(n) = n else { return false }; + let list = match stage.item { + None => Some(n.appearance.effects.as_slice()), + Some(i) => n.appearance.items.get(i).filter(|it| it.visible()).map(|it| it.effects().as_slice()), + }; + list.and_then(|l| l.get(stage.effect)).is_some_and(|e| e.visible && e.id == vectorcraft_plugins::effect::effect_id(plugin)) +} + +/// Drops the records of `fx`'s stages whose object or plug-in effect is no longer at their place +/// in `d` ([`stage_holds`]), and gives the objects of the others ([`stage_objects`]). +fn prune(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap, bool)> { + let objects = stage_objects(d, fx); + fx.retain(|stage, plugin| stage_holds(objects.get(&stage.object).map(|(n, _)| &**n), stage, plugin)); + objects +} + +/// The deferred stages of `d` as `effect.deferredStatus` lists them. The records of stages whose +/// object or plug-in effect is no longer at their place in `d` are dropped first. +fn deferred_effects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> Vec { + prune(d, fx); + fx.list() + .into_iter() + .map(|x| { + let mut v = json!({"objectId": x.stage.object, "effectIndex": x.stage.effect, "pluginId": x.plugin, "reason": x.reason.name()}); + if let Some(i) = x.stage.item { + v["item"] = json!(i); + } + v + }) + .collect() +} + +/// `effect.deferredStatus`. +fn deferred_status(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + Ok(json!({"budgetMs": vectorcraft_plugins::deferred::OPENING_BUDGET_MS, "effects": deferred_effects(&st.doc, &st.plugin_effects)})) +} + +/// Draws `n` alone, small, as the canvas would (its live-effect plug-ins run inside the view that +/// applies): what matters is that it is drawn, not its pixels. Is every part of it drawn, none left +/// out for its size? +fn draw_small(renderer: &mut vectorcraft_render::Renderer, doc: &Document, n: &Arc) -> bool { + let Some(b) = n.geometric_bounds() else { return false }; + let scale = 64.0 / b.width().max(b.height()).max(1.0); + let view = vectorcraft_geom::Affine::scale(scale) * vectorcraft_geom::Affine::translate((1.0 - b.x0, 1.0 - b.y0)); + renderer.stats = Default::default(); + renderer.render_node(doc, n, 66, 66, view); + renderer.stats.culled == 0 +} + +/// `effect.refreshDeferred`: each object of the document's layers is drawn again alone, small, +/// inside the document's view, so its stages are run with the input they were deferred with; a +/// hidden object, or one in a hidden layer or group, is not drawn. An object in the art of a +/// symbol, pattern, brush or opacity mask runs where that art is used: the visible layers are +/// drawn then. A stage input left out of a small drawing for its size stays deferred. +fn refresh_deferred(s: &mut Session, p: &Value) -> Result { + let st = s.doc()?; + let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone()); + let ids = super::named_ids(p)?; + let objects = prune(&doc, &fx); + if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) { + return Err(EngineError::NoNode(*id)); + } + let ids: Option> = ids.map(|ids| ids.iter().map(|id| id.0).collect()); + let counts = fx.refresh(ids.as_deref(), |targets| { + let mut renderer = vectorcraft_render::Renderer::new(); + let mut whole = Vec::new(); + fx.view(|| { + let mut elsewhere = false; + for id in targets { + match objects.get(id) { + Some((n, true)) if doc.is_visible(NodeId(*id)) && draw_small(&mut renderer, &doc, n) => whole.push(*id), + Some((_, false)) => elsewhere = true, + _ => {} + } + } + if elsewhere { + for layer in doc.layers.iter().filter(|l| l.visible) { + draw_small(&mut renderer, &doc, layer); + } + } + }); + whole + }); + Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed})) +} + fn ids_json(ids: &[NodeId]) -> Value { json!(ids.iter().map(|i| i.0).collect::>()) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index d0e4862404..08b8a2f294 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -110,6 +110,9 @@ pub struct DocState { /// paths the document links to are looked at within them later too, when the Links panel /// asks about a link outside any caller's scope. pub opened_by: Option>, + /// The live-effect plug-in stages deferred while the document is drawn on screen, and the time + /// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved. + pub plugin_effects: vectorcraft_plugins::deferred::Deferrals, /// What [`DocState::any_empty_artboards`] last measured. Not saved. empty_artboards: std::cell::RefCell, /// What [`DocState::any_art_to_fit`] last measured. Not saved. @@ -326,6 +329,7 @@ impl DocState { last_perspective: None, opened_by: file_access::current(), empty_artboards: Default::default(), + plugin_effects: Default::default(), art_to_fit: Default::default(), } } diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index aca18dee1e..04e7b7784e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -980,6 +980,174 @@ fn painted_pieces_keep_to_the_effects_budget() { assert!((350..=100_000).contains(&paths), "{paths} paths"); } +/// A clock for a document's deferrals that reads `step` milliseconds later each time it is read; +/// the test changes the step as it goes. +fn stepping_clock(step: &std::sync::Arc) -> vectorcraft_plugins::deferred::Clock { + let (now, step) = (std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), step.clone()); + std::sync::Arc::new(move || Some(now.fetch_add(step.load(std::sync::atomic::Ordering::Relaxed), std::sync::atomic::Ordering::Relaxed))) +} + +/// While a document is drawn on screen, the plug-in effects of its first view share a time budget. +/// A stage left out draws its input art, is listed by `effect.deferredStatus`, and stays left out +/// on later drawings; Effect › Refresh Deferred Effects runs it again with a fresh budget, and an +/// export draws every stage. Another document has a budget of its own. +#[test] +fn the_first_view_defers_plug_in_effects_past_its_budget() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let b = rect(&mut s, 30.0, "#ff0000"); + for (id, x) in [("test.engine.deferred.a", 100.0), ("test.engine.deferred.b", 140.0)] { + let out = json!({"objects": [{"path": square_at(x)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "effect", "{}"), &out)); + } + run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.a"})); + run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "plugin.test.engine.deferred.b"})); + // Each reading is 3 s later: the first run's result comes back after the budget, and the + // second run doesn't start. + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + let img = fx.view(|| drawn(&s)); + fx.first_view_done(); + assert_eq!((img.pixel(15, 15), img.pixel(35, 15), img.pixel(110, 50), img.pixel(150, 50)), (RED, RED, WHITE, WHITE), "the input art"); + assert_eq!(fx.take_report(), Some(2)); + let status = run(&mut s, "effect.deferredStatus", json!({})); + let listed = |id: NodeId, plugin: &str| json!({"objectId": id.0, "effectIndex": 0, "pluginId": plugin, "reason": "budget"}); + assert_eq!(status, json!({"budgetMs": 2000, "effects": [listed(a, "test.engine.deferred.a"), listed(b, "test.engine.deferred.b")]})); + assert_eq!(fx.view(|| drawn(&s)).pixel(110, 50), WHITE, "a later drawing leaves it deferred"); + + // Refreshed with a fresh budget, in which the clock stands still. + assert!(s.execute("effect.refreshDeferred", &json!({"ids": ["a"]})).is_err()); + assert!(s.execute("effect.refreshDeferred", &json!({"ids": [999_999]})).is_err(), "not an object of the document"); + step.store(0, std::sync::atomic::Ordering::Relaxed); + let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0]})); + assert_eq!(refreshed, json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(110, 50), img.pixel(150, 50)), (RED, WHITE)); + assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([listed(b, "test.engine.deferred.b")])); + + // An export draws every stage; the view then uses the result. + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.contains(r#">(); + assert_eq!(places, [(a.0, None, 1), (a.0, None, 2), (b.0, Some(0), 1), (b.0, Some(0), 2)]); +} + +/// A refresh that does not draw a stage (its object, or a group holding it, is hidden) leaves it +/// deferred, and a stage whose effect has been removed or hidden, or whose object has been removed, +/// is no longer listed and does not enable Effect › Refresh Deferred Effects. +#[test] +fn refresh_keeps_stages_it_did_not_draw_and_drops_removed_ones() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let b = rect(&mut s, 30.0, "#ff0000"); + let c = rect(&mut s, 50.0, "#ff0000"); + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.kept", "effect", "{}"), &out)); + run(&mut s, "effect.apply", json!({"ids": [a.0, b.0, c.0], "effect": "plugin.test.engine.deferred.kept"})); + run(&mut s, "select.set", json!({"ids": [c.0]})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + let listed = |s: &mut Session| { + run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::>() + }; + assert_eq!(listed(&mut s), [a.0, b.0, c.0]); + + s.execute("object.hide", &json!({"ids": [a.0, g.0]})).unwrap(); + step.store(0, std::sync::atomic::Ordering::Relaxed); + let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0, c.0]})); + assert_eq!(refreshed, json!({"refreshed": 0, "stillDeferred": 2, "failed": 0}), "a hidden object is not drawn"); + assert_eq!(listed(&mut s), [a.0, b.0, c.0]); + + run(&mut s, "effect.remove", json!({"ids": [a.0], "index": 0})); + assert_eq!(listed(&mut s), [b.0, c.0], "its effect was removed"); + run(&mut s, "effect.setParams", json!({"ids": [b.0], "index": 0, "visible": false})); + assert_eq!(listed(&mut s), [c.0], "its effect was hidden"); + s.execute("edit.clear", &json!({"ids": [b.0, g.0]})).unwrap(); + assert_eq!(listed(&mut s), Vec::::new(), "its object was deleted"); + assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred"); +} + +/// A deferred stage in a symbol's art is listed by the object in that art, and a refresh runs it +/// where the symbol is placed. +#[test] +fn deferred_stages_in_symbol_art_are_listed_and_refreshed() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.symbol", "effect", "{}"), &out)); + run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.symbol"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let instance = run(&mut s, "symbol.new", json!({"name": "Deferred"}))["id"].as_u64().unwrap(); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + assert_eq!(fx.take_report(), Some(1)); + let effects = run(&mut s, "effect.deferredStatus", json!({}))["effects"].clone(); + let object = effects[0]["objectId"].as_u64().unwrap(); + assert_eq!(effects.as_array().map(Vec::len), Some(1), "{effects}"); + assert!(object != instance && s.doc().unwrap().doc.node(NodeId(object)).is_none(), "an object of the symbol's art: {effects}"); + + step.store(0, std::sync::atomic::Ordering::Relaxed); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([])); +} + /// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app /// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its /// object's stroke is 5 pt wide, and hands the geometry back otherwise. diff --git a/crates/plugins/src/deferred.rs b/crates/plugins/src/deferred.rs new file mode 100644 index 0000000000..f817f32d90 --- /dev/null +++ b/crates/plugins/src/deferred.rs @@ -0,0 +1,724 @@ +//! Live-effect plug-ins while a document opens: the plug-in effects drawn for its first view share +//! a time budget of [`OPENING_BUDGET_MS`], and a stage that is not run for want of time, or that +//! gives no result, is deferred: it draws its input art and is listed with the reason +//! ([`Deferrals::list`]) until it runs again. +//! +//! One [`Deferrals`] belongs to each open document. Drawing that document on screen runs inside +//! [`Deferrals::view`], which applies its budget and its deferred stages to the plug-in effects +//! evaluated on that thread ([`crate::effect`]): +//! +//! - until [`Deferrals::first_view_done`], every run takes the lesser of its per-call limit and +//! what is left of the budget, no run starts once the budget is spent, and a result that comes +//! back after the budget ran out is not used; +//! - afterwards a deferred stage is not run again while its input and parameters stay the same; a +//! stage whose input or parameters changed runs under the per-call limit; +//! - [`Deferrals::refresh`] runs deferred stages again with a fresh budget. +//! +//! Work outside a view (exports, commands, drawing without a screen) runs every stage under the +//! per-call limit. When such a run gives a result for a stage some document has deferred, +//! [`revision`] changes, so that drawings made with the deferred stage are drawn again. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// The time the plug-in effects drawn for a document's first view share, in milliseconds. +pub const OPENING_BUDGET_MS: u64 = 2_000; + +/// Why a stage is deferred. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Reason { + /// It was not run, or its result came too late, because the budget was spent. + Budget, + /// It ran to its per-call time limit. + Timeout, + /// Its plug-in isn't installed as a live effect. + Missing, + /// It trapped, panicked, returned art that was refused, or its parameters were refused. + Failed, + /// Safe Mode is on: no plug-in runs. + SafeMode, +} + +impl Reason { + /// The reason as `effect.deferredStatus` names it. + pub fn name(self) -> &'static str { + match self { + Reason::Budget => "budget", + Reason::Timeout => "timeout", + Reason::Missing => "missing", + Reason::Failed => "failed", + Reason::SafeMode => "safeMode", + } + } +} + +/// Where a plug-in effect sits: the object, the index of the effect in its list, and the fill or +/// stroke whose list that is (`None`: the object's own effects). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Stage { + pub object: u64, + pub effect: usize, + pub item: Option, +} + +/// A deferred stage. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Deferred { + pub stage: Stage, + /// The plug-in's id. + pub plugin: String, + pub reason: Reason, + /// The input and parameters the stage was deferred with (the effect cache's key), 0 when the + /// plug-in was not looked at (Safe Mode, a missing plug-in). + pub(crate) key: u64, +} + +/// What [`Deferrals::refresh`] did with the stages it ran again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Refreshed { + /// Stages that gave a result. + pub refreshed: usize, + /// Stages left deferred for want of time, or with input the refresh did not run. + pub still_deferred: usize, + /// Stages that ran out of their per-call time, failed or had no plug-in again. + pub failed: usize, +} + +/// Milliseconds on a monotonic clock, `None` where there is none (the web build). +pub type Clock = Arc Option + Send + Sync>; + +/// Milliseconds since the first reading in this process (native builds); `None` on the web build, +/// whose `std` has no monotonic clock. +fn monotonic() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let start = START.get_or_init(std::time::Instant::now); + Some(u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)) + } + #[cfg(target_arch = "wasm32")] + None +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Phase { + /// Runs share a budget that started at `started` (`None`: no run yet). `first`: the first + /// view, which reports what it deferred when it ends. + Budgeted { started: Option, first: bool }, + /// Deferred stages are left as they are while their input stays the same. + Open, +} + +struct State { + phase: Phase, + deferred: Vec, + /// How many stages the first view left deferred, until [`Deferrals::take_report`] takes it. + report: Option, + /// The refresh running, if one is ([`Deferrals::refresh`]). + refresh: Option, + clock: Clock, +} + +/// A [`Deferrals::refresh`] while it runs. It applies only to the thread that runs it: drawings +/// of the document on other threads go on as if no refresh ran. +struct Refresh { + thread: std::thread::ThreadId, + /// When its budget started (`None`: no run yet). + started: Option, + /// The objects whose stages run again; the others' stay deferred. + ids: Vec, + /// The cache keys whose cached failures have been run again. + retried: Vec, + /// The stages of `ids` that were drawn. + visited: Vec, + /// The stage inputs of `ids` that ran, or were taken from the cache, or were deferred again. + touched: Vec<(Stage, u64)>, +} + +impl State { + /// The refresh running on this thread. + fn refresh_here(&mut self) -> Option<&mut Refresh> { + let here = std::thread::current().id(); + self.refresh.as_mut().filter(|r| r.thread == here) + } + + /// The phase that applies on this thread: a refresh running here has a budget of its own. + fn phase_here(&mut self) -> Phase { + match self.refresh_here() { + Some(r) => Phase::Budgeted { started: r.started, first: false }, + None => self.phase, + } + } + + /// Is a refresh running here, and does it run the stages of `object`? + fn refreshes(&mut self, object: u64) -> Option { + self.refresh_here().map(|r| r.ids.contains(&object)) + } +} + +impl Drop for State { + fn drop(&mut self) { + for d in &self.deferred { + unmark(d.key); + } + } +} + +/// The deferred stages and the opening budget of one open document. Clones share them. +#[derive(Clone)] +pub struct Deferrals(Arc>); + +impl Default for Deferrals { + fn default() -> Self { + Self::with_clock(Arc::new(monotonic)) + } +} + +impl std::fmt::Debug for Deferrals { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Deferrals").field("deferred", &self.list()).finish() + } +} + +/// What a budgeted run may take. +pub(crate) enum Allowance { + /// No budget applies: the per-call limit. + Unlimited, + /// At most this many milliseconds, which end the budget at `until`. + Until { ms: u64, until: u64 }, + /// The budget is spent: the stage is deferred without running. + Spent, +} + +impl Deferrals { + /// A document's deferrals before its first view, timed by the monotonic clock. + pub fn new() -> Self { + Self::default() + } + + /// [`Deferrals::new`] timed by `clock` (tests give a clock of their own). + pub fn with_clock(clock: Clock) -> Self { + Self(Arc::new(Mutex::new(State { + phase: Phase::Budgeted { started: None, first: true }, + deferred: Vec::new(), + report: None, + refresh: None, + clock, + }))) + } + + fn state(&self) -> std::sync::MutexGuard<'_, State> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The deferred stages, by object and effect, each once (a stage drawn with several inputs, + /// such as the paths of a group, is listed with the first one's reason). + pub fn list(&self) -> Vec { + let mut out = self.state().deferred.clone(); + out.sort_by_key(|d| (d.stage.object, d.stage.item, d.stage.effect)); + out.dedup_by_key(|d| d.stage); + out + } + + /// Is the first view still being drawn ([`Deferrals::first_view_done`] not called yet)? + pub fn opening(&self) -> bool { + matches!(self.state().phase, Phase::Budgeted { first: true, .. }) + } + + /// Runs `f` with these deferrals applied to the plug-in effects evaluated on this thread. + pub fn view(&self, f: impl FnOnce() -> T) -> T { + let previous = VIEW.with(|v| v.borrow_mut().replace(self.clone())); + let _ = PASSES.try_with(|p| p.borrow_mut().push(Pass::default())); + let _restore = Restore { previous, current: self.clone() }; + f() + } + + /// One drawing inside [`Deferrals::view`] has ended: a stage that ran after the first view, + /// whether it gave a result or was deferred again, keeps only the records of the inputs that + /// drawing left deferred. The records of its other inputs were made with input it no longer + /// has. + fn settle(&self, pass: Pass) { + if pass.ran.is_empty() { + return; + } + self.state().deferred.retain(|d| { + let keep = !pass.ran.contains(&d.stage) || pass.seen.contains(&(d.stage, d.key)); + if !keep { + unmark(d.key); + } + keep + }); + } + + /// The first view has been drawn: later drawings leave deferred stages deferred, and + /// [`Deferrals::take_report`] gives how many there are. Does nothing after the first call. + pub fn first_view_done(&self) { + let mut s = self.state(); + if let Phase::Budgeted { first: true, .. } = s.phase { + s.phase = Phase::Open; + s.report = Some(s.stages().len()); + } + } + + /// How many stages the first view left deferred, once, after it was drawn. + pub fn take_report(&self) -> Option { + self.state().report.take() + } + + /// Runs the deferred stages of the objects in `objects` (all of them when `None`) again with a + /// fresh budget: `run` is given those objects, draws them inside [`Deferrals::view`] on this + /// thread, and returns the objects it drew whole, every part of them reached. A stage the + /// drawing does not reach (that of a hidden object, say) stays deferred as it was, and so does + /// a stage input it does not reach, unless the object was drawn whole: the input is then one + /// the stage no longer has. The refresh and its budget apply only to this thread. + pub fn refresh(&self, objects: Option<&[u64]>, run: impl FnOnce(&[u64]) -> Vec) -> Refreshed { + let (targets, ids) = { + let mut s = self.state(); + let mut targets: Vec = s.deferred.iter().map(|d| d.stage).filter(|t| objects.is_none_or(|o| o.contains(&t.object))).collect(); + targets.sort_by_key(|t| (t.object, t.item, t.effect)); + targets.dedup(); + let mut ids: Vec = targets.iter().map(|t| t.object).collect(); + ids.dedup(); + let thread = std::thread::current().id(); + let (retried, visited, touched) = (Vec::new(), Vec::new(), Vec::new()); + s.refresh = Some(Refresh { thread, started: None, ids: ids.clone(), retried, visited, touched }); + (targets, ids) + }; + // The refresh ends when `run` returns, also when it unwinds. + struct Reopen<'a>(&'a Deferrals); + impl Drop for Reopen<'_> { + fn drop(&mut self) { + self.0.state().refresh = None; + } + } + let reopen = Reopen(self); + let whole = run(&ids); + let mut s = self.state(); + let touched = match s.refresh.take() { + Some(r) => { + s.deferred.retain(|d| { + let gone = r.visited.contains(&d.stage) && whole.contains(&d.stage.object) && !r.touched.contains(&(d.stage, d.key)); + if gone { + unmark(d.key); + } + !gone + }); + r.touched + } + None => Vec::new(), + }; + drop(s); + drop(reopen); + // A stage fails again when an input it ran with this time is deferred for a reason other + // than time; one with records left that this refresh did not run is still deferred. + let s = self.state(); + let mut out = Refreshed::default(); + for t in &targets { + let mut left = s.deferred.iter().filter(|d| d.stage == *t).peekable(); + if left.peek().is_none() { + out.refreshed += 1; + } else if left.any(|d| d.reason != Reason::Budget && touched.contains(&(d.stage, d.key))) { + out.failed += 1; + } else { + out.still_deferred += 1; + } + } + drop(s); + if out.refreshed > 0 { + REVISION.fetch_add(1, Ordering::Relaxed); + } + out + } + + /// Records `stage` with cache key `key` (of plug-in `plugin`) as deferred for `reason`, in + /// place of what was recorded for that stage and key. After the first view, when the drawing + /// ends, the stage's records of inputs that drawing did not leave deferred are dropped + /// ([`Deferrals::settle`]). + pub(crate) fn defer(&self, stage: Stage, plugin: &str, reason: Reason, key: u64) { + seen(stage, key); + let mut s = self.state(); + s.remove(stage, key); + mark(key); + s.deferred.push(Deferred { stage, plugin: plugin.to_string(), reason, key }); + s.ran_here(stage, key); + } + + /// `stage` gave a result for cache key `key`, from a run or from the cache: it is no longer + /// deferred with that input. After the first view, when the drawing ends, the stage's records + /// of inputs that drawing did not leave deferred are dropped as well ([`Deferrals::settle`]). + pub(crate) fn ran(&self, stage: Stage, key: u64) { + let mut s = self.state(); + s.remove(stage, key); + s.ran_here(stage, key); + } + + /// Should `stage`, with cache key `key`, be left deferred without running? After the first + /// view, a stage deferred with the same input and parameters is, and so is one of an object a + /// refresh does not run. + pub(crate) fn holds(&self, stage: Stage, key: u64) -> bool { + let mut s = self.state(); + let settled = s.phase_here() == Phase::Open || s.refreshes(stage.object) == Some(false); + let held = settled && s.deferred.iter().any(|d| d.stage == stage && d.key == key); + drop(s); + if held { + seen(stage, key); + } + held + } + + /// `stage` is being drawn: a refresh running here that runs its object's stages notes that it + /// reached the stage. + pub(crate) fn visit(&self, stage: Stage) { + let mut s = self.state(); + if let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.visited.contains(&stage)) { + r.visited.push(stage); + } + } + + /// Drops the records of the stages for which `keep` (given the stage and the plug-in id) is + /// false, such as those of effects or objects removed from the document. + pub fn retain(&self, keep: impl Fn(Stage, &str) -> bool) { + self.state().deferred.retain(|d| { + let k = keep(d.stage, &d.plugin); + if !k { + unmark(d.key); + } + k + }); + } + + /// Should the failure cached for `stage` with cache key `key` be run again? Yes once per key + /// while a refresh running here runs the stages of `stage`'s object. + pub(crate) fn retries(&self, stage: Stage, key: u64) -> bool { + let mut s = self.state(); + let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.retried.contains(&key)) else { return false }; + r.retried.push(key); + true + } + + /// What a run starting now may take of the budget: the budget starts with the first run. + /// Without a clock, the first view runs nothing and a refresh runs every stage under its + /// per-call limit. + pub(crate) fn allowance(&self) -> Allowance { + let mut s = self.state(); + let Phase::Budgeted { started, first } = s.phase_here() else { return Allowance::Unlimited }; + let Some(now) = (s.clock)() else { return if first { Allowance::Spent } else { Allowance::Unlimited } }; + let start = started.unwrap_or(now); + match s.refresh_here() { + Some(r) => r.started = Some(start), + None => s.phase = Phase::Budgeted { started: Some(start), first }, + } + let until = start.saturating_add(OPENING_BUDGET_MS); + match until.checked_sub(now).filter(|ms| *ms > 0) { + Some(ms) => Allowance::Until { ms, until }, + None => Allowance::Spent, + } + } + + /// Has the clock passed `until` (a result that came back now is too late)? Without a clock, + /// yes. + pub(crate) fn passed(&self, until: u64) -> bool { + let clock = self.state().clock.clone(); + clock().is_none_or(|now| now > until) + } +} + +impl State { + /// Removes what is recorded for `stage` with cache key `key`. A record without a key (the + /// plug-in was not looked at) stands for any input, so it goes whatever `key` is, and `key` 0 + /// removes every record of the stage. + fn remove(&mut self, stage: Stage, key: u64) { + self.deferred.retain(|d| { + let keep = d.stage != stage || (d.key != key && d.key != 0 && key != 0); + if !keep { + unmark(d.key); + } + keep + }); + } + + /// `stage` was run with cache key `key`, or taken from the cache, by the drawing on this + /// thread: a refresh running here notes the input ([`Deferrals::refresh`]), and after the first + /// view [`Deferrals::settle`] looks at the stage when that drawing ends. + fn ran_here(&mut self, stage: Stage, key: u64) { + if let Some(r) = self.refresh_here().filter(|r| r.ids.contains(&stage.object)) { + r.touched.push((stage, key)); + } + if self.phase_here() == Phase::Open { + let _ = PASSES.try_with(|p| { + if let Some(pass) = p.borrow_mut().last_mut().filter(|pass| !pass.ran.contains(&stage)) { + pass.ran.push(stage); + } + }); + } + } + + /// The deferred stages, each once. + fn stages(&self) -> Vec { + let mut out: Vec = self.deferred.iter().map(|d| d.stage).collect(); + out.sort_by_key(|t| (t.object, t.item, t.effect)); + out.dedup(); + out + } +} + +thread_local! { + static VIEW: RefCell> = const { RefCell::new(None) }; + /// One entry for each [`Deferrals::view`] running on this thread, innermost last. + static PASSES: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// What one drawing inside a view did: the stages that ran after the first view (with a result or +/// deferred again), and the stage inputs it left deferred. +#[derive(Default)] +struct Pass { + ran: Vec, + seen: Vec<(Stage, u64)>, +} + +/// The drawing on this thread left `stage` deferred with cache key `key`. +fn seen(stage: Stage, key: u64) { + let _ = PASSES.try_with(|p| { + if let Some(pass) = p.borrow_mut().last_mut() { + pass.seen.push((stage, key)); + } + }); +} + +/// Ends the drawing and puts the previous view back, also when the work inside unwinds. +struct Restore { + previous: Option, + current: Deferrals, +} + +impl Drop for Restore { + fn drop(&mut self) { + if let Some(pass) = PASSES.try_with(|p| p.borrow_mut().pop()).ok().flatten() { + self.current.settle(pass); + } + let previous = self.previous.take(); + let _ = VIEW.try_with(|v| *v.borrow_mut() = previous); + } +} + +/// The deferrals of the view being drawn on this thread ([`Deferrals::view`]). +pub fn current() -> Option { + VIEW.try_with(|v| v.borrow().clone()).ok().flatten() +} + +/// Changes when deferred stages give results: [`Deferrals::refresh`] ran some, or a run outside a +/// view gave a result for a stage some document has deferred. +pub fn revision() -> u64 { + REVISION.load(Ordering::Relaxed) +} + +static REVISION: AtomicU64 = AtomicU64::new(0); + +/// The cache keys some document's deferred stages were deferred with, and how many stages hold each. +static MARKED: Mutex>> = Mutex::new(None); + +fn mark(key: u64) { + if key != 0 { + *MARKED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).entry(key).or_default() += 1; + } +} + +fn unmark(key: u64) { + let mut marked = MARKED.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = marked.as_mut() else { return }; + if let Some(n) = m.get_mut(&key) { + *n -= 1; + if *n == 0 { + m.remove(&key); + } + } +} + +/// A run gave a result for cache key `key`: when some document deferred a stage with that key, +/// [`revision`] changes. +pub(crate) fn resolved(key: u64) { + let marked = MARKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&key)); + if marked { + REVISION.fetch_add(1, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A clock that reads `step` milliseconds later each time it is read. + fn stepping(step: u64) -> Clock { + let t = Arc::new(AtomicU64::new(0)); + Arc::new(move || Some(t.fetch_add(step, Ordering::Relaxed))) + } + + #[test] + fn the_budget_starts_with_the_first_run_and_ends_after_it() { + let d = Deferrals::with_clock(stepping(700)); + assert!(matches!(d.allowance(), Allowance::Until { ms: 2_000, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Until { ms: 1_300, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Until { ms: 600, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Spent)); + d.first_view_done(); + assert!(matches!(d.allowance(), Allowance::Unlimited)); + } + + #[test] + fn without_a_clock_the_first_view_runs_nothing_and_a_refresh_everything() { + let d = Deferrals::with_clock(Arc::new(|| None)); + assert!(matches!(d.allowance(), Allowance::Spent)); + assert!(d.passed(u64::MAX)); + d.first_view_done(); + d.defer(Stage::default(), "a", Reason::Budget, 31); + d.refresh(None, |_| { + assert!(matches!(d.allowance(), Allowance::Unlimited)); + vec![] + }); + } + + /// A stage drawn with several inputs (the paths of a group) holds one record for each, and is + /// listed and counted once. + #[test] + fn a_stage_is_listed_and_counted_once() { + let d = Deferrals::with_clock(stepping(1)); + let s = Stage { object: 7, effect: 1, item: None }; + d.defer(s, "a", Reason::Budget, 11); + d.defer(s, "a", Reason::Budget, 12); + d.defer(s, "a", Reason::Timeout, 12); + d.defer(Stage { item: Some(0), ..s }, "a", Reason::Failed, 13); + assert_eq!(d.list().len(), 2); + assert!(!d.holds(s, 12), "the first view runs deferred stages"); + d.first_view_done(); + assert!(d.holds(s, 11) && d.holds(s, 12)); + assert!(!d.holds(s, 14), "other input"); + assert_eq!(d.take_report(), Some(2)); + assert_eq!(d.take_report(), None); + d.first_view_done(); + assert_eq!(d.take_report(), None, "the first view ends once"); + d.ran(s, 11); + assert_eq!(d.list().len(), 2, "the stage is still deferred with its other input"); + d.ran(s, 12); + assert_eq!(d.list().len(), 1); + d.defer(s, "a", Reason::Missing, 0); + d.ran(s, 15); + assert_eq!(d.list().len(), 1, "a record without a key goes with any result"); + } + + /// A refresh runs the deferred stages of the objects asked for with a fresh budget, and counts + /// what became of them; the stages its drawing did not reach stay as they were. Another + /// thread draws the document as if no refresh ran. + #[test] + fn a_refresh_counts_what_became_of_each_stage() { + let d = Deferrals::with_clock(stepping(1)); + d.first_view_done(); + let st = |object, effect| Stage { object, effect, item: None }; + let stages = [ + (st(1, 0), Reason::Budget), + (st(1, 1), Reason::Budget), + (st(1, 2), Reason::Budget), + (st(1, 3), Reason::Timeout), + (st(2, 0), Reason::Budget), + (st(3, 0), Reason::Failed), + ]; + for (stage, reason) in stages { + d.defer(stage, "a", reason, 40 + stage.object * 4 + stage.effect as u64); + } + let seen = std::cell::RefCell::new(vec![]); + let counts = d.refresh(Some(&[1, 3, 9]), |ids| { + seen.borrow_mut().extend_from_slice(ids); + assert!(matches!(d.allowance(), Allowance::Until { .. }), "a fresh budget"); + assert!(d.holds(st(2, 0), 48), "an object not asked for stays deferred"); + d.visit(st(2, 0)); + d.visit(st(1, 0)); + d.visit(st(1, 1)); + d.defer(st(1, 1), "a", Reason::Budget, 45); + std::thread::scope(|scope| { + let other = scope.spawn(|| (matches!(d.allowance(), Allowance::Unlimited), d.holds(st(1, 2), 46), d.retries(st(3, 0), 52))); + assert_eq!(other.join().unwrap(), (true, true, false), "another thread"); + }); + d.visit(st(1, 1)); + assert_eq!(d.list().iter().filter(|x| x.stage == st(1, 1)).count(), 1, "a stage is reached once"); + d.visit(st(3, 0)); + d.defer(st(3, 0), "a", Reason::Failed, 52); + ids.to_vec() + }); + assert_eq!(*seen.borrow(), [1, 3]); + // st(1, 3) timed out before and was not reached: still deferred, not failed again. + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 3, failed: 1 }); + assert!(matches!(d.allowance(), Allowance::Unlimited), "the budget ends with the refresh"); + let left = d.list().iter().map(|x| x.stage).collect::>(); + assert_eq!(left, [st(1, 1), st(1, 2), st(1, 3), st(2, 0), st(3, 0)]); + + // An object the drawing did not reach whole keeps the inputs it did not reach: a reached + // stage of it gives a result only for the inputs that ran. + d.defer(st(1, 1), "a", Reason::Budget, 70); + let counts = d.refresh(Some(&[1]), |_| { + d.visit(st(1, 1)); + d.ran(st(1, 1), 45); + vec![] + }); + assert_eq!(counts, Refreshed { refreshed: 0, still_deferred: 3, failed: 0 }); + let keys = |stage| d.state().deferred.iter().filter(|x| x.stage == stage).map(|x| x.key).collect::>(); + assert_eq!(keys(st(1, 1)), [70]); + let counts = d.refresh(Some(&[1]), |_| { + d.visit(st(1, 1)); + vec![1] + }); + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 2, failed: 0 }, "drawn whole: an input it no longer has"); + assert_eq!(keys(st(1, 1)), Vec::::new()); + d.retain(|stage, _| stage.object != 1); + assert_eq!(d.list().iter().map(|x| x.stage).collect::>(), [st(2, 0), st(3, 0)]); + } + + /// After the first view, a stage drawn with several inputs (the paths of a group) whose one + /// changed input runs keeps the records of the inputs the same drawing left deferred, and drops + /// the record of the input it no longer has. + #[test] + fn a_stage_that_runs_keeps_the_inputs_its_drawing_left_deferred() { + let d = Deferrals::with_clock(stepping(1)); + let s = Stage { object: 4, effect: 0, item: None }; + let other = Stage { object: 5, ..s }; + for key in [61, 62] { + d.defer(s, "a", Reason::Budget, key); + } + d.defer(other, "a", Reason::Budget, 63); + d.first_view_done(); + d.view(|| { + assert!(d.holds(s, 61), "an unchanged path"); + assert!(!d.holds(s, 64), "the changed path"); + d.ran(s, 64); + }); + let keys = d.state().deferred.iter().map(|x| (x.stage.object, x.key)).collect::>(); + assert_eq!(keys, [(4, 61), (5, 63)]); + + // A changed input that fails again replaces the record of the input it no longer has. + d.view(|| { + assert!(!d.holds(other, 65)); + d.defer(other, "a", Reason::Failed, 65); + }); + let left = d.state().deferred.iter().map(|x| (x.stage.object, x.key, x.reason)).collect::>(); + assert_eq!(left, [(4, 61, Reason::Budget), (5, 65, Reason::Failed)]); + } + + #[test] + fn a_result_for_a_deferred_key_changes_the_revision() { + const KEY: u64 = 0xdef0_0001; + let marked = || MARKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&KEY)); + let d = Deferrals::with_clock(stepping(1)); + assert!(!marked()); + d.defer(Stage::default(), "a", Reason::Budget, KEY); + let other = d.clone(); + other.defer(Stage { object: 2, ..Stage::default() }, "a", Reason::Budget, KEY); + assert!(marked()); + let before = revision(); + resolved(KEY); + assert!(revision() > before); + other.ran(Stage::default(), KEY); + assert!(marked(), "another stage holds the key"); + drop((d, other)); + assert!(!marked(), "the document closed"); + } +} diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index 01cedbcc02..f06d17e242 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -12,7 +12,8 @@ //! plug-in installation, parameters, input geometry and paints: the plug-in runs again only when //! one of them changes. Failures are cached too (the geometry is then drawn unchanged) and //! reported by [`last_error`]. The swatches and patterns a painted result names are checked -//! against the document each time it is used. +//! against the document each time it is used. While a document is drawn on screen, its first view +//! shares a time budget and stages without a result are deferred ([`crate::deferred`]). use std::collections::HashMap; use std::hash::{Hash, Hasher}; @@ -22,6 +23,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document}; use vectorcraft_geom::{FillRule, PathData, Rect}; +use crate::deferred::{Allowance, Reason, Stage}; use crate::objects::{decode, output_geometry, paint_lists}; use crate::painted::{self, Piece, Scope}; use crate::{Error, Kind, Limits, Result, registry}; @@ -69,6 +71,9 @@ pub struct Paints<'a> { /// The index in `appearance.items` of the fill or stroke whose own effects hold this one; /// `None`: one of the object's effects. pub item: Option, + /// The object and the effect's place in its list, which a deferred stage is listed by + /// ([`crate::deferred`]); `None`: not known, listed as object 0. + pub at: Option, } /// [`Paints`] as the plug-in is given them: the input object's `fills` and `strokes`, and @@ -151,7 +156,8 @@ impl Out { #[derive(Default)] struct Cache { - entries: HashMap)>, + /// Each result, or why the run gave none ([`Reason::Timeout`] or [`Reason::Failed`]). + entries: HashMap)>, /// The anchors of the entries' inputs and results ([`CACHE_ANCHORS`]). anchors: usize, } @@ -294,9 +300,10 @@ pub fn paints_output(id: &str) -> bool { /// For an effect that returns painted pieces, the geometry is every piece's path in order, and /// `None` when the swatches and patterns they name are refused as [`apply_painted`] refuses them. pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints, doc: Option<&Document>) -> Option { + let at = paints.at; let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?; if let Out::Pieces(pieces) = &out { - references_found(id, &plugin, pieces, doc)?; + references_found(id, &plugin, pieces, doc, at)?; } Some(out.geometry()) } @@ -318,9 +325,10 @@ pub fn apply_painted( paints: Paints, doc: Option<&Document>, ) -> Option>> { + let at = paints.at; let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?; let Out::Pieces(pieces) = out else { return None }; - references_found(id, &plugin, &pieces, doc)?; + references_found(id, &plugin, &pieces, doc, at)?; Some(match doc { Some(d) => painted::with_swatch_colors(pieces, d), None => pieces, @@ -329,11 +337,17 @@ pub fn apply_painted( /// `Some` when every swatch and pattern `pieces` name is in `doc` ([`painted::check_references`]), /// recording the outcome for [`last_error`] when there is a document. The document's swatches and -/// patterns can change while a result stays cached, so each use checks them. -fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Option<&Document>) -> Option<()> { +/// patterns can change while a result stays cached, so each use checks them. Inside a document's +/// view, a refusal defers stage `at` as failed. +fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Option<&Document>, at: Option) -> Option<()> { let checked = painted::check_references(pieces, doc); if doc.is_some() { note(id, plugin, Origin::References, checked.as_ref().map(|_| ())); + if checked.is_err() + && let Some(v) = crate::deferred::current() + { + v.defer(at.unwrap_or_default(), id, Reason::Failed, 0); + } } checked.ok() } @@ -341,12 +355,36 @@ fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Opt /// Runs plug-in `id` as [`apply`] says, or takes its result from the cache: the plug-in and what /// it gave. The launch marker names the plug-in during its first run in this process, and until /// every run that started while it ran has ended too ([`crate::safe_mode::loading`]). +/// +/// Inside a document's view ([`crate::deferred`]), a stage without a result is recorded as +/// deferred with the reason, and one with a result is no longer deferred. During the view's +/// budget a run takes at most what is left of it, none starts once it is spent, and a result +/// that comes back after it ran out is not used; neither is cached or reported by +/// [`last_error`]. After the first view, a stage deferred with the same input is not run again. fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints) -> Option<(Arc, Out)> { + let view = crate::deferred::current(); + let stage = paints.at.unwrap_or_default(); + if let Some(v) = &view { + v.visit(stage); + } + let defer = |reason, key| { + if let Some(v) = &view { + v.defer(stage, id, reason, key); + } + }; if crate::safe_mode::active() { + defer(Reason::SafeMode, 0); return None; } - let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Effect)?; - let resolved = Value::Object(plugin.manifest().resolve_params(params).ok()?); + let Some(plugin) = registry::get(id).filter(|p| p.manifest().kind == Kind::Effect) else { + defer(Reason::Missing, 0); + return None; + }; + let Ok(resolved) = plugin.manifest().resolve_params(params) else { + defer(Reason::Failed, 0); + return None; + }; + let resolved = Value::Object(resolved); let given = paints.given(); let key = Key { serial: plugin.serial(), @@ -357,14 +395,44 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR path: path.clone(), }; let h = key.hash64(); - if let Some((k, out)) = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().and_then(|c| c.entries.get(&h)) - && *k == key - { - return out.clone().map(|o| (plugin, o)); + let cached = CACHE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(|c| c.entries.get(&h)) + .filter(|(k, _)| *k == key) + .map(|(_, out)| out.clone()); + match cached { + // A result from the cache counts as a run that gave it. + Some(Ok(o)) => { + if let Some(v) = &view { + v.ran(stage, h); + } + return Some((plugin, o)); + } + // A refresh runs a stage that failed again. + Some(Err(reason)) if !view.as_ref().is_some_and(|v| v.retries(stage, h)) => { + defer(reason, h); + return None; + } + _ => {} } + let allowance = match &view { + Some(v) if v.holds(stage, h) => return None, + Some(v) => v.allowance(), + None => Allowance::Unlimited, + }; + let (wall_time_ms, until) = match allowance { + Allowance::Unlimited => (WALL_TIME_MS, None), + Allowance::Until { ms, until } => (ms.min(WALL_TIME_MS), Some(until)), + Allowance::Spent => { + defer(Reason::Budget, h); + return None; + } + }; let scope = paints.scope(); let guarded = begin_run(&plugin); - let r = run(&plugin, resolved, path, bounds, rule, given, scope); + let r = run(&plugin, resolved, path, (bounds, rule), given, scope, wall_time_ms); let cancelled = matches!(r, Err(Error::Cancelled)); if guarded { end_run(plugin.serial(), cancelled); @@ -373,11 +441,28 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR if cancelled { return None; } + let timed_out = matches!(&r, Err(Error::Limit(l)) if l == crate::host::TIME_BUDGET); + // A run the budget cut short, or whose result came after the budget ran out, says nothing + // about the plug-in either: the stage waits for a later run. + let late = until.is_some_and(|u| view.as_ref().is_some_and(|v| v.passed(u))); + if (timed_out && wall_time_ms < WALL_TIME_MS) || late { + defer(Reason::Budget, h); + return None; + } note(id, &plugin, Origin::Run, r.as_ref().map(|_| ())); - let out = r.ok(); - let size = weight(&key, out.as_ref()); + let out = r.map_err(|_| if timed_out { Reason::Timeout } else { Reason::Failed }); + match &out { + Ok(_) => { + if let Some(v) = &view { + v.ran(stage, h); + } + crate::deferred::resolved(h); + } + Err(reason) => defer(*reason, h), + } + let size = weight(&key, out.as_ref().ok()); if size > CACHE_ANCHORS / 4 { - return out.map(|o| (plugin, o)); + return out.ok().map(|o| (plugin, o)); } let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); let cache = cache.get_or_insert_with(Cache::default); @@ -385,15 +470,24 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR *cache = Cache::default(); } if let Some((old, old_out)) = cache.entries.insert(h, (key, out.clone())) { - cache.anchors = cache.anchors.saturating_sub(weight(&old, old_out.as_ref())); + cache.anchors = cache.anchors.saturating_sub(weight(&old, old_out.as_ref().ok())); } cache.anchors += size; - out.map(|o| (plugin, o)) + out.ok().map(|o| (plugin, o)) } -/// One run of `plugin` on `path`, with the object's paints as `given`: geometry, or for an effect -/// that declares `paintOutput` its pieces, checked for an effect in `scope`. -fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule, given: Given, scope: Scope) -> Result { +/// One run of `plugin` on `path` (reference box and fill rule `(bounds, rule)`), with the object's +/// paints as `given`, stopped after `wall_time_ms`: geometry, or for an effect that declares +/// `paintOutput` its pieces, checked for an effect in `scope`. +fn run( + plugin: &crate::Plugin, + mut params: Value, + path: &PathData, + (bounds, rule): (Rect, FillRule), + given: Given, + scope: Scope, + wall_time_ms: u64, +) -> Result { let b = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]); params["_context"] = json!({"mode": "effect", "bounds": b, "item": given.item}); let rule_name = match rule { @@ -404,7 +498,9 @@ fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, json!({"objects": [{"type": "path", "path": path, "fillRule": rule_name, "bounds": b, "fills": given.fills, "strokes": given.strokes}]}); let (input, params) = (serde_json::to_vec(&input), serde_json::to_vec(¶ms)); let (Ok(input), Ok(params)) = (input, params) else { return Err(Error::Params("can't encode the input".into())) }; - let limits = Limits { wall_time_ms: WALL_TIME_MS, ..plugin.limits().clone() }; + let limits = Limits { wall_time_ms, ..plugin.limits().clone() }; + #[cfg(test)] + tests::RUNS_STARTED.with(|n| n.set(n.get() + 1)); let output = plugin.run_limited(&input, ¶ms, &limits)?; if plugin.manifest().paint_output { return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?))); @@ -420,6 +516,11 @@ mod tests { use super::*; + thread_local! { + /// How many plug-in runs this thread started ([`run`]). + pub(super) static RUNS_STARTED: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + /// Fills and strokes come in paint order, and the item an effect sits on is counted among the /// fills or among the strokes. #[test] @@ -427,7 +528,7 @@ mod tests { let fill = |c| AppearanceItem::Fill(FillLayer::new(Paint::solid(c))); let stroke = |w| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), w)); let ap = Appearance { items: vec![fill(Color::WHITE), stroke(2.0), fill(Color::BLACK), stroke(5.0)], ..Appearance::default() }; - let given = |item| Paints { appearance: Some(&ap), item }.given(); + let given = |item| Paints { appearance: Some(&ap), item, at: None }.given(); let g = given(None); assert_eq!((g.fills.len(), g.strokes.len(), &g.item), (2, 2, &json!("object"))); assert_eq!(g.strokes.iter().map(|s| s["width"].clone()).collect::>(), [json!(2.0), json!(5.0)]); @@ -494,9 +595,141 @@ mod tests { assert!(last_error(ID).unwrap().contains("trapped")); assert!(draw(&short).is_none(), "from the cache, refused again"); assert!(last_error(ID).unwrap().contains("swatch")); + // Inside a document's view, the refused stage is deferred as failed, also from the cache. + let view = crate::deferred::Deferrals::with_clock(Arc::new(|| Some(0))); + let at = Stage { object: 3, effect: 1, item: None }; + let in_view = || { + view.view(|| { + apply_painted( + ID, + &json!({}), + &short, + Rect::new(0.0, 0.0, 1.0, 1.0), + FillRule::NonZero, + Paints { at: Some(at), ..Paints::default() }, + Some(&doc), + ) + }) + }; + assert!(in_view().is_none()); + let listed = || view.list().iter().map(|d| (d.stage, d.reason)).collect::>(); + assert_eq!(listed(), [(at, Reason::Failed)]); + view.first_view_done(); + assert!(in_view().is_none()); + assert_eq!(listed(), [(at, Reason::Failed)], "a later drawing leaves it listed"); registry::remove(ID); } + /// A clock that reads `step` milliseconds later each time it is read. + fn stepping(step: u64) -> crate::deferred::Clock { + let t = Arc::new(std::sync::atomic::AtomicU64::new(0)); + Arc::new(move || Some(t.fetch_add(step, std::sync::atomic::Ordering::Relaxed))) + } + + /// A line of `n` points: a distinct input for each `n`. + fn line(n: usize) -> PathData { + PathData::single(SubPath::polyline(&(0..n).map(|i| Point::new(i as f64, 0.0)).collect::>(), false)) + } + + /// Plug-in `id` drawn on `path` as effect `effect` of object 1: whether it gave a result. + fn drawn(id: &str, path: &PathData, effect: usize) -> bool { + let at = Some(Stage { object: 1, effect, item: None }); + apply(id, &json!({}), path, Rect::new(0.0, 0.0, 1.0, 1.0), FillRule::NonZero, Paints { at, ..Paints::default() }, None).is_some() + } + + /// The effects of a first view share its budget: once it is spent no run starts, and a result + /// that comes back after it ran out is not used. Later drawings leave the deferred stages + /// deferred; a drawing outside the view (an export) runs them, and the view then uses the + /// result. + #[test] + fn the_first_view_shares_the_budget_and_defers_the_rest() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.budget"; + let src = crate::wat::returning(&crate::wat::manifest(ID, "effect", "{}"), r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + // Each run takes 900 ms by this clock (it is read before and after each run). + let view = crate::deferred::Deferrals::with_clock(stepping(450)); + let ran = view.view(|| (0..4).map(|i| drawn(ID, &line(i + 2), i)).collect::>()); + assert_eq!(ran, [true, true, false, false], "the third result comes back at 2,250 ms, the fourth doesn't start"); + let listed = view.list().iter().map(|d| (d.stage.effect, d.reason, d.plugin.clone())).collect::>(); + assert_eq!(listed, [(2, Reason::Budget, ID.to_string()), (3, Reason::Budget, ID.to_string())]); + view.first_view_done(); + assert_eq!(view.take_report(), Some(2)); + assert!(!view.view(|| drawn(ID, &line(4), 2)), "a later drawing leaves it deferred"); + assert!(view.view(|| drawn(ID, &line(9), 3)), "an edit to its input runs it"); + assert_eq!(view.list().len(), 1); + assert!(drawn(ID, &line(4), 2), "outside the view it runs"); + assert_eq!(view.list().len(), 1, "until the view draws it again"); + assert!(view.view(|| drawn(ID, &line(9), 2)), "an edit to an input whose result is cached"); + assert!(view.list().is_empty(), "the record of the input it no longer has goes"); + assert!(view.view(|| drawn(ID, &line(4), 2)), "from the cache"); + assert!(view.list().is_empty()); + registry::remove(ID); + } + + /// A stage that fails, or whose plug-in is missing, is deferred with that reason, from a run or + /// from the cache; a failure is cached and reported as before. + #[test] + fn failed_and_missing_stages_are_deferred_with_their_reason() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.deferfailed"; + // Runs to its instruction budget. + let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 1_000_000_000, r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + let view = crate::deferred::Deferrals::with_clock(stepping(1)); + assert!(!view.view(|| drawn(ID, &line(2), 0))); + assert!(last_error(ID).is_some()); + assert!(!view.view(|| drawn("test.effect.notinstalled", &line(2), 1))); + let reasons = |v: &crate::deferred::Deferrals| v.list().iter().map(|d| d.reason).collect::>(); + assert_eq!(reasons(&view), [Reason::Failed, Reason::Missing]); + let other = crate::deferred::Deferrals::with_clock(stepping(1)); + assert!(!other.view(|| drawn(ID, &line(2), 0))); + assert_eq!(reasons(&other), [Reason::Failed], "from the cache, in another document"); + // A refresh runs a stage whose failure is cached again, once, and later drawings take the + // failure from the cache. + other.first_view_done(); + let runs = || RUNS_STARTED.with(std::cell::Cell::get); + let before = runs(); + let counts = other.refresh(None, |_| { + other.view(|| (drawn(ID, &line(2), 0), drawn(ID, &line(2), 0))); + vec![] + }); + assert_eq!((counts.failed, runs() - before), (1, 1)); + assert!(!other.view(|| drawn(ID, &line(2), 0))); + assert_eq!((reasons(&other), runs() - before), (vec![Reason::Failed], 1)); + registry::remove(ID); + } + + /// A run the budget cuts short is deferred for want of time: it is not cached, and the plug-in + /// reports no error. + #[test] + fn a_run_the_budget_cuts_short_is_deferred_for_time() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.cutshort"; + const FAST: &str = "test.effect.cutshort.fast"; + let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 10_000_000, r#"{"objects":[]}"#); + let limits = Limits { fuel_base: 1_000_000_000, ..Limits::default() }; + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), limits).unwrap()); + let fast = crate::wat::returning(&crate::wat::manifest(FAST, "effect", "{}"), r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&fast).unwrap(), Limits::default()).unwrap()); + // The first run starts the budget at 0 ms and ends at 1,999: the next has 1 ms left, and + // ten million steps take longer. + let reads = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let clock: crate::deferred::Clock = + Arc::new(move || Some(if reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { 0 } else { 1_999 })); + let view = crate::deferred::Deferrals::with_clock(clock); + assert!(view.view(|| drawn(FAST, &line(2), 0))); + assert!(!view.view(|| drawn(ID, &line(2), 1))); + assert_eq!(view.list().iter().map(|d| (d.stage.effect, d.reason)).collect::>(), [(1, Reason::Budget)]); + assert_eq!(last_error(ID), None); + assert!(drawn(ID, &line(2), 1), "not cached: outside the view it runs to the end"); + registry::remove(ID); + registry::remove(FAST); + } + /// A first run that is cancelled leaves the next run to be the first: the launch marker names /// the plug-in during that one. #[test] diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 182456aa71..474234880b 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -318,6 +318,9 @@ pub struct Report { pub truncated: bool, } +/// The limit a run past its wall-clock deadline exceeded ([`Error::Limit`]). +pub(crate) const TIME_BUDGET: &str = "time budget"; + /// When a run must stop (native: a wall-clock deadline). #[derive(Clone, Copy)] pub(crate) struct Deadline { @@ -344,7 +347,7 @@ impl Deadline { } pub(crate) fn check(&self) -> Result<()> { - if self.passed() { Err(Error::Limit("time budget".into())) } else { Ok(()) } + if self.passed() { Err(Error::Limit(TIME_BUDGET.into())) } else { Ok(()) } } } diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b4faf543db..63f879c2f9 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -34,6 +34,7 @@ //! runs through `vc_run` with the command's id in `_context`. #![forbid(unsafe_code)] +pub mod deferred; pub mod dialog; pub mod effect; pub mod export; diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 4092de4e42..38b790ecc4 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -123,9 +123,9 @@ pub struct CacheKey { /// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since. pub placed: u64, /// The plug-in revision ([`vectorcraft_render::effects::plugin_revision`]) of the last plug-in - /// install or removal after which the document drew a plug-in effect - /// ([`vectorcraft_render::draws_plugin_effects`]): a frame drawn before it draws those effects - /// as the plug-ins installed then did. 0 until then. + /// install or removal, or of the last time deferred plug-in effect stages gave results, after + /// which the document drew a plug-in effect ([`vectorcraft_render::draws_plugin_effects`]): a + /// frame drawn before it draws those effects as the plug-ins installed then did. 0 until then. pub plugins: u64, /// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown /// with hard edges. None: the art is rendered for the screen. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 63be246dac..56f121ad6d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -293,6 +293,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let painter = ui.painter_at(rect); let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); + let effects = st.plugin_effects.clone(); let mask_view = st.shown_mask(); paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); @@ -349,8 +350,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if wait.is_none() && (!same_frame || app.canvas.texture.is_none() || settle) { let (w, h, view) = frame_view(pixel, (w, h), &v, ppp); let opts = frame_options(app, &key, mask_view, smooth_images); - draw_frame(app, ui, Frame { key: &key, doc: &doc, size: (w, h), view, opts, pixel }); + draw_frame(app, ui, Frame { key: &key, doc: &doc, effects: &effects, size: (w, h), view, opts, pixel }); } + report_deferred(app, &effects); // The status bar reports each image that a renderer (this thread's or the worker's) could not // decode, once per image in the process. let undecoded = vectorcraft_render::newly_undecodable(doc.images.values()); @@ -606,7 +608,7 @@ fn cache_key( /// [`CacheKey::plugins`] of document `st`, one of the documents open in `session`. `keys` holds each /// document's value and the plug-in revision it was checked at, so a document is looked through only -/// once after each plug-in install or removal. +/// once after each change of the plug-in revision. fn plugin_key( keys: &mut std::collections::HashMap, session: &vectorcraft_engine::Session, @@ -624,6 +626,19 @@ fn plugin_key( } } +/// Once the first view of a document has been drawn, the status bar says how many plug-in effect +/// stages it left deferred, if any. +fn report_deferred(app: &mut VectorcraftApp, effects: &vectorcraft_plugins::deferred::Deferrals) { + if let Some(n) = effects.take_report().filter(|n| *n > 0) { + app.status(crate::i18n::msg_n( + n as u64, + "Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.", + "Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them.", + &[], + )); + } +} + /// Start the render worker, and upload the frame it finished. fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { if !app.canvas.worker_started { @@ -647,6 +662,9 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: return; } upload(app, ctx, done.img, done.key.pixel.is_some()); + if let Some(d) = app.session.documents().iter().find(|d| d.uid as usize == done.key.doc) { + d.plugin_effects.first_view_done(); + } app.canvas.key = Some(done.key); app.canvas.shown = Some((done.doc, done.opts)); app.perf.render_ms = done.ms; @@ -729,6 +747,8 @@ fn frame_options( struct Frame<'a> { key: &'a CacheKey, doc: &'a std::sync::Arc, + /// The document's deferred plug-in effect stages: the frame renders inside their view. + effects: &'a vectorcraft_plugins::deferred::Deferrals, size: (u32, u32), view: Affine, opts: vectorcraft_render::RenderOptions, @@ -740,7 +760,7 @@ struct Frame<'a> { pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { - let Frame { key, doc, size: (w, h), view, opts, pixel } = frame; + let Frame { key, doc, effects, size: (w, h), view, opts, pixel } = frame; // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this @@ -768,7 +788,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.renderer.let_go_of_measured(); } if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let part = app.canvas.renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts); + let renderer = &mut app.canvas.renderer; + let part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts)); let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); @@ -790,6 +811,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { view, opts, scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: effects.clone(), may_copy, may_keep: true, }); @@ -801,7 +823,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } _ => { let t0 = now_ms(); - let img = app.canvas.renderer.render(doc, w, h, view, &opts); + let renderer = &mut app.canvas.renderer; + let img = effects.view(|| renderer.render(doc, w, h, view, &opts)); + effects.first_view_done(); upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); diff --git a/crates/ui-egui/src/canvas/fill.rs b/crates/ui-egui/src/canvas/fill.rs index 60d8b00754..8eda1db219 100644 --- a/crates/ui-egui/src/canvas/fill.rs +++ b/crates/ui-egui/src/canvas/fill.rs @@ -95,6 +95,7 @@ pub(super) fn fill_uncovered( let (_, _, view) = fill_view(&done.key); app.canvas.fill = Some(Fill { key: done.key, view, size: (fw, fh), tex }); } + let effects = app.session.documents().iter().find(|d| d.uid as usize == key.doc).map(|d| d.plugin_effects.clone()).unwrap_or_default(); let Some(worker) = app.canvas.fill_worker.as_mut().filter(|_| !gaps.is_empty()) else { return }; if !app.canvas.fill.as_ref().is_some_and(|f| covers(&f.key)) && !worker.pending.as_ref().is_some_and(covers) { let (w, h, view) = fill_view(key); @@ -106,6 +107,7 @@ pub(super) fn fill_uncovered( view, opts, scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects, may_copy: false, may_keep: false, }); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a9ef2c228d..587b4ced15 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2395,6 +2395,52 @@ fn undecodable_images_are_marked_and_reported_once() { assert_eq!(app.ui.status, "", "said once"); } +/// The plug-in effects a document's first view leaves out past its budget are reported in the +/// status bar once, in the singular or the plural, and Effect › Refresh Deferred Effects is +/// enabled until it has run them. +#[test] +fn the_first_view_reports_the_plug_in_effects_it_deferred() { + use std::sync::atomic::{AtomicU64, Ordering}; + use vectorcraft_plugins::wat as tpl; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread + let module = tpl::module(&tpl::manifest("test.ui.deferred", "effect", "{}"), tpl::ECHO, "", 1); + app.session.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(module).unwrap())})).unwrap(); + // Each reading of the clock is 3 s later: the first run's result comes back after the budget, + // and no later run starts. + let step = std::sync::Arc::new(AtomicU64::new(3_000)); + let ctx = egui::Context::default(); + for (count, said) in [ + (2, "Opened with 2 plug-in effects deferred. Effect › Refresh Deferred Effects runs them."), + (1, "Opened with 1 plug-in effect deferred. Effect › Refresh Deferred Effects runs it."), + ] { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // Art the plug-in has not been given before: a result it gave is kept and drawn at once. + for i in 0..count { + let x = 31.0 + 97.0 * f64::from(i) + 13.0 * f64::from(count); + let id = app.session.execute("shape.rectangle", &json!({"x": x, "y": 47, "width": 23, "height": 29})).unwrap()["id"].clone(); + app.session.execute("effect.apply", &json!({"ids": [id], "effect": "plugin.test.ui.deferred"})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + let (now, by) = (std::sync::Arc::new(AtomicU64::new(0)), step.clone()); + let clock: vectorcraft_plugins::deferred::Clock = + std::sync::Arc::new(move || Some(now.fetch_add(by.load(Ordering::Relaxed), Ordering::Relaxed))); + app.session.doc_mut().unwrap().plugin_effects = vectorcraft_plugins::deferred::Deferrals::with_clock(clock); + step.store(3_000, Ordering::Relaxed); + app.status(""); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.status, said); + assert!(crate::menus::enabled(&app, "effect.refreshDeferred")); + app.status(""); + app.session.doc_mut().unwrap().revision += 1; + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.status, "", "said once"); + step.store(0, Ordering::Relaxed); + app.session.execute("effect.refreshDeferred", &json!({})).unwrap(); + assert!(!crate::menus::enabled(&app, "effect.refreshDeferred"), "nothing is left deferred"); + } +} + /// A drag of an object with raster effects (#1257): the drag's frames render while /// interacting and draw the object's drop shadow and filtered content from the rasters of the /// frame before; the frame after the drag renders without `interacting`, on the render worker, @@ -10687,6 +10733,7 @@ fn pan_job(doc: &std::sync::Arc, key: &CacheKey, (dx, view: Affine::translate((dx, dy)), opts: vectorcraft_render::RenderOptions::default(), scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: Default::default(), may_copy: true, may_keep: true, } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ee32cee33f..6e7750058d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6504,3 +6504,7 @@ breakText Glyphs Глифи Ended by an internal fault Прекратен поради вътрешна грешка {ms} ms, {calls} host calls {ms} ms, {calls} извиквания към хоста {dropped} earlier lines dropped, {cut} lines cut {dropped} по-ранни реда премахнати, {cut} реда съкратени + +# Deferred plug-in effects + Refresh Deferred Effects Обновяване на отложените ефекти + Deferred Effects Отложени ефекти diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0970a70929..b5d50e03fa 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6555,3 +6555,7 @@ shape Open Otvoren Ended by an internal fault Završeno zbog interne greške {ms} ms, {calls} host calls {ms} ms, {calls} poziva hosta {dropped} earlier lines dropped, {cut} lines cut {dropped} ranijih redova uklonjeno, {cut} redova skraćeno + +# Deferred plug-in effects + Refresh Deferred Effects Osvježi odgođene efekte + Deferred Effects Odgođeni efekti diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 84b6833c4e..fad1dc153b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6759,3 +6759,9 @@ breakText Glyphs Glifs {ms} ms, {calls} host calls {ms} ms, {calls} crides a l’amfitrió {dropped} earlier lines dropped, {cut} lines cut {dropped} línies anteriors descartades, {cut} línies tallades @msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualitza els efectes ajornats + Deferred Effects Efectes ajornats +@msg no plug-in effect is deferred no hi ha cap efecte de complement ajornat +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. S’ha obert amb {n} efecte de complement ajornat. Efecte › Actualitza els efectes ajornats l’executa.|S’ha obert amb {n} efectes de complement ajornats. Efecte › Actualitza els efectes ajornats els executa. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 733a3e813b..11617a306f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6778,3 +6778,9 @@ breakText Glyphs Glyfy {ms} ms, {calls} host calls {ms} ms, {calls} volání hostitele {dropped} earlier lines dropped, {cut} lines cut {dropped} starších řádků zahozeno, {cut} řádků zkráceno @msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last` + +# Deferred plug-in effects + Refresh Deferred Effects Obnovit odložené efekty + Deferred Effects Odložené efekty +@msg no plug-in effect is deferred žádný efekt zásuvného modulu není odložen +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otevřeno s {n} odloženým efektem zásuvného modulu. Efekt › Obnovit odložené efekty jej spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d1871b2ed9..90325507fd 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6518,3 +6518,7 @@ breakText Glyphs Glyffer Ended by an internal fault Afsluttet af en intern fejl {ms} ms, {calls} host calls {ms} ms, {calls} værtskald {dropped} earlier lines dropped, {cut} lines cut {dropped} tidligere linjer fjernet, {cut} linjer afkortet + +# Deferred plug-in effects + Refresh Deferred Effects Opdatér udskudte effekter + Deferred Effects Udskudte effekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8c75b25b6b..4931ef2085 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6365,3 +6365,9 @@ breakText Glyphs Glyphen {ms} ms, {calls} host calls {ms} ms, {calls} Host-Aufrufe {dropped} earlier lines dropped, {cut} lines cut {dropped} ältere Zeilen verworfen, {cut} Zeilen gekürzt @msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last` + +# Deferred plug-in effects + Refresh Deferred Effects Zurückgestellte Effekte aktualisieren + Deferred Effects Zurückgestellte Effekte +@msg no plug-in effect is deferred kein Plug-in-Effekt ist zurückgestellt +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Mit {n} zurückgestelltem Plug-in-Effekt geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt ihn aus.|Mit {n} zurückgestellten Plug-in-Effekten geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt sie aus. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7813ee6cf8..53729616f6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6730,3 +6730,9 @@ breakText Glyphs Γλύφοι {ms} ms, {calls} host calls {ms} ms, {calls} κλήσεις προς το κεντρικό σύστημα {dropped} earlier lines dropped, {cut} lines cut {dropped} παλαιότερες γραμμές απορρίφθηκαν, {cut} γραμμές περικόπηκαν @msg `first` and `last` must be numbers of lines the console holds, first before last Τα `first` και `last` πρέπει να είναι αριθμοί γραμμών που κρατά η κονσόλα, το `first` πριν από το `last` + +# Deferred plug-in effects + Refresh Deferred Effects Ανανέωση εφέ σε αναμονή + Deferred Effects Εφέ σε αναμονή +@msg no plug-in effect is deferred κανένα εφέ προσθέτου δεν είναι σε αναμονή +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Άνοιξε με {n} εφέ προσθέτου σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή το εκτελεί.|Άνοιξε με {n} εφέ προσθέτων σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή τα εκτελεί. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d8bcecbc6e..e70daac853 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6721,3 +6721,9 @@ breakText Glyphs Glifos {ms} ms, {calls} host calls {ms} ms, {calls} llamadas al host {dropped} earlier lines dropped, {cut} lines cut {dropped} líneas anteriores descartadas, {cut} líneas recortadas @msg `first` and `last` must be numbers of lines the console holds, first before last `first` y `last` deben ser números de líneas que la consola conserva, `first` antes que `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualizar efectos aplazados + Deferred Effects Efectos aplazados +@msg no plug-in effect is deferred no hay ningún efecto de plugin aplazado +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Se abrió con {n} efecto de plugin aplazado. Efecto › Actualizar efectos aplazados lo ejecuta.|Se abrió con {n} efectos de plugin aplazados. Efecto › Actualizar efectos aplazados los ejecuta. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d3b9fb3260..3969a4167e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6813,3 +6813,9 @@ breakText Glyphs Merkit {ms} ms, {calls} host calls {ms} ms, {calls} isäntäkutsua {dropped} earlier lines dropped, {cut} lines cut {dropped} aiempaa riviä poistettu, {cut} riviä katkaistu @msg `first` and `last` must be numbers of lines the console holds, first before last `first` ja `last` on oltava konsolin säilyttämien rivien numeroita, `first` ennen arvoa `last` + +# Deferred plug-in effects + Refresh Deferred Effects Päivitä lykätyt tehosteet + Deferred Effects Lykätyt tehosteet +@msg no plug-in effect is deferred yhtään laajennustehostetta ei ole lykätty +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Avattiin, ja {n} laajennustehoste lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa sen.|Avattiin, ja {n} laajennustehostetta lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa ne. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6db5062046..8ffa30e492 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6773,3 +6773,9 @@ breakText Glyphs Glyphes {ms} ms, {calls} host calls {ms} ms, {calls} appels à l’hôte {dropped} earlier lines dropped, {cut} lines cut {dropped} lignes antérieures supprimées, {cut} lignes coupées @msg `first` and `last` must be numbers of lines the console holds, first before last `first` et `last` doivent être des numéros de lignes que la console contient, `first` avant `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualiser les effets différés + Deferred Effects Effets différés +@msg no plug-in effect is deferred aucun effet de plug-in n’est différé +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Ouvert avec {n} effet de plug-in différé. Effet › Actualiser les effets différés l’exécute.|Ouvert avec {n} effets de plug-in différés. Effet › Actualiser les effets différés les exécute. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3fa2269085..5e60e4a77c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8219,3 +8219,9 @@ theme Appearance अपीयरेंस {ms} ms, {calls} host calls {ms} ms, {calls} होस्ट कॉल {dropped} earlier lines dropped, {cut} lines cut {dropped} पुरानी पंक्तियाँ हटाई गईं, {cut} पंक्तियाँ काटी गईं @msg `first` and `last` must be numbers of lines the console holds, first before last `first` और `last` कंसोल में रखी पंक्तियों की संख्याएँ होनी चाहिए, `first` पहले और `last` बाद में + +# Deferred plug-in effects + Refresh Deferred Effects स्थगित इफ़ेक्ट्स रिफ्रेश करें + Deferred Effects स्थगित इफ़ेक्ट्स +@msg no plug-in effect is deferred कोई प्लग-इन इफ़ेक्ट स्थगित नहीं है +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} प्लग-इन इफ़ेक्ट स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इसे चलाता है।|{n} प्लग-इन इफ़ेक्ट्स स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इन्हें चलाता है। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27e22d0ad0..854403c8ab 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6762,3 +6762,9 @@ breakText Glyphs Glifák {ms} ms, {calls} host calls {ms} ms, {calls} gazdahívás {dropped} earlier lines dropped, {cut} lines cut {dropped} korábbi sor elvetve, {cut} sor levágva @msg `first` and `last` must be numbers of lines the console holds, first before last A `first` és a `last` a konzolban tárolt sorok számai legyenek, a `first` a `last` előtt + +# Deferred plug-in effects + Refresh Deferred Effects Elhalasztott effektusok frissítése + Deferred Effects Elhalasztott effektusok +@msg no plug-in effect is deferred nincs elhalasztott bővítményeffektus +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Megnyitva, elhalasztott bővítményeffektusok: {n}. Az Effektus › Elhalasztott effektusok frissítése futtatja őket. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c4e97482a8..5148ae16ec 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6518,3 +6518,7 @@ breakText Glyphs Glif Ended by an internal fault Berakhir karena galat internal {ms} ms, {calls} host calls {ms} ms, {calls} panggilan host {dropped} earlier lines dropped, {cut} lines cut {dropped} baris lama dibuang, {cut} baris dipotong + +# Deferred plug-in effects + Refresh Deferred Effects Segarkan efek yang ditunda + Deferred Effects Efek yang ditunda diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 987505a43c..5e33fa9a05 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6399,3 +6399,9 @@ breakText Glyphs Glifi {ms} ms, {calls} host calls {ms} ms, {calls} chiamate all'host {dropped} earlier lines dropped, {cut} lines cut {dropped} righe precedenti scartate, {cut} righe tagliate @msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devono essere numeri di righe presenti nella console, `first` prima di `last` + +# Deferred plug-in effects + Refresh Deferred Effects Aggiorna effetti rimandati + Deferred Effects Effetti rimandati +@msg no plug-in effect is deferred nessun effetto plug-in è rimandato +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aperto con {n} effetto plug-in rimandato. Effetto › Aggiorna effetti rimandati lo esegue.|Aperto con {n} effetti plug-in rimandati. Effetto › Aggiorna effetti rimandati li esegue. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d3c0b6603d..2791e7b833 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6464,3 +6464,9 @@ breakText Glyphs 字形 {ms} ms, {calls} host calls {ms} ms、ホスト呼び出し {calls} 回 {dropped} earlier lines dropped, {cut} lines cut 古い行 {dropped} 行を破棄、{cut} 行を切り詰め @msg `first` and `last` must be numbers of lines the console holds, first before last `first` と `last` には、コンソールが保持している行の番号を、`first` が `last` より前になるよう指定してください + +# Deferred plug-in effects + Refresh Deferred Effects 保留中の効果を更新 + Deferred Effects 保留中の効果 +@msg no plug-in effect is deferred 保留中のプラグイン効果はありません +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. プラグイン効果を {n} 件保留して開きました。「効果 › 保留中の効果を更新」で実行します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5a05ccec34..046d43e11c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6839,3 +6839,9 @@ font-script Japanese იაპონური {ms} ms, {calls} host calls {ms} ms, ჰოსტის {calls} გამოძახება {dropped} earlier lines dropped, {cut} lines cut {dropped} ძველი სტრიქონი წაიშალა, {cut} სტრიქონი შემოკლდა @msg `first` and `last` must be numbers of lines the console holds, first before last `first` და `last` უნდა იყოს კონსოლში შენახული სტრიქონების ნომრები და `first` უნდა იყოს `last`-ზე წინ + +# Deferred plug-in effects + Refresh Deferred Effects გადადებული ეფექტების განახლება + Deferred Effects გადადებული ეფექტები +@msg no plug-in effect is deferred პლაგინის ეფექტი არ არის გადადებული +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. გაიხსნა, გადადებული პლაგინის ეფექტები: {n}. ეფექტი › გადადებული ეფექტების განახლება მათ გაუშვებს. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b0fc26d1fe..f979865be2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6360,3 +6360,9 @@ breakText Glyphs 글리프 {ms} ms, {calls} host calls {ms} ms, 호스트 호출 {calls}회 {dropped} earlier lines dropped, {cut} lines cut 이전 줄 {dropped}개 삭제됨, 줄 {cut}개 잘림 @msg `first` and `last` must be numbers of lines the console holds, first before last `first`와 `last`는 콘솔에 있는 줄 번호여야 하며 `first`가 `last`보다 앞서야 합니다 + +# Deferred plug-in effects + Refresh Deferred Effects 보류된 효과 새로 고침 + Deferred Effects 보류된 효과 +@msg no plug-in effect is deferred 보류된 플러그인 효과가 없습니다 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 플러그인 효과 {n}개를 보류하고 열었습니다. 효과 › 보류된 효과 새로 고침으로 실행합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c30a50e71d..5b429c0883 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6569,3 +6569,7 @@ breakText Glyphs Glyphs Ended by an internal fault Beëindigd door een interne fout {ms} ms, {calls} host calls {ms} ms, {calls} host-aanroepen {dropped} earlier lines dropped, {cut} lines cut {dropped} eerdere regels verwijderd, {cut} regels ingekort + +# Deferred plug-in effects + Refresh Deferred Effects Uitgestelde effecten vernieuwen + Deferred Effects Uitgestelde effecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8450cb6540..cfcf8767df 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6634,3 +6634,9 @@ breakText Glyphs Glify {ms} ms, {calls} host calls {ms} ms, wywołania hosta: {calls} {dropped} earlier lines dropped, {cut} lines cut Odrzucone wcześniejsze wiersze: {dropped}, skrócone wiersze: {cut} @msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` muszą być numerami wierszy przechowywanych w konsoli, `first` przed `last` + +# Deferred plug-in effects + Refresh Deferred Effects Odśwież odroczone efekty + Deferred Effects Odroczone efekty +@msg no plug-in effect is deferred żaden efekt wtyczki nie jest odroczony +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otwarto z {n} odroczonym efektem wtyczki. Efekt › Odśwież odroczone efekty go uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00d9a89484..32606233f2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6851,3 +6851,9 @@ swatch Yellow Green Verde-amarelado {ms} ms, {calls} host calls {ms} ms, {calls} chamadas ao host {dropped} earlier lines dropped, {cut} lines cut {dropped} linhas anteriores descartadas, {cut} linhas cortadas @msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devem ser números de linhas que o console mantém, `first` antes de `last` + +# Deferred plug-in effects + Refresh Deferred Effects Atualizar Efeitos Adiados + Deferred Effects Efeitos Adiados +@msg no plug-in effect is deferred nenhum efeito de plug-in está adiado +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aberto com {n} efeito de plug-in adiado. Efeito › Atualizar Efeitos Adiados o executa.|Aberto com {n} efeitos de plug-in adiados. Efeito › Atualizar Efeitos Adiados os executa. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 24a6c74d5b..94f6b36b04 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6867,3 +6867,9 @@ shape Open Открытый {ms} ms, {calls} host calls {ms} мс, вызовов хоста: {calls} {dropped} earlier lines dropped, {cut} lines cut Отброшено прежних строк: {dropped}, обрезано строк: {cut} @msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` должны быть номерами строк, которые хранит консоль, причём `first` не позже `last` + +# Deferred plug-in effects + Refresh Deferred Effects Обновить отложенные эффекты + Deferred Effects Отложенные эффекты +@msg no plug-in effect is deferred нет отложенных эффектов модулей +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Открыто с {n} отложенным эффектом модуля. Эффект › Обновить отложенные эффекты выполнит его.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c038612c18..232b13f9b0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8263,3 +8263,9 @@ digits Hindi Hindi {ms} ms, {calls} host calls {ms} ms, {calls} värdanrop {dropped} earlier lines dropped, {cut} lines cut {dropped} tidigare rader borttagna, {cut} rader avkortade @msg `first` and `last` must be numbers of lines the console holds, first before last `first` och `last` måste vara nummer på rader som konsolen har kvar, `first` före `last` + +# Deferred plug-in effects + Refresh Deferred Effects Uppdatera uppskjutna effekter + Deferred Effects Uppskjutna effekter +@msg no plug-in effect is deferred ingen plugineffekt är uppskjuten +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Öppnades med {n} uppskjuten plugineffekt. Effekt › Uppdatera uppskjutna effekter kör den.|Öppnades med {n} uppskjutna plugineffekter. Effekt › Uppdatera uppskjutna effekter kör dem. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 282990771a..bda6a433a4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6734,3 +6734,9 @@ breakText Glyphs Glifler {ms} ms, {calls} host calls {ms} ms, {calls} ana bilgisayar çağrısı {dropped} earlier lines dropped, {cut} lines cut {dropped} eski satır atıldı, {cut} satır kesildi @msg `first` and `last` must be numbers of lines the console holds, first before last `first` ve `last`, konsolun tuttuğu satırların numaraları olmalı ve `first`, `last` değerinden önce gelmeli + +# Deferred plug-in effects + Refresh Deferred Effects Ertelenen Efektleri Yenile + Deferred Effects Ertelenen Efektler +@msg no plug-in effect is deferred ertelenen eklenti efekti yok +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} eklenti efekti ertelenerek açıldı. Efekt › Ertelenen Efektleri Yenile bunları çalıştırır. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 88bcb4702a..3f1b2edefc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6379,3 +6379,9 @@ breakText Glyphs Гліфи {ms} ms, {calls} host calls {ms} мс, викликів хоста: {calls} {dropped} earlier lines dropped, {cut} lines cut Відкинуто попередніх рядків: {dropped}, обрізано рядків: {cut} @msg `first` and `last` must be numbers of lines the console holds, first before last `first` і `last` мають бути номерами рядків, які зберігає консоль, причому `first` не пізніше `last` + +# Deferred plug-in effects + Refresh Deferred Effects Оновити відкладені ефекти + Deferred Effects Відкладені ефекти +@msg no plug-in effect is deferred немає відкладених ефектів модулів +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Відкрито з {n} відкладеним ефектом модуля. Ефект › Оновити відкладені ефекти виконає його.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 90c292bc92..f7c86e4eff 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6380,3 +6380,9 @@ breakText Glyphs Glyph {ms} ms, {calls} host calls {ms} ms, {calls} lệnh gọi máy chủ {dropped} earlier lines dropped, {cut} lines cut Đã bỏ {dropped} dòng cũ, đã cắt {cut} dòng @msg `first` and `last` must be numbers of lines the console holds, first before last `first` và `last` phải là số thứ tự của các dòng mà bảng điều khiển đang giữ, `first` đứng trước `last` + +# Deferred plug-in effects + Refresh Deferred Effects Làm mới hiệu ứng bị hoãn + Deferred Effects Hiệu ứng bị hoãn +@msg no plug-in effect is deferred không có hiệu ứng plug-in nào bị hoãn +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Đã mở với {n} hiệu ứng plug-in bị hoãn. Hiệu ứng › Làm mới hiệu ứng bị hoãn sẽ chạy chúng. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 77578eec12..f7e5247aea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6616,3 +6616,9 @@ breakText Glyphs 字形 {ms} ms, {calls} host calls {ms} 毫秒,宿主调用 {calls} 次 {dropped} earlier lines dropped, {cut} lines cut 已丢弃 {dropped} 行较早内容,已截断 {cut} 行 @msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必须是控制台保留的行号,且 `first` 不能在 `last` 之后 + +# Deferred plug-in effects + Refresh Deferred Effects 刷新延迟的效果 + Deferred Effects 延迟的效果 +@msg no plug-in effect is deferred 没有延迟的增效工具效果 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 打开时延迟了 {n} 个增效工具效果。效果 › 刷新延迟的效果可运行它们。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bdec63590f..66d744f10f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6414,3 +6414,9 @@ breakText Glyphs 字符 {ms} ms, {calls} host calls {ms} 毫秒,主機呼叫 {calls} 次 {dropped} earlier lines dropped, {cut} lines cut 已捨棄 {dropped} 行較早內容,已截斷 {cut} 行 @msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必須是主控台保留的行號,且 `first` 不能在 `last` 之後 + +# Deferred plug-in effects + Refresh Deferred Effects 重新整理延後的效果 + Deferred Effects 延後的效果 +@msg no plug-in effect is deferred 沒有延後的增效模組效果 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 開啟時延後了 {n} 個增效模組效果。效果 › 重新整理延後的效果可執行它們。 diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 9e8a7ac650..469c40e7c7 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -136,6 +136,7 @@ pub(super) fn effect_menu() -> Vec { c("Last Effect…", "effect.last"), Sep, c("Document Raster Effects Settings…", "document.rasterEffectsSettings"), + c("Refresh Deferred Effects", "effect.refreshDeferred"), Sep, Item::Header("Vector Effects"), ]; diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index bf764e0e4b..40478e36ed 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -24,6 +24,9 @@ pub struct Job { /// The automation roots in force where the job was made: the render reads linked files under /// them, as it would on that thread. pub scope: ScopeHandle, + /// The document's deferred live-effect plug-in stages and first-view budget: the render runs + /// inside their view ([`vectorcraft_plugins::deferred::Deferrals::view`]). + pub effects: vectorcraft_plugins::deferred::Deferrals, /// The render may copy pixels from the worker's last frame ([`crate::canvas::render_job`]). /// Off: it renders the whole frame. pub may_copy: bool, @@ -71,7 +74,7 @@ impl Worker { job = newer; } let t0 = crate::now_ms(); - let frame = job.scope.clone().run(|| crate::canvas::render_job(&mut r, &mut kept, &job)); + let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job))); let ms = crate::now_ms() - t0; let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }; if done_tx.send(done).is_err() { diff --git a/docs/mcp.md b/docs/mcp.md index 19f16205cd..94a29ad568 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7134,7 +7134,26 @@ id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearanc `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them as ordinary paths with those paints; a result it refuses is drawn as if the effect weren't there, and `plugin.info`'s -`lastError` names the plug-in and the refused field. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): +`lastError` names the plug-in and the refused field. While the app draws a document on screen, the live-effect plug-ins +of its first view share a 2,000 ms budget (VectorCraft's own value), and each run also keeps to its own 5,000 ms limit: +once the budget is spent no run starts, and a result that comes back after it is not used. A stage left out for want +of time, or one that times out, fails or has no plug-in, draws its input art unchanged and is deferred; the status bar +then says how many (`Opened with 3 plug-in effects deferred. Effect › Refresh Deferred Effects runs them.`). Later +drawings leave a deferred stage as it is until its input or parameters change, which runs it under the per-call limit. +`effect.deferredStatus {}` returns `{budgetMs: 2000, effects: [{objectId, effectIndex, item?, pluginId, reason}]}` for +the active document (`reason`: `budget`, `timeout`, `missing`, `failed` or `safeMode`; `item` is the fill or stroke +whose effect it is; `objectId` can be an object in the art of a symbol, pattern, brush or opacity mask; an empty list +when none is deferred). A stage whose object is deleted, or whose plug-in effect is +removed, moved from its place in the list or hidden (or whose fill or stroke is hidden), is no longer listed. `effect.refreshDeferred {ids?}` (Effect › Refresh +Deferred Effects, enabled while a stage is deferred) runs the deferred stages of those objects (default: all of them) +again with a fresh 2,000 ms budget and returns `{refreshed, stillDeferred, failed}`: `stillDeferred` counts stages left +out for want of time again, the stages of an object that is hidden or in a hidden group or layer, which is not drawn, +and the stages with a part of their input too small for the drawing the refresh makes, and `failed` those that +timed out, failed or have no plug-in. `id` names one object in place of +`ids`, and an entry that is not an object id of the document is an error. Each document has its own budget and its own deferred stages. Exports, Expand +Appearance and commands run every stage under the per-call limit, so an export never leaves out a stage that was only +deferred for time, and the canvas then draws the result. The web build has no clock for the budget: there the first +view runs no plug-in effect, and Refresh Deferred Effects runs them. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): `document.export {format: "plugin.", params?, path?}` writes it, as does a `path` ending in one of its extensions that no built-in format has. An importer adds a read-only file format `plugin.` (listed by `document.formats` with `read: true`, and `openExtensions` holds the extensions File › Open opens with it, without those a built-in format reads or that File › Open installs, imports or loads as something else, such as `.wasm` or `.ase`): `document.open {path | name, dataBase64, importer?: diff --git a/docs/plugins.md b/docs/plugins.md index 026dcc0d9a..55de6cdafc 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -137,6 +137,19 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Live effects while a document opens + +While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget +(`vectorcraft_plugins::deferred::OPENING_BUDGET_MS`, VectorCraft's own value), measured from the first run. Each run +takes the lesser of its 5 s limit and what is left of the budget; once the budget is spent no run starts, and a result +that comes back after it is not used. A stage left out this way, or one that times out, traps, returns output the host +refuses or has no plug-in, draws its input art unchanged and is deferred. The status bar then says how many stages +are deferred, and later drawings leave them as they are until their input or parameters change. Effect › Refresh +Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget, and `effect.deferredStatus` lists +them with the reason (`budget`, `timeout`, `missing`, `failed`, `safeMode`). Each document has its own budget. +Exports, Expand Appearance and commands run every stage under the 5 s limit. The web build has no clock for the +budget, so there the first view runs no live effect and Refresh Deferred Effects runs them. + ### Heavy filters Some filters do heavy but legitimate work, such as routing a plotter's pen, packing shapes onto a sheet or running a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8fc74c474..55f1498b02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1641,6 +1641,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache totals in memory (#6228):** the settings stay in memory while `settings.json` keeps its size and modified time, a set to the same value writes nothing, every other change is written to the file before the call returns, and `cacheBytes` comes from a total kept while the `cache` folder keeps its modified time. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From f4496d61aafda82ee93df5d46cd3336537a1451d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:17:08 -0800 Subject: [PATCH 30/83] Paths: Add Anchor Point keeps the same anchors and segments selected path.insertAnchor (the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment and Alt-click with the Scissors) added the anchor without changing the selection, so the direct-selected anchors and selected segments after it on the subpath kept their old numbers and the selection shifted onto the next points along. It now renumbers them with renumber_after_insert, the helper path.reshape uses. A selected segment that the new anchor splits stays selected as its two halves, and the new anchor is direct-selected with them. Undo restores the path and the selection in one step. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/path.rs | 13 +++++- crates/engine/src/tests/draw2.rs | 76 ++++++++++++++++++++++++++++++++ docs/mcp.md | 4 ++ docs/target-app-parity.md | 1 + 4 files changed, 92 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index e249a23fcc..9ee6b61bb5 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -135,7 +135,15 @@ pub fn specs() -> Vec { has_doc, reshape ), - cmd!("path.insertAnchor", "Add Anchor Point", [], None, "{id, subpath?, segment, t: 0..1}", has_doc, insert_anchor), + cmd!( + "path.insertAnchor", + "Add Anchor Point", + [], + None, + "{id, subpath?, segment, t: 0..1} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + has_doc, + insert_anchor + ), cmd!( "path.cutAtAnchors", "Cut Path at Selected Anchor Points", @@ -1526,7 +1534,7 @@ fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[ /// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and /// selected segments after it on that subpath one higher, so the selection keeps the same points. /// A selected segment that the new anchor splits stays selected as its two halves, and the new -/// anchor joins its ends in the anchors that move with it. +/// anchor is added to the direct-selected anchors. fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { if let Some(set) = sel.anchors.get_mut(&id) { // A selected anchor index can name no anchor (`select.anchors` takes any index), so the @@ -1669,6 +1677,7 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("no such segment".into())); } let idx = sp.insert_anchor(seg, t); + renumber_after_insert(sel, id, si, idx); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so // the point added shows and can be edited at once (#4237). if !sel.contains(id) { diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index df3a5f0667..fcf9b63636 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2380,6 +2380,82 @@ fn add_anchor_point_selects_the_path_it_was_added_to() { assert!(selected_anchors(&s, kept).is_empty(), "a path selected as a whole stays so"); } +fn path_from(s: &mut Session, d: &str) -> NodeId { + NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()) +} + +fn selected_segments(s: &Session, id: NodeId) -> Vec<(usize, usize)> { + s.doc().unwrap().selection.segments.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default() +} + +fn selected_points(s: &Session, id: NodeId) -> Vec { + let pd = path(s, id); + selected_anchors(s, id).iter().filter_map(|&(si, ai)| pd.subpaths.get(si)?.anchors.get(ai)).map(|a| a.p).collect() +} + +#[test] +fn add_anchor_point_keeps_the_same_anchors_selected() { + // The direct-selected anchors after the one added are numbered one higher, so the selection + // stays on the same points; one undo step restores the path and the selection. + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 5]], "mode": "set"})).unwrap(); + let before = selected_points(&s, id); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap(); + assert_eq!(r["anchor"], 3); + assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 6)], "the anchor at 350 is now number 6"); + assert_eq!(selected_points(&s, id), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7); + assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 5)]); +} + +#[test] +fn add_anchor_point_on_a_selected_segment_keeps_both_halves_and_the_new_anchor_selected() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0"); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap(); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap(); + assert_eq!(selected_segments(&s, id), [(0, 2), (0, 3), (0, 5)]); + assert_eq!(selected_anchors(&s, id), [(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor is selected with the segment's ends"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7); + assert_eq!(selected_segments(&s, id), [(0, 2), (0, 4)]); +} + +#[test] +fn add_anchor_point_on_the_closing_segment_keeps_it_selected_as_two_halves() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L100 0 L100 100 L0 100 Z"); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 3, "t": 0.5})).unwrap(); + assert_eq!(r["anchor"], 4); + assert_eq!(selected_segments(&s, id), [(0, 3), (0, 4)]); + assert_eq!(selected_anchors(&s, id), [(0, 0), (0, 3), (0, 4)]); + assert_eq!(selected_points(&s, id), [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(0.0, 50.0)]); +} + +#[test] +fn add_anchor_point_renumbers_only_the_subpath_it_was_added_to() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [1, 1], [1, 2]], "mode": "set"})).unwrap(); + let before = selected_points(&s, id); + s.execute("path.insertAnchor", &json!({"id": id.0, "subpath": 1, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(selected_anchors(&s, id), [(0, 2), (1, 2), (1, 3)]); + assert_eq!(selected_points(&s, id), before); +} + +#[test] +fn add_anchor_point_with_a_selected_anchor_index_past_the_end_does_not_panic() { + // `select.anchors` takes any index, so a selected one can name no anchor. + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, usize::MAX]], "mode": "set"})).unwrap(); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(selected_anchors(&s, id), [(0, 2), (0, usize::MAX)]); +} + fn selected_anchors(s: &Session, id: NodeId) -> Vec<(usize, usize)> { s.doc().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default() } diff --git a/docs/mcp.md b/docs/mcp.md index 19f16205cd..fda4c0012b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3675,6 +3675,10 @@ the canvas (coordinates out of range)". `path.setHandle`, `path.moveAnchor` and `path.insertAnchor` edit subpath 0 when `subpath` is absent or null, and refuse a `subpath` that is not a whole number of 0 or more, such as 1.5, -1 or "1" ("missing integer `subpath`"); `path.split` refuses such an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. +`path.insertAnchor` keeps the direct-selected anchors and selected segments of the path on the same points: those +after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays +selected as its two halves, and the new anchor is direct-selected with them. Undo restores the path and the selection +in one step. `path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8fc74c474..ea62257e0c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -943,6 +943,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). + When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. `path.curvatureEdit`, `path.removeAnchor`, `path.convertAnchor`, `path.reshapeSegment`, `path.split`, `path.setHandle`, `path.moveAnchor` and `path.insertAnchor` refuse a `subpath` that is not a whole number of 0 or more, and `path.split` refuses such an `anchor` or `segment`; without a `subpath` they edit subpath 0. `path.reshapeSegment` refuses a delta of 1e9 pt or longer, as `object.blend.spine.reshapeSegment` does, and `path.convertAnchor` and `path.freehand` refuse a point whose x or y is 1e9 pt or more in size. `path.reshapeSegment`, `object.blend.spine.reshapeSegment`, `path.convertAnchor`, `path.curvatureEdit`, `path.insertAnchor`, `path.moveAnchors`, `path.reshape`, `path.close` and the Pencil, Curvature, Knife, Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a number, point or handle given as text, such as "10", and leave the document unchanged; `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`. From fdbf85d4c8e75f9b157cd9ac208410bc7cfc7164 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:24:39 -0800 Subject: [PATCH 31/83] Stores: saving a preset, profile or plug-in reads at most one byte past it from the file it replaces Before writing a PDF preset, ICC profile, plug-in, Color Settings, disabled list or grants file, the store compared the new bytes with the file already there by reading the whole file into memory, so a large file left in the folder was read in full. The comparison now reads at most one byte more than the new content. --- crates/engine/src/store.rs | 9 ++++++- crates/engine/src/tests/store.rs | 43 +++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index f6fe8ff5bc..01ebc46526 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -135,11 +135,18 @@ fn too_large(max: u64) -> String { format!("larger than {max} bytes") } +/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a +/// large file is not read into memory. +pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool { + let mut read = vec![]; + old.take(bytes.len() as u64 + 1).read_to_end(&mut read).is_ok() && read == bytes +} + /// Write `bytes` to `dir/file`, making the folder; nothing is written when the file has them /// already. A failure is logged: remembering is best effort and never fails the command. fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool { let path = dir.join(file); - if std::fs::read(&path).is_ok_and(|old| old == bytes) { + if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) { return true; } let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes)); diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index 37eafe6e46..b6ac7b0201 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use vectorcraft_color::cms; use crate::Session; -use crate::store::{MAX_PRESET_FILE, file_stem}; +use crate::store::{MAX_PRESET_FILE, file_stem, holds}; fn fresh_dir(tag: &str) -> std::path::PathBuf { let dir = vectorcraft_testkit::temp_dir(&format!("store-{tag}")); @@ -128,6 +128,47 @@ fn a_folder_that_does_not_exist_yet_takes_the_presets_the_preferences_held() { assert_eq!(saved_names(&mut b), ["From Preferences"]); } +/// Serves `0` bytes without end and counts how many were read. +struct Endless(u64); + +impl std::io::Read for Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0 > 1 << 24 { + return Err(std::io::Error::other("read too far")); + } + buf.fill(0); + self.0 += buf.len() as u64; + Ok(buf.len()) + } +} + +#[test] +fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { + let mut old = Endless(0); + assert!(!holds(&mut old, &[0; 10])); + assert_eq!(old.0, 11); + assert!(holds(&[1, 2, 3][..], &[1, 2, 3])); + assert!(!holds(&[1, 2, 3, 4][..], &[1, 2, 3])); + assert!(!holds(&[1, 2][..], &[1, 2, 3])); + assert!(holds(&[][..], &[])); +} + +#[test] +fn a_saved_preset_replaces_an_oversized_file_in_its_place() { + let dir = fresh_dir("oversized-put").join("PDF Presets"); + let mut a = Session::new(); + a.attach_pdf_preset_store(dir.clone()); + a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); + let file = dir.join(format!("{}.vcpdfpresets", file_stem("Web"))); + let saved = std::fs::read(&file).unwrap(); + let mut oversized = saved.clone(); + oversized.resize(usize::try_from(MAX_PRESET_FILE).unwrap() * 2, b' '); + std::fs::write(&file, &oversized).unwrap(); + + a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); + assert_eq!(std::fs::read(&file).unwrap(), saved); +} + #[test] fn damaged_unsafe_and_oversized_preset_files_are_skipped() { let dir = fresh_dir("damaged").join("PDF Presets"); From 5a8a57d5f69964bbfd64ce2a9d946f6b9c78fb12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:27:53 -0800 Subject: [PATCH 32/83] Type: upright glyphs on a vertical path keep vertical point type's cells, and the caret spans the column On a vertical path, an upright glyph is now placed in its column as vertical point type places it, then the column is centered on the path. - Its cell starts at its place on the path; it started 0.12 em earlier with fonts whose cell top is less than a full cell above the baseline. - A baseline shift moves it across the column instead of along the path. - A horizontal scale widens it evenly about the column's center. - A combining mark stays on its upright letter. - The caret and the selection highlight span the column, half its em on each side of the path, instead of the font's ascent and descent. With Skew, 3D Ribbon and Stair Step on a path that runs to the left, letters are a quarter turn counterclockwise from upright glyphs: Skew and 3D Ribbon mirror both kinds there, and Stair Step keeps letters level. The test, the progress doc and the params text of Tate-chu-yoko Settings now state these conditions and the block's directions on a path. --- crates/engine/src/cmd/panelcmds.rs | 2 +- crates/engine/src/cmd/textedit.rs | 2 +- crates/text/src/layout.rs | 65 +++++++++++------ crates/text/src/layout/on_path.rs | 9 +++ crates/text/src/tests/ligature_carets.rs | 18 ++--- crates/text/src/tests/vertical.rs | 90 +++++++++++++++++++++++- docs/mcp.md | 5 +- docs/target-app-parity.md | 4 +- 8 files changed, 155 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 04b1ce6857..d7788df10c 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index c315c2a1cb..689a73ea08 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 4a92c4ed34..15b71ae233 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -93,6 +93,34 @@ fn takes_cell(g: &SGlyph) -> bool { g.adv > 0.0 || g.face.advance(g.gid) > 0.0 } +/// Vertical type on a path: the turn that takes upright glyph `g` (of size `em`, its glyph space +/// mapped onto the path by `pre`) from its local transform `local` (`unturned` takes its Character +/// Rotation off) to the path, and where the next glyph of its cluster goes in its glyph space. +/// +/// It stands in glyph space as it stands in vertical point type's line space: a quarter turn +/// counterclockwise from horizontal path type's pose about the center of its cell, a baseline shift +/// kept across the column and a leading space taken off moving it along the path, then moved across +/// the path as a glyph lying on its side is. +fn upright_path_turn(g: &SGlyph, em: f64, pre: Affine, local: Affine, unturned: Affine, angle: f64, advance: f64) -> (Affine, f64) { + let cell = if takes_cell(g) { upright_cell(g) } else { advance }; + let (shift, unshift) = (Affine::translate((0.0, -g.bshift)), Affine::translate((0.0, g.bshift))); + let about = Point::new(cell * 0.5, -upright_centre(g, cell, em)); + let mut turn = + Affine::translate((-g.lead, g.face.ideographic_centre() * em)) * shift * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, about) * unshift; + // The effects that keep the glyph's axes fixed (Stair Step) leave its top toward the path's end on + // a path that runs to the left: it turns half a turn about its cell's center. + let tangent = Vec2::new(angle.cos(), angle.sin()); + let placed = pre * turn * local * unturned; + if (placed * Point::new(0.0, -1.0) - placed * Point::ZERO).dot(tangent) > 0.0 { + let centre = turn * shift * about; + turn = Affine::translate(centre.to_vec2() * 2.0) * Affine::scale(-1.0) * turn; + } + // Its own advance across, from where the cell centers it: where the shaper set the next glyph of + // its cluster. + let across = g.face.advance(g.gid) * g.sx; + (pre * turn, (cell - across) * 0.5 + across) +} + /// Clear the caret stops of each glyph that shares its cluster with another glyph: only a glyph /// that alone stands for its characters is a ligature. fn keep_lone_ligature_carets(glyphs: &mut [PositionedGlyph]) { @@ -333,7 +361,7 @@ impl Ctx<'_> { }; // A glyph whose leading space was taken off (mojikumi) is drawn that much earlier: an // upright one in vertical type by moving it up the column once it stands upright. - let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g); + let upright = self.vertical && g.tcy.is_none() && stands_upright(g) && !(self.on_path && g.inline.is_some()); let lead = if upright { 0.0 } else { g.lead }; let local = match &g.inline { // Inline graphics: art space to glyph space (no font outline), moved along the line by @@ -417,28 +445,21 @@ impl Ctx<'_> { let centre = g.face.ideographic_centre() * g.face.units_per_em() * g.sy; m = pre * Affine::translate((0.0, centre)) * local; } else if self.vertical && self.on_path { - // An upright glyph is a quarter turn counterclockwise from horizontal path type's pose, - // turned in glyph space so that every effect bends it as it bends glyphs lying on their - // side: its top faces the path's start and the characters of an upright ligature read - // along the path in order. The center of its cell (without its Character Rotation) keeps - // its place along the path, and its em box is centered across the path. - let (cell, top) = path_cell.unwrap_or((0.0, 0.0)); - let unrotated = local * unturned; - let middle = Point::new(g.face.units_per_em() * 0.5, cell * 0.5 - top); - // The em box's middle across the column, which the shaper's offsets then move. - let at = Point::new(g.face.units_per_em() * g.sx * 0.5, (unrotated * middle).y); - let target = Point::new(-at.y, 0.0); - let quarter = Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]); - let mut turn = Affine::translate(target.to_vec2() - (quarter * at).to_vec2()) * quarter; - // The effects that keep the glyph's axes fixed (Stair Step) leave its top toward the - // path's end on a path that runs to the left: it turns half a turn about its cell's - // center. - let tangent = Vec2::new(angle.cos(), angle.sin()); - let placed = pre * turn * unrotated; - if (placed * Point::new(middle.x, middle.y - 1.0) - placed * middle).dot(tangent) > 0.0 { - turn = Affine::translate(target.to_vec2() * 2.0) * Affine::scale(-1.0) * turn; + // An upright glyph is turned in glyph space ([`upright_path_turn`]), so every effect bends it + // as it bends glyphs lying on their side: its top faces the path's start and the characters + // of an upright ligature read along the path in order. + let next = self.out.glyphs.len(); + let after_base = self.out.glyphs.last().is_some_and(|p| p.byte == g.byte && p.line == line && p.len > 0); + if let Some((_, _, turn, after)) = cluster.filter(|c| c.0 == g.byte && c.1 == next && after_base && g.len > 0) { + // A later glyph of an upright glyph's cluster: set after it as the shaper placed it, + // and turned with it, in its glyph space. + m = turn * Affine::translate((after, 0.0)) * local; + self.upright_cluster = Some((g.byte, next + 1, turn, after)); + } else { + let (turn, after) = upright_path_turn(g, self.style_at(g.byte).size, pre, local, unturned, angle, advance); + m = turn * local; + self.upright_cluster = (g.len > 0).then_some((g.byte, next + 1, turn, after)); } - m = pre * turn * local; } else if let (true, Some(t)) = (self.vertical, g.tcy) { // Tate-chu-yoko: the block set across the column, centred on its em of it, then moved up // by its Up/Down and right by its Left/Right (line x runs down the column and line y diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index aafe175310..398928ee98 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -174,6 +174,15 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let s = style_metrics(cx.face_at(0).as_deref(), cx.style_at(0)); (s.0, s.1) }); + // Vertical type: the caret and the selection span the column, half its em on each side of the + // line Align to Path puts the baseline on. + let m = if cx.vertical { + let half = sg.iter().map(|g| g.face.units_per_em() * g.sx * 0.5).fold(f64::NAN, f64::max); + let half = if half.is_finite() { half } else { cx.style_at(0).size * 0.5 }; + (half, half) + } else { + m + }; if ap.is_empty() { cx.out.overflow = !sg.is_empty(); cx.out.lines.push(LineInfo { diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 2f9699de68..a1e06887a7 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -655,7 +655,7 @@ fn vertical_only_settings_keep_a_horizontal_ligature_whole() { } /// On a path, an upright ligature in vertical type stands with its top toward the path's start, and -/// its cell runs from 0.12 em before the pen to 0.88 em after it, with or without the font's vertical +/// its cell runs one em from the pen, as in vertical point type, with or without the font's vertical /// metrics. The inner stop lies at the middle of that cell, and the first character's selection ends /// there. #[test] @@ -673,21 +673,21 @@ fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() { assert!(l.on_path); let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; assert_eq!(g.carets, vec![(1, 0.5)], "{family}"); - assert!((g.width - 100.0).abs() < 1e-9 && (g.width_start + 12.0).abs() < 1e-9, "{family}: {} {}", g.width, g.width_start); + assert!((g.width - 100.0).abs() < 1e-9 && g.width_start.abs() < 1e-9, "{family}: {} {}", g.width, g.width_start); let x = |b| caret_position(&l, b).0.x - g.origin.x; - assert!((x(1) - 38.0).abs() < 1e-6, "{family}: {}", x(1)); + assert!((x(1) - 50.0).abs() < 1e-6, "{family}: {}", x(1)); let q = selection_quads(&l, 0, 1); assert_eq!(q.len(), 1, "{q:?}"); - assert!(((q[0][1] - q[0][0]).hypot() - 38.0).abs() < 1e-6, "{family}: {q:?}"); - // A baseline shift moves the turned glyph along the path, and its stop with it. - let ink = g.outline.bounding_box().x0; + assert!(((q[0][1] - q[0][0]).hypot() - 50.0).abs() < 1e-6, "{family}: {q:?}"); + // A baseline shift moves the turned glyph across the path, and leaves its stop in place. + let ink = g.outline.bounding_box(); t.runs[0].style.baseline_shift = 10.0; let l = layout(&db, &t); let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; - let moved = s.outline.bounding_box().x0 - ink; - assert!(moved.abs() > 1.0, "{family}: the shift moves the glyph along the path: {moved}"); + let moved = s.outline.bounding_box().center() - ink.center(); + assert!((moved.x.abs()) < 1e-6 && (moved.y + 10.0).abs() < 1e-6, "{family}: the shift moves the glyph to the path's left: {moved:?}"); let stop = caret_position(&l, 1).0.x - s.origin.x; - assert!((stop - 38.0 - moved).abs() < 1e-6, "{family}: {stop} against {}", 38.0 + moved); + assert!((stop - 50.0).abs() < 1e-6, "{family}: {stop}"); // Horizontal Scale widens the glyph across the path; its stop stays inside the glyph. t.runs[0].style.baseline_shift = 0.0; t.runs[0].style.h_scale = 200.0; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 4df48c51ef..12069e007e 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -201,9 +201,10 @@ fn top_and_ahead(l: &TextLayout, i: usize) -> (Vec2, Vec2) { (unit(g.xf * Point::new(0.0, -500.0) - pen), unit(g.xf * Point::new(500.0, 0.0) - pen)) } -/// On a vertical path, an upright glyph's top faces the path's start, and a letter lying on its side -/// is a quarter turn clockwise from it: its top faces the path's left and its baseline runs along -/// the path. Both turn with the path when it runs the other way. +/// On a vertical path with Rainbow, an upright glyph's top faces the path's start, and a letter lying +/// on its side is a quarter turn clockwise from it: its top faces the path's left and its baseline +/// runs along the path. Both turn with the path when it runs the other way. The effects that keep +/// the glyphs' axes fixed on the page keep that relation only on a path that runs to the right. #[test] fn on_a_vertical_path_letters_lie_a_quarter_turn_clockwise_from_upright_glyphs() { use vectorcraft_doc::PathEffect; @@ -218,6 +219,24 @@ fn on_a_vertical_path_letters_lie_a_quarter_turn_clockwise_from_upright_glyphs() assert!((side - Vec2::new(-upright.y, upright.x)).hypot() < 1e-6, "{to:?}: {side:?} against {upright:?}"); assert!((side - left).hypot() < 1e-6 && (ahead - tangent).hypot() < 1e-6, "{to:?}: {side:?} {ahead:?}"); } + // Skew, 3D Ribbon and Stair Step keep axes of the glyphs fixed on the page: on a path that runs + // to the right the relation holds. On one that runs to the left, Skew and 3D Ribbon mirror both + // kinds, and Stair Step keeps letters level while upright glyphs still face the path's start, so + // letters are a quarter turn counterclockwise from upright glyphs there. + for effect in [PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep] { + for to in [(1000.0, 0.0), (700.0, 700.0), (0.0, 1000.0), (0.0, -1000.0), (-1000.0, 0.0), (-700.0, 300.0)] { + // Skew and 3D Ribbon slant glyphs on a slanted path, where no turn relates them exactly. + if to.1 != 0.0 && effect != PathEffect::StairStep { + continue; + } + let l = layout(FontDb::global(), &on_vertical_path("§L", (0.0, 0.0), to, effect)); + let (upright, _) = top_and_ahead(&l, 0); + let (side, _) = top_and_ahead(&l, 1); + let clockwise = to.0 >= 0.0; + let want = if clockwise { Vec2::new(-upright.y, upright.x) } else { Vec2::new(upright.y, -upright.x) }; + assert!((side - want).hypot() < 1e-6, "{effect:?} {to:?}: {side:?} against {upright:?}"); + } + } } /// On a vertical path, letters lying on their side are set as horizontal type on the same path sets @@ -277,6 +296,71 @@ fn on_a_vertical_path_the_column_is_centered_on_the_path() { } } +/// On a vertical path, the caret and the selection span the column, half its em on each side of the +/// path, as the glyphs do. +#[test] +fn on_a_vertical_path_the_caret_and_selection_span_the_column() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (1000.0, 0.0), (-700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§L§", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let across = |p: Point| p.to_vec2().dot(Vec2::new(tangent.y, -tangent.x)); + let (top, bottom) = caret_position(&l, "§".len()); + assert!((across(top) - 10.0).abs() < 1e-6 && (across(bottom) + 10.0).abs() < 1e-6, "{to:?}: caret {top:?} {bottom:?}"); + for q in selection_quads(&l, 0, "§L§".len()) { + let (lo, hi) = q.iter().map(|p| across(*p)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), a| (lo.min(a), hi.max(a))); + assert!((lo + 10.0).abs() < 1e-6 && (hi - 10.0).abs() < 1e-6, "{to:?}: highlight from {lo} to {hi}"); + } + } +} + +/// On a straight path running down from the anchor, vertical type sets every glyph where vertical +/// point type sets it: upright glyphs with a horizontal scale stay centered on the column, a baseline +/// shift moves an upright glyph across the column, every upright glyph keeps its own cell along the +/// path, and a combining mark stays on its upright letter. +#[test] +fn on_a_downward_vertical_path_glyphs_sit_where_vertical_point_type_sets_them() { + use crate::test_fonts::{VERTICAL_FAMILY, vertical_font}; + let run = |text: &str, style: CharStyle| TextRun { text: text.into(), style, inline: None }; + let runs = |plain: CharStyle| { + vec![ + run("§×", plain.clone()), + run("§", CharStyle { h_scale: 150.0, ..plain.clone() }), + run("§", CharStyle { baseline_shift: 3.0, ..plain.clone() }), + run("§", CharStyle { rotation: 30.0, ..plain.clone() }), + run("L", CharStyle { h_scale: 150.0, ..plain.clone() }), + run("L", CharStyle { baseline_shift: 3.0, ..plain.clone() }), + run("q\u{301}x", CharStyle { standard_vertical_roman: true, ..plain.clone() }), + run("§", plain), + ] + }; + let compare = |db: &FontDb, point: &TextObject, name: &str| { + let mut on_path = point.clone(); + on_path.kind = + TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None }; + let (p, v) = (layout(db, point), layout(db, &on_path)); + assert_eq!(p.glyphs.len(), v.glyphs.len(), "{name}"); + let apart: Vec<_> = (p.glyphs.iter().zip(&v.glyphs).enumerate()) + .filter(|(_, (a, b))| a.xf.as_coeffs().iter().zip(b.xf.as_coeffs()).any(|(a, b)| (a - b).abs() > 1e-6)) + .map(|(i, (a, b))| format!("glyph {i}: {:?} on the path, {:?} in point type", b.xf.as_coeffs(), a.xf.as_coeffs())) + .collect(); + assert!(apart.is_empty(), "{name}: {apart:#?}"); + }; + let mut point = vertical(""); + point.runs = runs(CharStyle { size: 20.0, ..CharStyle::default() }); + compare(FontDb::global(), &point, "the bundled face"); + // A face with vertical metrics, whose cells hang from their vertical origins. + let db = FontDb::with_font_dirs(vec![]); + db.add_font(vertical_font(true).unwrap()); + point.runs = runs(CharStyle { size: 20.0, font_family: VERTICAL_FAMILY.into(), ..CharStyle::default() }); + compare(&db, &point, "vertical metrics"); + // The horizontally scaled upright glyph is wider across the column, centered where the plain one is. + point.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None }; + let l = layout(&db, &point); + let (plain, wide) = (ink(&l, 0), ink(&l, 2)); + assert!(wide.width() > plain.width() * 1.4 && (wide.center().x - plain.center().x).abs() < 1e-6, "{plain:?} {wide:?}"); +} + /// With Skew on a curved vertical path, every glyph's axis along the path follows the tangent and /// its axis across the path stays upright on the page: an upright glyph's top runs back along the /// tangent and its own x axis points up the page, and a letter lying on its side keeps its top up diff --git a/docs/mcp.md b/docs/mcp.md index 14a5bfb6cf..d0b41e8ca3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6374,8 +6374,9 @@ with binding punctuation (`Tg`) on, which opens as `forced`. `none` isn't saved. `text.setFormat` and `text.setRangeStyle {tcyUpDown?, tcyLeftRight?}` set the Character panel menu's Tate-chu-yoko Settings of the characters, in points from -1296 to 1296 (document points, as `baselineShift`). In vertical type a block of tate-chu-yoko characters (`tateChuYoko`) moves up by a positive Up/Down and down by a negative one, and right -by a positive Left/Right and left by a negative one. The block moves as one piece with the values of its first -character, and keeps its one em down the column, its caret positions and its hit region. Two or three digits set +by a positive Left/Right and left by a negative one. On a vertical path, a positive Up/Down moves the block toward the +path's start and a positive Left/Right moves it to the path's left, with every path effect. The block moves as one piece +with the values of its first character, and keeps its one em down the column, its caret positions and its hit region. Two or three digits set across the column without the mark do not move, and horizontal type keeps the values without moving the characters. Neither value turns `tateChuYoko` on. Both are 0 by default and saved only when not 0, and character styles carry them. A value that is not a number is refused with `` `tcyUpDown` must be a number ``, and one outside the range with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 562574cde0..d0db4c3424 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1165,10 +1165,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Tabs ruler's upper first-line marker and lower left-indent marker show absolute positions and set paragraph indents (`text.setFormat`). Dragging the lower marker keeps the upper position, while Ctrl-dragging it (Command on macOS) moves both; marker drags snap like tab stops, and each release is one undo step. With differing left indents, only the upper marker is shown and its absolute target applies to every touched paragraph. When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them in the same column, which is centered on the path); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. - Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. + Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). From 76517afebc66e0d0361d66a5b974197c209cef93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:25:33 -0800 Subject: [PATCH 33/83] Character Styles: the Fill and Stroke Tint fields have distinct names The two Tint fields in the Character Color section were both named "Tint", so a screen reader gave no way to tell the Fill field from the Stroke one. They are now named "Fill Tint" and "Stroke Tint"; the visible caption stays "Tint". The names have rows in every catalog, and a test checks both names in Character Style Options and New Character Style. --- .../ui-egui/src/dialogs/char_style_options.rs | 46 +++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + 28 files changed, 97 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index e1f564d08a..2011d2616a 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -804,19 +804,19 @@ fn paint_choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { /// the stroke Weight and Overprint Fill and Overprint Stroke, each unset or set. pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-color").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { - for (key, caption) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { + for (key, caption, tint_name) in [("fill", tl!("Fill"), tl!("Fill Tint")), ("stroke", tl!("Stroke"), tl!("Stroke Tint"))] { let row = ui.label(caption); ui.label_inputs_by(row.id, |ui| paint_choice(ui, d, key)); ui.end_row(); let tint_key = format!("{key}_tint"); - let row = ui.label(tl!("Tint")); + ui.label(tl!("Tint")); if d.fields.get(&tint_key).is_none_or(Value::is_null) { d.fields.insert(tint_key.clone(), json!("")); } let linked = d.fields.get(key).and_then(|p| p.get("swatch")).is_some_and(Value::is_string); ui.add_enabled_ui(linked, |ui| { ui.horizontal(|ui| { - ui.label_inputs_by(row.id, |ui| form::text(ui, d, &tint_key, 160.0)); + form::text_named(ui, d, &tint_key, tint_name, 160.0); ui.label("%"); }); }); @@ -1893,6 +1893,46 @@ mod tests { } } + #[test] + fn fill_and_stroke_tint_fields_have_distinct_names() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + for new_style in [false, true] { + let mut app = app(); + app.run("swatch.new", json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + if new_style { + app.run("ui.newCharStyle", json!({})).unwrap(); + } else { + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + } + let brand = json!(app.session.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("color")); + d.fields.insert("fill".into(), brand.clone()); + d.fields.insert("stroke".into(), brand); + } + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for name in ["Fill Tint", "Stroke Tint"] { + let field = h.get_by_role_and_label(Role::TextInput, name); + assert!(!field.accesskit_node().is_disabled(), "new {new_style}: {name} is enabled for a linked swatch"); + } + assert!(h.query_by_role_and_label(Role::TextInput, "Tint").is_none(), "new {new_style}: a field is named only Tint"); + } + } + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ee32cee33f..8bfb93915a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3486,6 +3486,8 @@ digits Malayalam Малаялам Tiles are numbered across, then down; leave the range empty for every tile. Плочките се номерират напречно, след това надолу; оставете диапазона празен за всяка плочка. Copies per Sheet (as many as fit, in a grid) Копия на лист (колкото се побират, в мрежа) Tint Оттенък + Fill Tint Оттенък на запълване + Stroke Tint Оттенък на щриха Tip extends past the end point Връхът продължава след крайната точка Tip on the end point Връх върху крайната точка Title Case Заглавни букви diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0970a70929..31ada1b70e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2256,6 +2256,8 @@ digits Malayalam Malajalam Green Zelena Shifts the tints of global and spot colors; other colors stay. Pomjera nijanse globalnih i spot boja; ostale boje ostaju. Tint Preliv + Fill Tint Preliv ispune + Stroke Tint Preliv poteza Color Guide Options Opcije vodiča za boje Less Manje Steps: Koraci: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 84b6833c4e..4898a45f4d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4478,6 +4478,8 @@ digits Malayalam Malaiàlam Tilt Inclinació Time (hhmmss) Hora (hhmmss) Tint To + Fill Tint To de farciment + Stroke Tint To del traç Tint Reduction Reducció de to Tints Tons Tints and Shades Tons i ombres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 733a3e813b..1b4a6bcb85 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2285,6 +2285,8 @@ digits Malayalam Malajálamské Green Zelená Shifts the tints of global and spot colors; other colors stay. Posune tóny globálních a přímých barev; ostatní barvy zůstanou. Tint Tón + Fill Tint Tón výplně + Stroke Tint Tón tahu Color Guide Options Možnosti průvodce barvami Less Méně Steps: Kroky: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d1871b2ed9..53f0e48f15 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2089,6 +2089,8 @@ digits Malayalam Malayalam Green Grøn Shifts the tints of global and spot colors; other colors stay. Flytter nuancerne af globale farver og spotfarver; andre farver forbliver uændrede. Tint Nuance + Fill Tint Fyldnuance + Stroke Tint Stregnuance Color Guide Options Indstillinger for farveguide Less Mindre Steps: Trin: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8c75b25b6b..4241811e5c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3520,6 +3520,8 @@ effect Points Punkte Copies per Sheet (as many as fit, in a grid) Kopien pro Blatt (so viele wie passen, im Raster) Gutter: Zwischenraum: Tint Tonwert + Fill Tint Flächentonwert + Stroke Tint Konturtonwert Tip extends past the end point Spitze ragt über den Endpunkt hinaus Tip on the end point Spitze auf dem Endpunkt Title Case Wortanfänge groß diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7813ee6cf8..7d3858b17f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2085,6 +2085,8 @@ font-technology Variable Μεταβλητές Threshold Κατώφλι Tile Παράθεση Tint Χρωματική απόχρωση + Fill Tint Χρωματική απόχρωση γεμίσματος + Stroke Tint Χρωματική απόχρωση περιγράμματος Tolerance Ανοχή Tolerance: Ανοχή: Tool Options… Επιλογές εργαλείου… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d8bcecbc6e..c8d60f1d41 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3575,6 +3575,8 @@ digits Malayalam Malayálam Copies per Sheet (as many as fit, in a grid) Copias por hoja (tantas como quepan, en cuadrícula) Gutter: Medianil: Tint Matiz + Fill Tint Matiz de relleno + Stroke Tint Matiz de trazo Tip extends past the end point La punta se extiende más allá del punto final Tip on the end point Punta en el punto final Title Case Tipo Título diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d3b9fb3260..37ff372c43 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2244,6 +2244,8 @@ digits Malayalam Malajalam Green Vihreä Shifts the tints of global and spot colors; other colors stay. Siirtää globaalien värien ja spottivärien sävyjä; muut värit säilyvät. Tint Sävy + Fill Tint Täytön sävy + Stroke Tint Viivan sävy Color Guide Options Väriopasteen asetukset Less Vähemmän Steps: Vaiheet: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6db5062046..3c9ad20474 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3566,6 +3566,8 @@ digits Malayalam Malayalam Copies per Sheet (as many as fit, in a grid) Copies par feuille (autant qu’il en tient, en grille) Tiles are numbered across, then down; leave the range empty for every tile. Les carreaux sont numérotés de gauche à droite, puis de haut en bas ; laissez la plage vide pour tous les carreaux. Tint Teinte + Fill Tint Teinte du fond + Stroke Tint Teinte du contour Tip extends past the end point La pointe dépasse le point d’extrémité Tip on the end point Pointe sur le point d’extrémité Title Case Majuscule à chaque mot diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3fa2269085..7aa88cfb68 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4853,6 +4853,8 @@ antiAlias Sharp शार्प Tilt झुकाव Time (hhmmss) समय (hhmms) Tint टिंट + Fill Tint फ़िल टिंट + Stroke Tint स्ट्रोक टिंट Tint Reduction टिंट में कमी Tints टिंट्स Tints and Shades टिंट्स और शेड्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27e22d0ad0..de2999dcf7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4249,6 +4249,8 @@ mark-style Japanese Japán Tilt Dőlés Copies per Sheet (as many as fit, in a grid) Példány laponként (ahány elfér, rácsban) Tint Tónus + Fill Tint Kitöltés tónusa + Stroke Tint Körvonal tónusa Tints Tónusok Tints and Shades Tónusok és árnyalatok Tips Tippek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c4e97482a8..daa818885e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2089,6 +2089,8 @@ digits Malayalam Malayalam Green Hijau Shifts the tints of global and spot colors; other colors stay. Menggeser tint warna global dan warna spot; warna lainnya tetap. Tint Tint + Fill Tint Tint isian + Stroke Tint Tint stroke Color Guide Options Opsi panduan warna Less Lebih sedikit Steps: Langkah: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 987505a43c..5f75418902 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3612,6 +3612,8 @@ digits Malayalam Malayalam Copies per Sheet (as many as fit, in a grid) Copie per foglio (quante ne entrano, in griglia) Gutter: Spazio intermedio: Tint Tinta + Fill Tint Tinta riempimento + Stroke Tint Tinta traccia Tip extends past the end point La punta si estende oltre il punto finale Tip on the end point Punta sul punto finale Title Case Iniziali maiuscole diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d3c0b6603d..3c092ac172 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3890,6 +3890,8 @@ file-filter Templates テンプレート Text Wrap Options テキストの回り込みオプション Tile Full Pages ページ全体を分割 Tint 濃度 + Fill Tint 濃度 (塗り) + Stroke Tint 濃度 (線) Tip extends past the end point 先端をパスの端点より先に伸ばす Tip on the end point 先端をパスの端点に合わせる Top 上 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5a05ccec34..c08146eea3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1995,6 +1995,8 @@ digits Malayalam მალაიალამური Green მწვანე Shifts the tints of global and spot colors; other colors stay. ცვლის გლობალური და სპოტ-ფერების ტონირებებს; სხვა ფერები უცვლელი რჩება. Tint ტონირება + Fill Tint შევსების ტონირება + Stroke Tint კონტურის ტონირება Color Guide Options ფერის გზამკვლევის პარამეტრები Less ნაკლები Steps: ბიჯები: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b0fc26d1fe..e59645e7db 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3878,6 +3878,8 @@ file-filter Templates 템플릿 Text Wrap Options 텍스트 감싸기 옵션 Tile Full Pages 전체 페이지 타일링 Tint 색조 + Fill Tint 칠 색조 + Stroke Tint 선 색조 Tip extends past the end point 끝이 끝점을 지나 연장됨 Tip on the end point 끝이 끝점에 위치 Top 위쪽 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c30a50e71d..925cd97e0b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2103,6 +2103,8 @@ digits Malayalam Malayalam Green Groen Shifts the tints of global and spot colors; other colors stay. Verschuift de tinten van globale kleuren en spotkleuren; andere kleuren blijven ongewijzigd. Tint Tint + Fill Tint Vultint + Stroke Tint Contourtint Color Guide Options Opties voor kleurengids Less Minder Steps: Stappen: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8450cb6540..343339d6d2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2201,6 +2201,8 @@ digits Malayalam Malajalam Green Zielony Shifts the tints of global and spot colors; other colors stay. Przesuwa tinty kolorów globalnych i dodatkowych; pozostałe kolory bez zmian. Tint Tinta + Fill Tint Tinta wypełnienia + Stroke Tint Tinta obrysu Color Guide Options Opcje przewodnika kolorów Less Mniej Steps: Kroki: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00d9a89484..88753d8dc8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5019,6 +5019,8 @@ axis Both Ambos Text Wrap Options Opções de Quebra de Texto Tile Full Pages Dividir em Páginas Inteiras Tint Tom + Fill Tint Tom de Preenchimento + Stroke Tint Tom do Traçado Tip extends past the end point A ponta se estende além do ponto final Tip on the end point Ponta no ponto final Toolbar: Add Tool Barra de Ferramentas: Adicionar Ferramenta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 24a6c74d5b..d487080adb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3606,6 +3606,8 @@ digits Malayalam Малаялам Tiles are numbered across, then down; leave the range empty for every tile. Плитки нумеруются слева направо, затем вниз; оставьте диапазон пустым для всех плиток. Copies per Sheet (as many as fit, in a grid) Копий на лист (сколько поместится, сеткой) Tint Оттенок + Fill Tint Оттенок заливки + Stroke Tint Оттенок обводки Tip extends past the end point Кончик выходит за конечную точку Tip on the end point Кончик на конечной точке Title Case Как в заголовке diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c038612c18..366111ee8b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3496,6 +3496,8 @@ digits Malayalam Malayalam Tiles are numbered across, then down; leave the range empty for every tile. Rutorna numreras från vänster till höger och sedan nedåt. Lämna omfånget tomt för att få med alla rutor. Copies per Sheet (as many as fit, in a grid) Kopior per ark (så många som får plats, i ett rutnät) Tint Färgton + Fill Tint Fyllnadsfärgton + Stroke Tint Konturfärgton Tip extends past the end point Spetsen sträcker sig förbi slutpunkten Tip on the end point Spetsen på slutpunkten Title Case Inledande versaler diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 282990771a..138287eda4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3385,6 +3385,8 @@ digits Malayalam Malayalam tile {number} kiremit {number} Tiles are numbered across, then down; leave the range empty for every tile. Fayanslar önce baştan sonra aşağı doğru numaralandırılır; aralığı her döşeme için boş bırakın. Tint Renk tonu + Fill Tint Dolgu Renk Tonu + Stroke Tint Kontur Renk Tonu Tip extends past the end point İpucu bitiş noktasının ötesine uzanıyor Tip on the end point Bitiş noktasına dair ipucu Title Case Başlık Durumu diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 88bcb4702a..443d15b9de 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3605,6 +3605,8 @@ effect Points Точки Copies per Sheet (as many as fit, in a grid) Копій на аркуш (скільки поміститься, сіткою) Gutter: Проміжок: Tint Відтінок + Fill Tint Відтінок заливки + Stroke Tint Відтінок обведення Tip extends past the end point Кінчик виходить за кінцеву точку Tip on the end point Кінчик на кінцевій точці Title Case Як у заголовку diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 90c292bc92..bba3d862d2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3952,6 +3952,8 @@ mark-style Japanese Kiểu Nhật Copies per Sheet (as many as fit, in a grid) Nhiều bản sao trên một tờ (xếp vừa bao nhiêu in bấy nhiêu, theo lưới) Gutter: Khoảng cách: Tint Tông màu + Fill Tint Tông màu tô + Stroke Tint Tông màu nét Tints Sắc pha Tints and Shades Sắc pha và bóng Tips Mẹo diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 77578eec12..eea0e9373b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3438,6 +3438,8 @@ digits Malayalam 马拉雅拉姆数字 Tiles are numbered across, then down; leave the range empty for every tile. 拼贴先由左至右再由上至下编号;范围留空表示全部拼贴。 Copies per Sheet (as many as fit, in a grid) 每张纸印多份 (尽量排满,按网格排列) Tint 色调 + Fill Tint 填色色调 + Stroke Tint 描边色调 Tip extends past the end point 箭头超出端点 Tip on the end point 箭头位于端点 Title Case 词首大写 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bdec63590f..95457c4d3f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4549,6 +4549,8 @@ digits Malayalam 馬來亞拉姆數字 Copies per Sheet (as many as fit, in a grid) 每張紙印多份 (盡量排滿,以格點排列) Gutter: 間距: Tint 色調 + Fill Tint 填色色調 + Stroke Tint 筆畫色調 Tip extends past the end point 尖端延伸超過終點 Tip on the end point 尖端位於終點 Title Case 標題式大小寫 From 4110f8c24e7419c3d437482746638ffc5311c1f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:30:18 -0800 Subject: [PATCH 34/83] Reshape: a step recorded without focal points plays by the earlier rule Before the Reshape tool had focal points it sent path.reshape without focal or radius, and the command stretched an open path from the grabbed point to its ends whatever the selection, and moved the anchors of a closed path within half the diagonal of its bounding box with a falloff. Such a step, in a saved action or a script, now moved a closed path whole. A step without focal (or with focal null) and without radius now plays by that earlier rule. The Reshape tool always sends focal, an empty list included, so its drags keep the focal-point rule. --- crates/engine/src/cmd/path.rs | 23 +++++++++++++++++----- crates/engine/src/tests.rs | 36 ++++++++++++++++++++++++++++------- crates/tools/src/extra.rs | 7 ++----- docs/mcp.md | 11 +++++++---- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index e249a23fcc..d6c532224b 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -131,7 +131,7 @@ pub fn specs() -> Vec { "Reshape", [], None, - "{id, x, y, dx, dy, tol=3, focal?: [[subpath, anchor]…], radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). The grabbed anchor and the anchors in focal are focal points and move by the whole drag. Anchors that are not direct-selected stay in place (a path selected whole, or not selected, has every anchor selected), and so do an open path's two ends unless they are focal points. A selected anchor between two focal points moves whole; one between a focal point and an anchor that stays takes a share of the drag that falls smoothly from 1 at the focal point to 0 at the anchor that stays, by its distance along the path's control polygon. A closed subpath with every anchor selected moves whole; a subpath with no focal point does not move. With radius, only the grabbed point's subpath changes: anchors follow with a smooth falloff over radius, measured along the path (0 or more), whatever the selection; focal and radius cannot be used together", + "{id, x, y, dx, dy, tol=3, focal?: [[subpath, anchor]…], radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). The grabbed anchor and the anchors in focal are focal points and move by the whole drag. Anchors that are not direct-selected stay in place (a path selected whole, or not selected, has every anchor selected), and so do an open path's two ends unless they are focal points. A selected anchor between two focal points moves whole; one between a focal point and an anchor that stays takes a share of the drag that falls smoothly from 1 at the focal point to 0 at the anchor that stays, by its distance along the path's control polygon. A closed subpath with every anchor selected moves whole; a subpath with no focal point does not move. With radius, only the grabbed point's subpath changes: anchors follow with a smooth falloff over radius, measured along the path (0 or more), whatever the selection; focal and radius cannot be used together. Without focal (or with focal null) and without radius, the earlier rule applies: the selection does not matter, an open path stretches from the grabbed point to its two ends, and on a closed path the anchors follow with the falloff over half the diagonal of the subpath's bounding box; the Reshape tool always sends focal", has_doc, reshape ), @@ -1573,6 +1573,11 @@ fn reshape(s: &mut Session, p: &Value) -> Result { if radius.is_some() && !focal.is_empty() { return Err(bad("path.reshape", "`focal` and `radius` cannot be used together")); } + // A step that names neither `focal` nor `radius` (as the Reshape tool recorded one before it + // had focal points) keeps that earlier rule: the selection does not matter, an open path + // stretches from the grabbed point to its two ends, and a closed one follows with a falloff + // over the default radius. + let earlier = radius.is_none() && matches!(p.get("focal"), None | Some(Value::Null)); { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -1605,11 +1610,12 @@ fn reshape(s: &mut Session, p: &Value) -> Result { added } }; - let Some(r) = radius else { + let earlier_closed = earlier && sp.closed; + if radius.is_none() && !earlier_closed { focal.insert((si, grabbed)); // Anchors that are not direct-selected stay; a path selected whole, or not selected, - // has every anchor selected. - let selected = sel.anchors.get(&id); + // has every anchor selected, and so does every path under the earlier rule. + let selected = sel.anchors.get(&id).filter(|_| !earlier); for (k, sp) in path.subpaths.iter_mut().enumerate() { if focal.range((k, 0)..=(k, usize::MAX)).next().is_none() { continue; @@ -1629,13 +1635,20 @@ fn reshape(s: &mut Session, p: &Value) -> Result { } } return Ok(()); - }; + } let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?; let closed = sp.closed; // Each anchor's distance along the path from the grabbed one, the shorter way round a // closed path: the lengths are measured once, as a path can have many anchors. let pos = sp.anchor_arc_positions(); let total = pos.last().copied().unwrap_or(0.0); + // The default reach of the earlier rule: half the diagonal of the subpath's bounding box. + let r = radius.unwrap_or_else(|| { + let mut bp = vectorcraft_geom::BezPath::new(); + sp.to_bezpath_into(&mut bp); + let b = vectorcraft_geom::Shape::bounding_box(&bp); + (b.width().hypot(b.height()) / 2.0).max(1.0) + }); let from = pos.get(grabbed).copied().unwrap_or(0.0); for (i, a) in sp.anchors.iter_mut().enumerate() { let w = if i == grabbed { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 72b6d3ea80..217d31e018 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3217,9 +3217,8 @@ fn flare_rotation_turns_only_the_rays() { fn reshape_moves_the_grabbed_point_and_its_neighbourhood() { let mut s = session(); let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); - // Grab the middle of the top edge: a new anchor appears there and moves the full delta. The - // radius, about half the square's diagonal, bounds the reach. - s.execute("path.reshape", &json!({"id": r.0, "x": 50.0, "y": 0.0, "dx": 0.0, "dy": -40.0, "radius": 70.0})).unwrap(); + // Grab the middle of the top edge: a new anchor appears there and moves the full delta. + s.execute("path.reshape", &json!({"id": r.0, "x": 50.0, "y": 0.0, "dx": 0.0, "dy": -40.0})).unwrap(); let st = s.doc().unwrap(); let pd = st.doc.node(r).unwrap().path_data().unwrap().clone(); assert_eq!(pd.anchor_count(), 5); @@ -3478,7 +3477,7 @@ fn reshape_of_a_closed_path_selected_whole_moves_all_of_it() { let mut s = session(); let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); let before = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); - s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 15.0, "dy": -40.0})).unwrap(); + s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 15.0, "dy": -40.0, "focal": []})).unwrap(); let after = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); assert_eq!(after.anchor_count(), before.anchor_count(), "a grab on an anchor adds none"); let drag = vectorcraft_geom::Vec2::new(15.0, -40.0); @@ -3492,7 +3491,7 @@ fn reshape_leaves_the_anchors_that_are_not_selected_in_place() { let mut s = session(); let id = reshape_open_path(&mut s, reshape_line_of_seven()); s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); - s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": []})).unwrap(); let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); assert_eq!((y[0], y[1], y[5], y[6]), (0.0, 0.0, 100.0, 0.0), "{y:?}"); // The stretch runs from the last anchor that is not selected, 280 from the focal point. @@ -3502,6 +3501,29 @@ fn reshape_leaves_the_anchors_that_are_not_selected_in_place() { } } +/// A step with neither `focal` nor `radius`, as one recorded before focal points, plays as it did +/// then: the selection does not matter, and a closed path follows with the default falloff. +#[test] +fn reshape_without_focal_or_radius_keeps_the_earlier_rule() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[5], y[6]), (0.0, 100.0, 0.0), "{y:?}"); + // Anchor 1 is not selected and still takes its share, measured from the end 350 away. + for i in 1..5 { + let u = i as f64 / 5.0; + assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}"); + } + // `focal: null` is the same as leaving it out. + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -40.0, "focal": null})).unwrap(); + let pts: Vec = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + assert!(pts.contains(&Point::new(0.0, -40.0)), "{pts:?}"); + assert!(pts.contains(&Point::new(100.0, 100.0)), "the far corner stays: {pts:?}"); +} + #[test] fn reshape_of_a_partly_selected_closed_path_stretches_between_the_anchors_that_stay() { let mut s = session(); @@ -3516,7 +3538,7 @@ fn reshape_of_a_partly_selected_closed_path_stretches_between_the_anchors_that_s ); // Anchors 5, 0, 1 and 2 are selected; 3 and 4 stay. The walk runs 4, 5, 0, 1, 2, 3. s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 5], [0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); - s.execute("path.reshape", &json!({"id": id.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -50.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -50.0, "focal": []})).unwrap(); let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); assert_eq!((y[0], y[3], y[4]), (-50.0, 100.0, 100.0), "{y:?}"); // From anchor 4 to the focal point is 200: anchor 5 is halfway. From anchor 3 back to it is @@ -3571,7 +3593,7 @@ fn reshape_of_a_segment_keeps_a_selected_segment_as_its_two_halves() { fn reshape_moves_only_the_subpaths_with_a_focal_point() { let mut s = session(); let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"})).unwrap()["id"].as_u64().unwrap()); - s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 40.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 40.0, "focal": []})).unwrap(); let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); let y: Vec> = pd.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p.y).collect()).collect(); assert_eq!(y[1], vec![100.0, 100.0, 100.0], "{y:?}"); diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index bcf7d6e655..4f8e867a54 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -402,11 +402,8 @@ impl ReshapeTool { /// `path.reshape`'s params for `press` dragged by `d`. fn params(cx: &ToolContext, press: &ReshapePress, d: Vec2) -> Value { let others: Vec<[usize; 2]> = press.others.iter().map(|&((si, ai), _)| [si, ai]).collect(); - let mut v = json!({ "id": press.id.0, "x": press.at.x, "y": press.at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0) }); - if !others.is_empty() { - v["focal"] = json!(others); - } - v + // `focal` is sent when empty too: without it, `path.reshape` follows the earlier rule. + json!({ "id": press.id.0, "x": press.at.x, "y": press.at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0), "focal": others }) } } diff --git a/docs/mcp.md b/docs/mcp.md index 19f16205cd..d01aa4a742 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3681,8 +3681,8 @@ anchor there unless one lies within `tol` (3 by default), and moves that point b [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has the Reshape tool stretch part of a path from the dragged point without losing the path's general form, with every highlighted focal point pulling the path. Which anchors stay, how far the stretch reaches and the share of the drag each -point takes are VectorCraft's own rule. The grabbed point and the anchors that `focal` lists as `[subpath, anchor]` pairs are focal -points and move by the whole drag; a pair that names no anchor of the path is refused ("`focal` names [0, 7], which is +point takes are VectorCraft's own rule. When `focal` is given (an empty list included), the grabbed point and the +anchors that `focal` lists as `[subpath, anchor]` pairs are focal points and move by the whole drag; a pair that names no anchor of the path is refused ("`focal` names [0, 7], which is not an anchor of the path"). Anchors that are not direct-selected stay in place (on a path selected whole, or not selected, every anchor is selected), and so do the two ends of an open path unless they are focal points. A selected anchor between two focal points moves by the whole drag. A selected anchor between a focal point and an anchor that @@ -3695,8 +3695,11 @@ point does not move. An anchor added on a segment of a partly selected path is s anchors stay selected. With `radius`, only the grabbed point's subpath changes, whatever the selection: the anchors within `radius` of the grabbed point along the path follow with a smooth falloff and the others stay; a negative `radius` is refused ("`radius` must be 0 or more"), and so is `radius` given with `focal` ("`focal` and `radius` -cannot be used together"). A drag of no length on an anchor (`dx` and `dy` 0 or left out) leaves the path as it is -and records no undo step. +cannot be used together"). Without `focal` (or with `focal` null) and without `radius`, the earlier rule applies, so +steps recorded before focal points play as they did: the selection does not matter, an open path stretches from the +grabbed point to its two ends as above, and on a closed path the anchors within half the diagonal of the subpath's +bounding box follow with the smooth falloff. The Reshape tool always sends `focal`. A drag of no length on an anchor +(`dx` and `dy` 0 or left out) leaves the path as it is and records no undo step. With the Reshape tool, a click on an anchor of a selected path makes it the focal point, and a click on a segment adds an anchor there (one undo step) that becomes the focal point. Shift-click adds an anchor or a point on a segment to the From 548fb9aa6171fb4645f68afbcb523661c5dea08d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:35:21 -0800 Subject: [PATCH 35/83] Docs: the roadmap lists each milestone once Merges of main kept both sides of conflicting edits to the milestone table, so M3, M7, M10, M11 and M13 appeared two to four times, each copy with a different subset of later edits. Keep one row per milestone. For M3, M10, M11 and M13 the kept row already contains every statement in the removed copies. For M7 no copy held them all: the kept row gains the Hyphenation and Justification clause that only the second copy carried. --- docs/roadmap.md | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index dba1b580f6..6613ebb220 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -143,25 +143,15 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 1f1b7a8b7cef0b5a66a68d9bc4e1040caecc28db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:36:45 -0800 Subject: [PATCH 36/83] Scripts: test that an include ending in a carriage return keeps the next line's number --- crates/engine/src/tests/script_include.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index f0cf7a7535..2d857b2301 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -304,6 +304,13 @@ fn script_included_error_has_local_file_and_line() { assert!(report.get("file").is_none(), "{report}"); let report = failed(&base, "#include \"five.jsxinc\"\nvar = 1;"); assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + // An included file that ends in a carriage return does not join the script's next line ending. + write(&base.join("main/cr.jsxinc"), "1;\r2;\r"); + let report = failed(&base, "#include \"cr.jsxinc\"\n\n throw new Error('after');"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(3)), "{report}"); + assert!(report.get("file").is_none(), "{report}"); + let report = failed(&base, "#include \"cr.jsxinc\"\r\nvar = 1;"); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); // An uncaught error in a file $.evalFile ran is at that file's line. let report = failed(&base, "var a = 1;\n$.evalFile('sub/thrower.jsx');"); assert_eq!(report["line"], 3, "{report}"); From 6701a1f8e553db2f506a6a927f52895db0de3363 Mon Sep 17 00:00:00 2001 From: jmverges Date: Wed, 11 Nov 2026 05:10:57 +0000 Subject: [PATCH 37/83] .ai import: stroked type in an envelope maps from its glyphs grown by half its stroke With Distort Appearance, the stroked candidate for type in an envelope mapped from the type's bounds with strokes, which for a stroke on the type's appearance (or on a group round it) reach as far as a miter join may at a corner, the miter limit times half the weight. In users' files the drawn art maps from the glyphs grown by what the strokes paint along a side: half the weight of a centred stroke. The candidate now uses that box. Character strokes keep the measure the type's bounds with strokes already give them (they have no miter allowance), and other objects in the contents keep their bounds with strokes. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 138 +++++++++++++++++++++++++-- docs/file-format-parity.md | 3 +- docs/target-app-parity.md | 4 +- 3 files changed, 134 insertions(+), 11 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 9bd3e937ad..25701650c9 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -131,15 +131,48 @@ fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { envelope_stroke_margin(stroked, plain) } -/// Envelope `kind` mapping from its contents' bounds with their strokes, for an envelope with -/// Distort Appearance whose contents have strokes it doesn't map from already; `None` otherwise. +/// The box of `content` an envelope of type with Distort Appearance maps from in a file: type by +/// its glyph outlines grown by as far as its strokes paint along a side (half the weight of a +/// centred stroke), without what miter joins add at corners, as are groups by their own strokes; +/// other objects by their bounds with strokes. `None` when nothing in it has bounds. +fn half_stroked_box(content: &[Arc]) -> Option { + /// How far the visible strokes of `appearance` paint along the sides of closed outlines. + fn along(appearance: &Appearance) -> f64 { + appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max) + } + /// `r` grown by `by` on each side, where that is a distance. + fn grown(r: Rect, by: f64) -> Rect { + if by.is_finite() && by > 0.0 { r.inflate(by, by) } else { r } + } + fn walk(n: &Arc, acc: Option) -> Option { + let one = std::slice::from_ref(n); + match &n.kind { + NodeKind::Text(t) => { + let Some((_, ink)) = envelope_content_boxes(one, Affine::IDENTITY) else { return acc }; + // The characters' own strokes as the type's bounds with strokes measure them (they + // have no miter allowance there), and the strokes of its appearance along a side. + vectorcraft_geom::union_opt(acc, Some(grown(ink, t.char_stroke_outset().max(along(&n.appearance))))) + } + NodeKind::Group { children, clip: false } => { + let members = children.iter().fold(None, |acc, c| walk(c, acc)); + vectorcraft_geom::union_opt(acc, members.map(|b| grown(b, along(&n.appearance)))) + } + _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(one, Affine::IDENTITY).map(|(stroked, _)| stroked)), + } + } + content.iter().fold(None, |acc, c| walk(c, acc)) +} + +/// Envelope `kind` mapping from its contents' glyphs grown by as far as their strokes paint along a +/// side ([`half_stroked_box`]), for an envelope with Distort Appearance whose contents have strokes it +/// doesn't map from already; `None` otherwise. fn with_strokes(kind: &NodeKind) -> Option { let NodeKind::Envelope { content, options, .. } = kind else { return None }; if !options.distort_appearance { return None; } - let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; - let margin = envelope_stroke_margin(stroked, plain)?; + let (_, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let margin = envelope_stroke_margin(half_stroked_box(content)?, plain)?; if margin == options.bounds_margin || margin.iter().any(|m| *m < 0.0) || margin.iter().all(|m| *m == 0.0) { return None; } @@ -518,7 +551,8 @@ impl WarpedType { /// doesn't draw as its drawn art is checked again as a mesh envelope on the grid the file saves /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays /// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each - /// is also checked mapping from its contents' bounds with their strokes ([`with_strokes`]). Each + /// is also checked mapping from its type's glyphs grown by half their strokes' weight + /// ([`with_strokes`]). Each /// check uses one of the import's checks and, for an envelope that shows, adds to what the page /// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't /// available, the drawn art and the hidden type stay. @@ -581,9 +615,9 @@ impl WarpedType { // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; - // With Distort Appearance, a file's envelope may map its contents from their bounds with - // their strokes or without them, and for type the size the file saves for that box is often - // out of date (not the size of the type there now): each is checked. + // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half + // their strokes' weight or from the glyphs alone, and for type the size the file saves for + // that box is often out of date (not the size of the type there now): each is checked. let kinds: Vec = live(&obj, before, inner) .into_iter() .chain(on_grid) @@ -772,3 +806,91 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s *spent = Spent { any, solid }; true } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{AppearanceItem, CharStyle, LineJoin, StrokeLayer, TextObject}; + + /// An envelope of `content` with Distort Appearance, on a flat one-patch mesh. + fn envelope_of(content: Vec>) -> NodeKind { + let points = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 50.0), Point::new(100.0, 50.0)]; + NodeKind::Envelope { + content, + kind: Box::new(EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::default(), + } + } + + /// The bounds margin of the stroked candidate for an envelope of `content`. + fn stroked_margin(content: Vec>) -> Option<[f32; 4]> { + match with_strokes(&envelope_of(content)) { + Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin), + _ => None, + } + } + + /// "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 })))) + } + + /// A 4 point stroke with miter joins at a limit of 4. + fn mitred() -> StrokeLayer { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + (stroke.join, stroke.miter_limit) = (LineJoin::Miter, 4.0); + stroke + } + + /// Type with Distort Appearance and a stroke from its appearance is tried mapped from its glyphs + /// grown by half the stroke's weight, not from its bounds with strokes, which reach as far as a + /// miter join may at a corner. + #[test] + fn stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke() { + let mut text = type_node(1, CharStyle::default()); + let mut appearance = (*text.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(mitred())); + text.appearance = appearance.into(); + let content = vec![Arc::new(text)]; + let (with, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + let half = glyphs.inflate(2.0, 2.0); + assert!(with.width() > half.width() + 1.0, "{with:?} {half:?}"); + assert_eq!(stroked_margin(content), envelope_stroke_margin(half, glyphs)); + } + + /// Type stroked by its characters alone is tried mapped from its bounds with strokes, as before, + /// turned and stretched as well as upright. + #[test] + fn type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes() { + let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, ..CharStyle::default() }; + for xf in [ + Affine::IDENTITY, + Affine::rotate(std::f64::consts::FRAC_PI_4), + Affine::scale_non_uniform(std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2), + ] { + let mut text = type_node(1, style.clone()); + if let NodeKind::Text(t) = &mut text.kind { + t.xf = xf * t.xf; + } + let content = vec![Arc::new(text)]; + let (with, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert_eq!(stroked_margin(content), envelope_stroke_margin(with, glyphs), "{xf:?}"); + } + } + + /// A stroke on a group's own appearance round type grows the box by half its weight too. + #[test] + fn a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight() { + let mut group = Node::new(NodeId(2), NodeKind::Group { children: vec![Arc::new(type_node(1, CharStyle::default()))], clip: false }); + let mut appearance = (*group.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(mitred())); + group.appearance = appearance.into(); + let content = vec![Arc::new(group)]; + let (_, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert_eq!(stroked_margin(content), envelope_stroke_margin(glyphs.inflate(2.0, 2.0), glyphs)); + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6ef0a1d863..0831a87699 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` and EPS import: stroked type in an envelope with Distort Appearance is tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, for a stroke on its appearance or on a group round it as well as its characters'; it was mapped from its bounds with strokes, which reach as far as a miter join may at a corner. Tests `ai::envelope::tests::stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke`, `type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes`, `a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. A second try is only made while more checks are left than there are envelopes of type and warped text objects still to come. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box (a rule chosen by measuring real files). An envelope's grid (warp, mesh or top object) now reads its way round from all its rows and columns, not its first row alone: a mesh bent far round (its end columns leaning more than halfway over) reads the way it runs, not turned a quarter round, and a grid symmetric about its middle reads the same wherever it is on the page. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `a_warp_of_type_tried_again_leaves_the_next_envelope_its_check`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs`, `a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: type stroked in the text document keeps its stroke's cap, join and miter limit (keys 61, 62 and 64 of its character attributes, numbered as PostScript's `setlinecap` and `setlinejoin`: 0 butt or miter, 1 round, 2 projecting or bevel). They were left at a miter join with a limit of 10 whatever the file said, so type the file strokes with round joins, or with the usual limit of 4 or less, drew spikes at its sharp corners, some many points long. In users' files, used locally and never committed, the page strokes the type with the cap, join and miter limit these keys give; no file had a bevel join, which is read by the same numbering. A value that isn't one of theirs keeps the default, a miter limit past 500 is 500, and type without a stroke keeps the defaults. Dashes are not read: no file had dashed type to tell which keys hold them. Tests `ate::tests::a_run_keeps_its_stroke_cap_join_and_miter_limit`, `tests_native::stroked_type_keeps_its_cap_join_and_miter_limit`; scores unchanged | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 33d1c3e642..d200ba07b6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -1419,7 +1419,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). From 988bfeb6ec7175648d7e87861da7017fa8167363 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:50:48 -0800 Subject: [PATCH 38/83] Symbols: Break Link keeps new art on a locked artboard selected Break Link to Symbol on an instance just placed on a locked artboard selected nothing: the art that replaced the instance has a new id, so the locked-artboard check did not see it as new art. The art of an instance that was new art is now checked without the locked artboards, and the session keeps it selected as new art. The art of an older instance on a locked artboard, named by id, is still left out of the selection. --- crates/engine/src/cmd/brushsym/symbols.rs | 25 +++++++++++++++-------- crates/engine/src/cmd/select.rs | 14 ++++++++++++- crates/engine/src/tests/brushsym.rs | 25 +++++++++++++++++++++++ 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 395c07052c..4c5cd89edf 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -391,9 +391,10 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { } /// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). A hidden or -/// locked instance's art stays hidden or locked. Returns the art's ids. Fails before any edit when -/// the instances together would make more than [`MAX_EXPAND_NODES`] objects. -fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { +/// locked instance's art stays hidden or locked. Returns each replaced instance's id with its art's +/// id. Fails before any edit when the instances together would make more than +/// [`MAX_EXPAND_NODES`] objects. +fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own))); if total > MAX_EXPAND_NODES as u64 { return Err(EngineError::Other("Too many pieces to make at once".into())); @@ -408,7 +409,7 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result Result { } let iso = s.doc()?.isolation; let out = s.edit("Break Link to Symbol", |d, sel| { - let out = break_links(d, &ids, true)?; + let fresh = d.new_art.get(); + let made = break_links(d, &ids, true)?; // Art that is hidden or locked, or in a hidden or locked group or layer, is left out of the - // selection. + // selection, as is art on a locked artboard unless the instance it replaces was new art. let locks = d.locked_artboards(); - sel.set(out.iter().copied().filter(|id| crate::cmd::select::is_selectable(d, iso, &locks, *id))); - Ok(out) + sel.set(made.iter().filter_map(|(inst, art)| { + let keep = if fresh.contains(inst) { + crate::cmd::select::is_selectable_on_any_artboard(d, iso, *art) + } else { + crate::cmd::select::is_selectable(d, iso, &locks, *art) + }; + keep.then_some(*art) + })); + Ok(made.into_iter().map(|(_, art)| art).collect::>()) })?; Ok(json!({ "ids": ids_json(&out) })) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f16246dff..4ef1e6bc6a 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -252,6 +252,18 @@ pub(crate) fn selectable_ids(d: &Document, iso: Option) -> BTreeSet, locks: &LockedArtboards, id: NodeId) -> bool { + is_selectable_within(d, iso, Some(locks), id) +} + +/// [`is_selectable`] without the locked artboards, for an edit's new selection: after the edit, +/// the session takes the art on a locked artboard out of the selection, except the new art the +/// edit made. +pub(crate) fn is_selectable_on_any_artboard(d: &Document, iso: Option, id: NodeId) -> bool { + is_selectable_within(d, iso, None, id) +} + +/// [`is_selectable`], leaving out the locked artboards when `locks` is `None`. +fn is_selectable_within(d: &Document, iso: Option, locks: Option<&LockedArtboards>, id: NodeId) -> bool { let Some(a) = d.ancestry(id) else { return false }; if !a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())) { return false; @@ -262,7 +274,7 @@ pub(crate) fn is_selectable(d: &Document, iso: Option, locks: &LockedArt None => { // The object Select All takes: the outermost one that is not a layer. let top = a.iter().filter_map(|i| d.node(*i)).find(|n| !n.is_layer()); - top.is_some_and(|t| locks.is_empty() || !locks.holds(t)) + top.is_some_and(|t| locks.is_none_or(|l| l.is_empty() || !l.holds(t))) } } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index ccf277585f..b86cf89ee7 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1386,6 +1386,31 @@ fn break_link_leaves_art_in_hidden_or_locked_groups_unselected() { assert!(!a.contains(&hidden) && !a.contains(&locked), "{a:?}"); } +/// Break Link to Symbol on an instance just placed on a locked artboard selects the art that +/// replaces it, which stays new art there. The art of an older instance there, named by id, is not +/// selected. +#[test] +fn break_link_keeps_new_art_on_a_locked_artboard_selected() { + let mut s = session(); + let (old, name, _) = make_symbol(&mut s); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + select(&mut s, &[old]); + s.execute("object.move", &json!({"dx": 1000, "dy": 0})).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "moved onto the locked artboard"); + let inst = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 1100, "y": 100})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [inst], "placed art is selected"); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + let art: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(art.len(), 1, "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art that replaces it"); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art stays editable"); + let r = s.execute("symbol.breakLink", &json!({"ids": [old.0]})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 1, "{r}"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the older instance's art"); +} + /// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked /// instance's art locked. #[test] From 9bfd6b7be5d5c99e2151cb5485889ecfea91f57c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:00:40 -0800 Subject: [PATCH 39/83] Paths: describe the anchor added on a selected segment as an end of its halves A selected segment that path.insertAnchor splits stays selected as its two halves. The new anchor is the end both halves share, so it moves with them, and Delete cuts both halves. docs/mcp.md and the comment on renumber_after_insert called it a direct-selected anchor; they now describe it as an end of the halves that moves with them. --- crates/engine/src/cmd/path.rs | 2 +- docs/mcp.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 9ee6b61bb5..12d76470cd 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1534,7 +1534,7 @@ fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[ /// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and /// selected segments after it on that subpath one higher, so the selection keeps the same points. /// A selected segment that the new anchor splits stays selected as its two halves, and the new -/// anchor is added to the direct-selected anchors. +/// anchor joins its ends in the anchors that move with it. fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { if let Some(set) = sel.anchors.get_mut(&id) { // A selected anchor index can name no anchor (`select.anchors` takes any index), so the diff --git a/docs/mcp.md b/docs/mcp.md index fda4c0012b..88a485d83e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3677,8 +3677,8 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("missing integer `su an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.insertAnchor` keeps the direct-selected anchors and selected segments of the path on the same points: those after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays -selected as its two halves, and the new anchor is direct-selected with them. Undo restores the path and the selection -in one step. +selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and +the selection in one step. `path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. From de5323efb63ada637dd6f86bbd10c201bdacb99c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:05:53 -0800 Subject: [PATCH 40/83] Expand Appearance: tinted symbols keep their colors under a color adjustment Expand Appearance on a symbol instance with a fill tint and a color adjustment applied the adjustment to the untinted art, so the expanded colors differed from the canvas. The expand path now passes the tinted instance art to adjust_in_document. --- crates/effects/src/adjust.rs | 8 +++++--- crates/effects/src/bake.rs | 2 +- crates/engine/src/cmd/effectcmd.rs | 9 ++++++++- crates/engine/src/tests/expand.rs | 23 +++++++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index a656f11e85..c345136255 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -468,12 +468,14 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images } /// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in -/// `d` (named by their content), and a symbol instance stands for its symbol's art. -pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option { +/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art` +/// when given, otherwise the symbol's art with the instance's own appearance changes. +pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option) -> Option { let art; let src = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => { - let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); + let symbol = symbol_art + .or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n))); art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?; &art } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index afe256e596..ec0da9c46a 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -112,7 +112,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { } // Colour adjustments: the object recoloured (inside it too), then baked as it is. if has_adjustment(n) - && let Some(m) = adjust_in_document(d, n) + && let Some(m) = adjust_in_document(d, n, None) { return Some(bake_node(d, &m).unwrap_or(m)); } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8bf5c9a3d7..a19455bd51 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -814,8 +814,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br let mut changed = false; // Is `n` in `out` yet? let mut listed_n = false; + // A symbol instance's fill tints its art before the adjustment, as the canvas draws it. + let symbol_art = match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(&n) => { + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n)) + } + _ => None, + }; if effects::has_adjustment(&n) - && let Some(m) = effects::adjust_in_document(d, &n) + && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { out.push((id, 0)); listed_n = true; diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 090cb98285..038b8844bb 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -75,6 +75,29 @@ fn symbol_instance_tint_survives_expanding_an_object_effect() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// The canvas tints a symbol's art with the instance fill before the instance's color adjustment, +/// and expanding gives the same colors. +#[test] +fn symbol_instance_tint_comes_before_a_color_adjustment_when_expanded() { + let mut s = session(); + square(&mut s); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Tinted Square"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let fill = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": fill, "color": "#00ff00", "opacity": 50})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}})); + let before = render(&s); + assert_ne!(before.pixel(100, 100), [255, 255, 255, 255], "the symbol is visible"); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + assert!(!matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. })); + let after = render(&s); + let (b, a) = (before.pixel(100, 100), after.pixel(100, 100)); + assert!(b.iter().zip(a.iter()).all(|(x, y)| x.abs_diff(*y) <= 8), "expanding changed the color from {b:?} to {a:?}"); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + /// An instance fill with an opacity of 0 does not tint the symbol's art, so expanding keeps the /// art's global swatch link. #[test] From badcf3f63f682800464ca8ffd07cc45736eaaf0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:07:27 -0800 Subject: [PATCH 41/83] Symbols: an instance that only moves holds art its 9-slice guides move A symbol whose natural size is not 20 x 20 is drawn through its 9-slice guides by an instance that only moves, so art the guides move can draw outside the art box moved by the instance. The visual box took that moved art box alone, and the renderer culled the instance when only the moved art was in view. The visual box now measures such an instance as it does a scaled one. --- crates/doc/src/node/ops.rs | 5 ++++- crates/render/src/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index f769572588..eb7e0d39b9 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -373,7 +373,10 @@ impl Node { NodeKind::SymbolInstance { symbol, xf } => { let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) { Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric), - Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual), + // A symbol drawn at other than its natural size goes through its 9-slice guides. + Some((s, art)) if moves_only(*xf) && s.document().symbol_slice_map_of(symbol, art.geometric, *xf).is_none() => { + xf.transform_rect_bbox(art.visual) + } Some((s, art)) => { let placed = xf.transform_rect_bbox(art.geometric); match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index dd7198d531..d5c129e5c1 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -425,6 +425,29 @@ fn an_instance_is_culled_by_the_art_nested_9_slice_guides_move() { assert_eq!(img.pixel(95, 50), [255, 0, 0, 255]); } +#[test] +fn an_instance_that_only_moves_is_culled_by_the_art_its_9_slice_guides_move() { + // A symbol made in the app: art in the 20 × 20 square, a natural size of 2 × 2, and guides a + // quarter in. An instance that only moves draws it at 20 × 20, ten times its natural size. The + // bar from x −9.9 to 0.1 crosses the left guide and is placed by the middle column's map, + // x → 1.9x: moved 115 pt right, it draws from x 96.19 to 115.19 while its art box starts at + // x 105, out of view. + let mut d = Document::new(100.0, 100.0); + let bar = rect_node(&mut d, Rect::new(-9.9, -1.0, 0.1, 1.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(bar) }); + let frame = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::None, Paint::None, 0.0); + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let art = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(inner)]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(art) }); + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [2.0, 2.0] })); + d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default())); + let (id, l) = (d.alloc_id(), d.layers[0].id); + let xf = Affine::translate((115.0, 50.0)); + d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Panel".into(), xf })).unwrap(); + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(img.pixel(98, 50), [255, 0, 0, 255]); +} + #[test] fn an_instance_with_a_geometry_effect_is_culled_by_its_reshaped_art() { // The art, (0, 0) to (20, 20), drawn from (-100, 10) is out of view, and the Transform effect From 22189986a9aac6973e3a850182ea1465abd98def Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:37:34 -0800 Subject: [PATCH 42/83] PDF export: flattening for PDF/X-1a, X-3 and 1.3 keeps art across clipping layers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PDF/X-1a, PDF/X-3 and PDF 1.3 files leave the layers they don't print out of the flattening. A flattened group no longer takes the place of art in a layer that doesn't print, so the art of a clipping layer over such a layer prints, and art of a layer that doesn't print stays out of the file. - A flattened group goes into a lower layer only when that layer prints, shows and is a template as the clipping layer does, the clipping layer and the groups it leaves have no opacity, blend mode or isolation, and the clipping path has no fill. Otherwise the group holds only the art inside the clipping layer, drawn over the clipping path's fill and the art below, and the art below is flattened on its own. Before, the fill covered the group, the group lost the layer's opacity, or the clipping path cut the art below. - Transparent art that a clipping path hides entirely, such as one of area type holding only a space, is removed. Before, the export failed because the art kept its transparency. Object › Flatten Transparency follows the same rules. Documents without clipping layers or layers that don't print export the same bytes as before. --- crates/engine/src/cmd/fileio/pdf.rs | 25 ++- crates/engine/src/cmd/fileio/tests_pdfx.rs | 198 ++++++++++++++++++++ crates/engine/src/cmd/flatten/apply.rs | 205 +++++++++++++++++++-- crates/engine/src/cmd/flatten/commands.rs | 2 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 2 +- 6 files changed, 411 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index e0acc2d52d..ccafc96e5e 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -360,9 +360,9 @@ fn encode_carrying_at( if set.pdf13() { vectorcraft_doc::cancel::progress(0, 0, "Flattening transparency"); } - let flat = flatten_for(cmd, doc, set, p)?; + let (flat, flattened) = flatten_for(cmd, doc, set, p)?; vectorcraft_doc::cancel::check()?; - if flat.is_some() { + if flattened { let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() }; warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")); } @@ -379,11 +379,19 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` /// options over it; images with see-through pixels and colorized images, including those in /// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and -/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency). -fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result> { +/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked +/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is) +/// and whether its transparency was flattened. +fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option, bool)> { if !set.pdf13() { - return Ok(None); + return Ok((None, false)); } + let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) }; + let shown = printed.map(|layers| { + let mut d = doc.clone(); + d.layers = layers; + d + }); let name = Some(set.flattener_preset.trim()).filter(|n| !n.is_empty()).unwrap_or(DEFAULT_FLATTENER); let mut o = FlattenOptions::for_export(Some(name), p.get("flattener"), &[]).map_err(|e| bad(cmd, format!("PDF flattener: {e}")))?; o.preserve_overprints &= set.advanced.overprint == Overprint::Preserve; @@ -391,7 +399,10 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul // Without soft masks a rasterized area can't be a rectangle with see-through pixels around // its art: it is clipped to its regions (opaque inside them). o.clip_complex_regions = true; - flatten_document(doc, &o) + Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? { + Some(flat) => (Some(flat), true), + None => (shown, false), + }) } /// The pages `opts` export of `doc` drawn on white, [`THUMBNAIL_SIZE`] pixels on their long side: diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index 4063e090d6..68df66bd93 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -281,6 +281,13 @@ pub(super) fn lost(reference: &vectorcraft_render::Rendered, variant: &vectorcra reference.iter().zip(variant).filter(|(r, v)| r[..3].iter().any(|c| *c < 200) && v[..3].iter().all(|c| *c >= 250)).count() } +/// How many pixels of `a` and `b` differ by more than 24 in a channel. +fn differ(a: &vectorcraft_render::Rendered, b: &vectorcraft_render::Rendered) -> usize { + assert_eq!((a.width, a.height), (b.width, b.height)); + let (a, b) = (a.pixels.as_chunks::<4>().0, b.pixels.as_chunks::<4>().0); + a.iter().zip(b).filter(|(p, q)| p[..3].iter().zip(&q[..3]).any(|(x, y)| x.abs_diff(*y) > 24)).count() +} + /// The width and height of what each of `doc`'s images shows: its frame inside the clipping /// paths around it. pub(super) fn shown_image_sizes(doc: &vectorcraft_doc::Document) -> Vec<(f64, f64)> { @@ -501,3 +508,194 @@ fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() { let (mut s, _) = cropped("cmyk", 400.0, Art::Image { see_through: true }); assert!(bytes(&mut s, &files[0]) != before(|| bytes(&mut s, &files[0]))); } + +/// The options of the PDF files without transparency. +const FLAT_FILES: [&str; 3] = [r#"{"standard": "pdfX1a"}"#, r#"{"standard": "pdfX3"}"#, r#"{"compatibility": "1.3", "preserveEditing": false}"#]; + +/// [`cropped_by`]'s clipping layer of a gradient at 80%, with a rectangle in the layer below that +/// crosses the crop's right edge. → the session and the clipping layer's id. +fn clipping_layer_over_a_rectangle(mode: &str) -> (Session, u64) { + let (mut s, layer) = cropped_by(mode, 400.0, Art::Gradient, true); + run(&mut s, "transparency.set", json!({"opacity": 80})); + let below = s.doc().unwrap().doc.layers[0].id.0; + run(&mut s, "layer.setCurrent", json!({"id": below})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 60, "width": 120, "height": 40})); + run(&mut s, "paint.setFill", json!({"color": "#406020"})); + (s, layer) +} + +/// A clipping layer over a layer that doesn't print, and a clipping layer that doesn't print +/// over one that does: the files without transparency print what the file with transparency +/// prints, and nothing of the layer that doesn't print. +#[test] +fn flattening_for_pdfx_leaves_out_the_layers_that_do_not_print() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut wrong = vec![]; + for mode in ["cmyk", "rgb"] { + for clipping_layer_prints in [true, false] { + let (mut s, layer) = clipping_layer_over_a_rectangle(mode); + let below = s.doc().unwrap().doc.layers[0].id.0; + let off = if clipping_layer_prints { below } else { layer }; + run(&mut s, "layer.setProps", json!({"id": off, "printable": false})); + let reference = drawn(&read_back(&mut s, &json!({}))); + for flat in FLAT_FILES { + let back = drawn(&read_back(&mut s, &serde_json::from_str(flat).unwrap())); + let (lost, gained) = (lost(&reference, &back), lost(&back, &reference)); + if lost + gained > 0 { + wrong.push(format!("{mode}, clipping layer prints: {clipping_layer_prints}, {flat}: {lost} pixels lost, {gained} gained")); + } + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// A clipping layer whose clipping path has a fill: the files without transparency show the art +/// over the fill, not the fill over the art. +#[test] +fn flattening_for_pdfx_keeps_the_art_of_a_clipping_layer_over_its_clipping_path_fill() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut wrong = vec![]; + for mode in ["cmyk", "rgb"] { + let (mut s, layer) = clipping_layer_over_a_rectangle(mode); + let clip = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(layer)).unwrap().children().unwrap()[0].id.0; + run(&mut s, "paint.setFill", json!({"ids": [clip], "color": "#ffdd00"})); + let reference = drawn(&read_back(&mut s, &json!({}))); + for flat in FLAT_FILES { + let back = drawn(&read_back(&mut s, &serde_json::from_str(flat).unwrap())); + // PDF/X-1a converts an RGB document's colors to CMYK. + let converted = mode == "rgb" && flat.contains("pdfX1a"); + let (lost, differ) = (lost(&reference, &back), if converted { 0 } else { differ(&reference, &back) }); + if lost > 0 || differ > 100 { + wrong.push(format!("{mode}, {flat}: {lost} pixels of art lost, {differ} pixels differ")); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Transparent art in a clipping layer whose clipping path is area type holding only a space, +/// which hides it: the files without transparency are written, without the art. +#[test] +fn flattening_for_pdfx_removes_transparent_art_that_a_clipping_layer_hides_entirely() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let [x, y, w, h] = FRAME; + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300, "colorMode": "cmyk"})); + let layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + run(&mut s, "paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}})); + run(&mut s, "transparency.set", json!({"opacity": 80})); + run(&mut s, "text.create", json!({"x": 50, "y": 50, "text": " ", "area": {"width": 80, "height": 60}})); + run(&mut s, "layer.clippingMask.toggle", json!({"id": layer})); + let reference = drawn(&read_back(&mut s, &json!({}))); + for flat in FLAT_FILES { + let p: Value = serde_json::from_str(flat).unwrap(); + let back = match s.execute("document.exportPdf", &p) { + Ok(v) => vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap(), + Err(e) => panic!("{flat}: {e}"), + }; + assert_eq!(lost(&drawn(&back), &reference), 0, "{flat}: the hidden art prints"); + } +} + +/// Object › Flatten Transparency of art in a clipping layer and art in the layer below that +/// reaches past the clipping path: when the layer below doesn't print, the clipping layer has +/// opacity, or the clipping path has a fill (see-through too, flattened keeping alpha, in a layer +/// with opacity or Multiply mode, or +/// over a layer with opacity, overlapping art of a layer with opacity or art an opacity mask +/// hides), the group stays in the clipping layer, the art below stays in its layer, and the page +/// looks the same. +#[test] +fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs() { + let mut wrong = vec![]; + let cases = [ + "the layer below doesn't print", + "the clipping path has a fill", + "the clipping path has a see-through fill, keeping alpha", + "the clipping path has a see-through fill, in a layer with opacity", + "the clipping path has a see-through fill, in a layer in Multiply mode", + "the clipping path has a see-through fill, over a layer with opacity", + "the clipping path has a see-through fill, over art that an opacity mask hides", + "the clipping path has a see-through fill, over overlapping art of a layer at 50%", + "the clipping path has no fill, in a layer with opacity", + ]; + for case in cases { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})); + let below = s.doc().unwrap().doc.layers[0].id.0; + let orange = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 200, "height": 150}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff8000"})); + let upper = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap(); + let blue = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 80, "width": 200, "height": 150}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#2040c0"})); + run(&mut s, "transparency.set", json!({"opacity": 50})); + let clip = run(&mut s, "shape.rectangle", json!({"x": 60, "y": 40, "width": 300, "height": 220}))["id"].clone(); + run(&mut s, "layer.clippingMask.toggle", json!({"id": upper})); + if case.starts_with("the layer below") { + run(&mut s, "layer.setProps", json!({"id": below, "printable": false})); + } else if !case.contains("no fill") { + run(&mut s, "paint.setFill", json!({"ids": [clip], "color": "#88ffcc"})); + } + let keeping_alpha = case.ends_with("keeping alpha"); + if case.contains("see-through fill") { + run(&mut s, "transparency.set", json!({"ids": [clip], "opacity": 50})); + } + if case.ends_with("in a layer with opacity") { + run(&mut s, "transparency.set", json!({"ids": [upper], "opacity": 80})); + } + if case.ends_with("over a layer with opacity") { + run(&mut s, "transparency.set", json!({"ids": [below], "opacity": 50})); + } + if case.ends_with("an opacity mask hides") { + run(&mut s, "layer.setCurrent", json!({"id": below})); + run(&mut s, "select.set", json!({"ids": [orange]})); + let group = run(&mut s, "object.group", json!({}))["id"].clone(); + let mask = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 200, "height": 150}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#000000"})); + run(&mut s, "select.set", json!({"ids": [group, mask]})); + run(&mut s, "transparency.makeOpacityMask", json!({})); + } + if case.ends_with("Multiply mode") { + run(&mut s, "transparency.set", json!({"ids": [upper], "blendMode": "multiply"})); + } + let mut art = vec![orange.clone()]; + if case.ends_with("a layer at 50%") { + run(&mut s, "layer.setCurrent", json!({"id": below})); + art.push(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 60, "width": 120, "height": 120}))["id"].clone()); + run(&mut s, "paint.setFill", json!({"color": "#20a040"})); + run(&mut s, "transparency.set", json!({"ids": [below], "opacity": 50})); + } + art.push(blue.clone()); + // The page as it prints. + let printed = |d: &vectorcraft_doc::Document| { + let mut d = d.clone(); + if case.starts_with("the layer below") { + let mut layer = (*d.layers[0]).clone(); + layer.visible = false; + d.layers[0] = layer.into(); + } + drawn(&d) + }; + let before = printed(&s.doc().unwrap().doc); + run(&mut s, "select.set", json!({"ids": art})); + run(&mut s, "object.flattenTransparency", json!({"preserveAlpha": keeping_alpha})); + let d = &s.doc().unwrap().doc; + let layer_of = |id: &Value| id.as_u64().and_then(|id| d.ancestry(vectorcraft_doc::NodeId(id))).map(|a| a[0].0); + if layer_of(&orange) != Some(below) { + wrong.push(format!("{case}: the art below is in layer {:?}", layer_of(&orange))); + } + let upper_art = d.node(vectorcraft_doc::NodeId(upper)).and_then(|l| l.children()).map_or(0, Vec::len); + if d.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).is_some() || upper_art != 2 { + wrong.push(format!("{case}: the clipping layer holds {upper_art} objects")); + } + let after = printed(d); + // Flat regions differ from see-through art along their antialiased edges. + let (lost, differ) = (lost(&before, &after), differ(&before, &after)); + if lost > 0 || differ > 1200 { + wrong.push(format!("{case}: {lost} pixels of art lost, {differ} pixels differ")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index c9459ed76c..555058e58f 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1,4 +1,4 @@ -use super::analysis::{Scratch, outlined_text, overlapping, reach}; +use super::analysis::{Scratch, has_effects, masked, outlined_text, overlapping, reach}; use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE}; use super::options::FlattenOptions; use super::{ @@ -108,30 +108,82 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() }; let plain: Vec = art.iter().map(|n| sc.plain(n)).collect(); // Each object as its clip groups and clipping layers show it. - let clipped: Vec = plain.iter().zip(roots).map(|(n, id)| clipped_by_ancestors(src, *id, n)).collect(); + let clipped: Vec = plain.iter().zip(roots).map(|(n, id)| clipped_by_ancestors(src, *id, n, None)).collect(); let reaches: Vec> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect(); let see_through: Vec = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; - for g in overlapping(&reaches)? { + let mut queue = overlapping(&reaches)?; + queue.reverse(); + while let Some(g) = queue.pop() { vectorcraft_doc::cancel::check()?; + // A group that stays inside the clip groups and clipping layers of its topmost object + // replaces only the objects inside them, over the others, which are flattened on their own. + let (g, under) = match inside_and_under(src, roots, &g) { + Some((inside, under)) => { + queue.push(under.clone()); + (inside, under) + } + None => (g, vec![]), + }; + // Composited over white, the group covers what it is drawn over, so it is composited over + // the fills of the clipping paths around it and the objects under it in the same kind of + // layer. Composited over nothing, it keeps its alpha and they show through. + let backdrop = !o.preserve_alpha; + let state = g.last().map(|&i| layer_state(src, roots[i])); + let top = g.last().map(|&i| roots[i]); + // A blend mode of a layer or group around the group alone would blend the art under it + // twice. + let blends = |i: usize| top.is_some_and(|t| own_layers(src, t, Some(roots[i])).iter().any(|a| a.blend != BlendMode::Normal)); + // Art under an opacity mask, effects or a knockout group is left out: the group can't draw it + // as those do. + let drawn_plainly = |i: usize| { + own_layers(src, roots[i], top).iter().all(|a| !masked(a) && !has_effects(a) && !matches!(a.knockout, vectorcraft_doc::Knockout::On)) + }; + let under_shown = under.iter().copied().filter(|&i| backdrop && Some(layer_state(src, roots[i])) == state && !blends(i) && drawn_plainly(i)); + let composited: Vec = under_shown.chain(g.iter().copied()).collect(); + let below = composited.len() - g.len(); + let extent = composited.iter().filter_map(|&i| reaches[i]).reduce(|a, b| a.union(b)).unwrap_or_default(); + let shown = |nodes: &[Node]| -> Vec { + let mut seen = vec![]; + let (mut under, mut out) = (vec![], vec![]); + for (k, &i) in composited.iter().enumerate() { + let n = clipped_by_ancestors(src, roots[i], &nodes[i], backdrop.then_some((&mut seen, extent))); + if k < below { + let groups = own_layers(src, roots[i], top).into_iter().filter(|a| !draws_as_is(a)).collect(); + under.push((groups, n)); + } else { + out.push(n); + } + } + let mut all = in_groups(under, 0); + all.extend(out); + all + }; let ids: Vec = g.iter().map(|&i| roots[i]).collect(); let group = g.iter().any(|&i| see_through[i]).then(|| { - let plain: Vec<&Node> = g.iter().map(|&i| &clipped[i]).collect(); - flatten_group(&plain, o, cmyk) + let plain = shown(&plain); + flatten_group(&plain.iter().collect::>(), o, cmyk) }); let Some((regions, area)) = group.flatten() else { - out.kept.extend(ids); + // Transparent art that its clip groups or clipping layers hide entirely draws nothing: + // it is removed. + let hides = |i: usize| see_through[i] && reach(&plain[i]).is_some() && reach(&clipped[i]).is_none(); + let (hidden, left): (Vec, Vec) = g.iter().partition(|&&i| hides(i)); + if !hidden.is_empty() { + let roots = hidden.iter().map(|&i| roots[i]).collect(); + out.flat.push(Flat { roots, regions: vec![], area: None, raster: None, lines: None }); + } + out.kept.extend(left.iter().map(|&i| roots[i])); continue; }; let raster = match area.as_ref().filter(|_| render) { Some(a) => { // Drawn as planned: the image can land outside the clip groups and clipping layers // around its art. - let art: Vec = g.iter().map(|&i| clipped_by_ancestors(src, roots[i], &art[i])).collect(); - Some(render_raster(&baked, &art, a.rect, a.ppi, a.clip.clone(), o)?) + Some(render_raster(&baked, &shown(&art), a.rect, a.ppi, a.clip.clone(), o)?) } None => None, }; @@ -146,8 +198,10 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: /// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and /// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping -/// path. `plain` itself when nothing around it clips. -fn clipped_by_ancestors(src: &Document, id: NodeId, plain: &Node) -> Node { +/// path. `plain` itself when nothing around it clips. With `fills` (clipping paths, and an area), +/// the fill of each clipping path not in them yet goes behind the art, inside the area, and the +/// path is added to them. +fn clipped_by_ancestors(src: &Document, id: NodeId, plain: &Node, mut fills: Option<(&mut Vec, Rect)>) -> Node { let mut out = plain.clone(); if !clips_count() { return out; @@ -170,13 +224,106 @@ fn clipped_by_ancestors(src: &Document, id: NodeId, plain: &Node) -> Node { if let NodeKind::Path { rule: r, .. } = &mut path.kind { *r = rule; } - let mut g = Node::group(above.id, vec![Arc::new(path), Arc::new(out)]); + let mut children = vec![Arc::new(path)]; + // The renderer paints the fill behind the clipped art. + if let Some((seen, r)) = fills.as_mut() + && !seen.contains(&clip.id) + && let Some(fill) = clip.clip_paint().fill + { + let r = *r; + seen.push(clip.id); + let mut at = Node::group(above.id, vec![Arc::new(Node::path(clip.id, shapes::rectangle(r), Appearance::default())), Arc::new(fill)]); + at.set_clips(true); + children.push(Arc::new(at)); + } + children.push(Arc::new(out)); + let mut g = Node::group(above.id, children); g.set_clips(true); out = g; } out } +/// Whether layer or group `n` draws what it holds as it is: opaque, in Normal mode, not isolated. +fn draws_as_is(n: &Node) -> bool { + n.opacity >= 1.0 && n.blend == BlendMode::Normal && !n.isolate +} + +/// `items` (in paint order, each an object and the layers and groups around it, outermost first, +/// that don't draw it as it is) with the objects of each such layer or group in one group with its +/// opacity, blend mode and isolation, from the `depth`th around them on: they then composite +/// together as that layer or group draws them. +fn in_groups(items: Vec<(Vec<&Node>, Node)>, depth: usize) -> Vec { + let mut out = vec![]; + let mut items = items.into_iter().peekable(); + while let Some((around, n)) = items.next() { + let Some(a) = around.get(depth).copied() else { + out.push(n); + continue; + }; + let mut run = vec![(around, n)]; + while let Some(next) = items.next_if(|(around, _)| around.get(depth).is_some_and(|b| b.id == a.id)) { + run.push(next); + } + let mut g = Node::group(a.id, in_groups(run, depth + 1).into_iter().map(Arc::new).collect()); + (g.opacity, g.blend, g.isolate) = (a.opacity, a.blend, a.isolate); + out.push(g); + } + out +} + +/// The layers and groups around object `id` of `src` that are not also around `other`, outermost +/// first. +fn own_layers(src: &Document, id: NodeId, other: Option) -> Vec<&Node> { + let mine = src.ancestry(id).unwrap_or_default(); + let theirs = other.and_then(|t| src.ancestry(t)).unwrap_or_default(); + let shared = mine.iter().zip(&theirs).take_while(|(a, b)| a == b).count(); + let own = mine.get(shared..mine.len().saturating_sub(1)).unwrap_or_default(); + own.iter().filter_map(|a| src.node(*a)).collect() +} + +/// The clip groups and clipping layers around object `id` of `d`, innermost first. +fn clip_ancestors(d: &Document, id: NodeId) -> Vec { + let mut a = d.ancestry(id).unwrap_or_default(); + a.pop(); + a.into_iter().rev().filter(|a| d.node(*a).is_some_and(Node::clips)).collect() +} + +/// Whether the layers around object `id` of `d` all print, all show, and whether one is a +/// template. +fn layer_state(d: &Document, id: NodeId) -> (bool, bool, bool) { + let mut a = d.ancestry(id).unwrap_or_default(); + a.pop(); + a.iter().filter_map(|a| d.node(*a)).fold((true, true, false), |(print, show, template), n| match &n.kind { + NodeKind::Layer { printable, template: t, .. } => (print && *printable, show && n.visible, template || *t), + _ => (print, show, template), + }) +} + +/// For group `g` (indices of `roots` of `src`, in paint order) whose flattened group can't leave +/// the clip groups and clipping layers of its topmost object ([`place_of`]): the objects inside +/// them and the objects under them. `None` when the group can leave them, or every object is +/// inside them. +fn inside_and_under(src: &Document, roots: &[NodeId], g: &[usize]) -> Option<(Vec, Vec)> { + if !clips_count() || g.len() < 2 { + return None; + } + let ids: Vec = g.iter().map(|&i| roots[i]).collect(); + let top = clip_ancestors(src, *ids.last()?); + if top.is_empty() { + return None; + } + let inside = |id: NodeId| { + let mine = clip_ancestors(src, id); + top.iter().all(|c| mine.contains(c)) + }; + if !inside(place_of(src, &ids)?) { + return None; + } + let (inside, under): (Vec, Vec) = g.iter().partition(|&&i| inside(roots[i])); + (!under.is_empty()).then_some((inside, under)) +} + /// The regions and the image area replacing one group of overlapping objects (`plain`: the art as /// composited; `cmyk`: in a CMYK document); `None` when it paints nothing. fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Regions, Option)> { @@ -493,6 +640,17 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan for f in plan.flat { // A group always has objects. let Some(top) = place_of(d, &f.roots) else { continue }; + // Art hidden entirely is removed. + if f.regions.is_empty() && f.area.is_none() { + if one_pass { + flat.extend(f.roots.iter().map(|r| (*r, vec![]))); + } else { + for r in &f.roots { + d.remove(*r)?; + } + } + continue; + } let mut children = vec![]; // The image goes under the regions, reaching a pixel past its own: their edges then fall on // matching pixels instead of on what is behind the group. @@ -564,19 +722,26 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan /// The object of `roots` (in paint order) whose place their flattened group takes: the topmost one /// that no clip group or clipping layer clips unless it clips every object of `roots`, else the -/// topmost one. +/// topmost one. The group stays with the topmost object rather than move to a layer that prints, +/// shows or is a template where the topmost object's layer differs, out from a clip group or +/// clipping layer whose clipping path has a fill, which would then cover it, or out from a layer +/// or group with opacity, a blend mode or isolation. fn place_of(d: &Document, roots: &[NodeId]) -> Option { - let top = roots.last().copied(); + let top = roots.last().copied()?; if !clips_count() || roots.len() < 2 { - return top; + return Some(top); } - let clips = |id: NodeId| -> Vec { - let ancestry = d.ancestry(id).unwrap_or_default(); - ancestry.iter().rev().skip(1).filter(|a| d.node(**a).is_some_and(Node::clips)).copied().collect() - }; - let all: Vec> = roots.iter().map(|r| clips(*r)).collect(); + let fills = |clip: &NodeId| d.node(*clip).and_then(|n| n.children()?.first().map(|c| c.clip_paint().fill.is_some())).unwrap_or(false); + let all: Vec> = roots.iter().map(|r| clip_ancestors(d, *r)).collect(); + let above = all.last().map_or(&[][..], Vec::as_slice); let shared = |mine: &Vec| mine.iter().all(|c| all.iter().all(|theirs| theirs.contains(c))); - roots.iter().zip(&all).rev().find(|(_, mine)| shared(mine)).map(|(r, _)| *r).or(top) + let leaves_fill = |mine: &Vec| above.iter().any(|c| !mine.contains(c) && fills(c)); + // Out of a layer or group with opacity, a blend mode or isolation, the group would lose it. + let leaves_compositing = |r: NodeId| own_layers(d, top, Some(r)).iter().any(|a| !draws_as_is(a)); + let state = layer_state(d, top); + let place = + roots.iter().zip(&all).rev().find(|(r, mine)| shared(mine) && !leaves_fill(mine) && layer_state(d, **r) == state && !leaves_compositing(**r)); + Some(place.map_or(top, |(r, _)| *r)) } /// An image of `r` (in a clip group when it is clipped). diff --git a/crates/engine/src/cmd/flatten/commands.rs b/crates/engine/src/cmd/flatten/commands.rs index d528e40d8b..53687713b5 100644 --- a/crates/engine/src/cmd/flatten/commands.rs +++ b/crates/engine/src/cmd/flatten/commands.rs @@ -10,7 +10,7 @@ pub fn specs() -> Vec { "Flatten Transparency…", ["Object"], None, - "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_doc, flatten ), diff --git a/docs/mcp.md b/docs/mcp.md index face503682..f979db1549 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -836,7 +836,8 @@ page with hint tables saying where every other page's objects are), which stays `compatibility: "1.3"` writes a PDF 1.3 file, which has no transparency: a copy of the document is flattened first with `flattenerPreset` (empty: High Resolution; `high`, `medium`, `low` or a saved preset, `flattener.presets.list`) and `flattener` options over it (as `object.flattenTransparency` takes them); images with see-through pixels count as -transparency and rasterized areas are clipped to their regions. A file that would still have transparency fails the +transparency and rasterized areas are clipped to their regions. Layers the file leaves out (non-printing ones, unless +`includeNonPrinting` or `createLayers` is set) are left out of the flattening. A file that would still have transparency fails the export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than @@ -3062,7 +3063,12 @@ Each other group becomes one group of atomic regions: paths filled with the flat white, which blend modes do not read; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, opacity masks or raster effects reach (clipped to those regions with `clipComplexRegions`, a rectangle without). The image leaves out the part of such art that the clipping path of a clip group or clipping layer hides, so art under -the hidden part of a cropped picture stays as it is. +the hidden part of a cropped picture stays as it is. Transparent art that such a clipping path hides entirely is +removed. A group that holds art from inside and outside a clipping layer goes in the place of the topmost art outside +it. When that layer prints, shows or is a template where the clipping layer differs, the clipping layer or a group +around the art has opacity, a blend mode or isolation, or the clipping path has a fill, +the group holds only the art inside the clipping layer, drawn over the fill and over the art below in the same kind of +layer as its own layers draw it (over nothing with `preserveAlpha`), and the art outside is flattened on its own. `preset` is `high`, `medium` (the default) or `low`; option keys (`balance` 0–100, `lineArtPpi`, `gradientPpi`, `textToOutlines`, `strokesToOutlines`, `clipComplexRegions`, `antiAlias`, `preserveAlpha`, `preserveOverprints`) override it, at the top level or in `options`. `balance: 0` rasterizes everything; lower balances rasterize groups diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e291ded52..22a7cbb828 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1413,7 +1413,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. - PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). + PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one. Layers the file leaves out are left out of the flattening, and transparent art that a clipping path hides entirely is removed (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). 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`). From df50bbf0f3706c15aaac650dacf540e570a3d1dd Mon Sep 17 00:00:00 2001 From: jmverges Date: Wed, 11 Nov 2026 06:32:40 +0000 Subject: [PATCH 43/83] Type: tracking and manual kerning take the Horizontal Scale In horizontal type, tracking and manual kerning are now thousandths of the em as the Horizontal Scale draws it: at 50%, a tracking of 100 adds 0.05 em after each character. They were added at the full em while the glyph advances took the scale, so narrow tracked type drifted from the page of users' .ai files letter by letter. That page writes such type's character spacing as the tracking itself in a text space as wide as the scale, which PDF scales by it (ISO 32000-1 9.4.4). Vertical type keeps the full em: its advances down the column don't all take the scale. vectorcraft_text::spacing_scale gives the factor. Shaping, inline graphics and the Optical pairs use it, and so do the conversions from points back to thousandths of an em: the automatic kerning the Character panel reads and Touch Type's limits (glyph_em), Combine Point Text, and PDF import, whose tracking is now the file's Tc. Scale Text Attributes now keeps tracked type where a horizontal stretch drew it. SVG export writes letter-spacing in thousandths of the font size it writes (the vertical scale), so uniformly scaled type keeps its spacing in a viewer. Type with both a Horizontal Scale other than 100% and tracking or manual kerning lays out differently than before, in every document. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/text/char_style.rs | 4 +- crates/engine/src/cmd/addons/cleanup/text.rs | 6 ++- .../src/cmd/addons/cleanup/text/tests.rs | 18 +++++++++ crates/engine/src/cmd/textedit.rs | 10 +++-- crates/engine/src/tests/textedit.rs | 31 ++++++++++++++ crates/engine/src/tests/typescale.rs | 24 +++++++++++ crates/pdf/src/import_text.rs | 29 +++++++++----- crates/pdf/src/tests/text_placement.rs | 15 +++++++ crates/svg/src/css.rs | 7 +++- crates/svg/tests/it/text_layout.rs | 12 ++++++ crates/text/src/lib.rs | 1 + crates/text/src/shape.rs | 34 ++++++++++++---- crates/text/src/tests.rs | 40 +++++++++++++++++++ crates/text/src/tests/inline.rs | 4 ++ crates/text/src/tests/typo.rs | 18 +++++++++ crates/text/src/tests/vertical.rs | 14 +++++++ docs/file-format-parity.md | 3 +- docs/type-parity.md | 3 +- 18 files changed, 247 insertions(+), 26 deletions(-) diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 67ccb60a44..fd828c79af 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -22,10 +22,10 @@ pub struct CharStyle { /// Leading in points; None = Auto (120% of size). #[serde(default, skip_serializing_if = "Option::is_none")] pub leading: Option, - /// Tracking in 1/1000 em. + /// Tracking in 1/1000 em; in horizontal type, of the em as [`Self::h_scale`] draws it. #[serde(default)] pub tracking: f64, - /// Manual pair spacing in 1/1000 em; None uses the automatic mode. + /// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option, /// Use glyph shapes for automatic pair spacing; false uses font metrics. diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 73b21356b0..6e6abfaa48 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -544,7 +544,11 @@ fn merge(chain: &[&Piece]) -> std::result::Result { for (k, w) in off.windows(2).enumerate() { let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue }; if delta.abs() > 1e-9 { - edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0); + // Thousandths of the em as the Horizontal Scale draws it (`spacing_scale`). + let vertical = m.vertical; + edit::style_range(&mut m.runs, s, e, |st| { + st.tracking += delta / (st.size * vectorcraft_text::spacing_scale(st, vertical)).max(1e-6) * 1000.0; + }); if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) { return Err(k + 1); } diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index c75446b106..27d0233bb6 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -176,6 +176,24 @@ fn combine_joins_only_pieces_on_one_line_turned_alike() { assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine")); } +/// Pieces in horizontally scaled type: the tracking that puts each back where it was is measured in +/// the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), as layout spaces it. +#[test] +fn combine_puts_horizontally_scaled_pieces_back_where_they_were() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 160, "y": 100, "text": "Right", "size": 20})); + for id in [a, b] { + s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 200})).unwrap(); + } + let was = glyphs(&s, &[a, b]); + select(&mut s, &[a, b]); + let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap(); + assert_eq!(ids(&r), [a]); + assert_eq!(obj(&s, a).plain_text(), "Left Right"); + assert_same_places(&was, &glyphs(&s, &[a])); +} + /// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs, /// pieces on a line left to right, each line's baseline where it was (its leading is the distance /// from the line above), in one undo step. A piece turned unlike the top-left one stays. diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index c315c2a1cb..2650aa9b2f 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1087,12 +1087,16 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { } /// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it -/// was shaped at (superscript, small caps and Shrink Text to Fit included). +/// was shaped at (superscript, small caps and Shrink Text to Fit included), in horizontal type +/// as its Horizontal Scale draws it ([`vectorcraft_text::spacing_scale`]). fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option { let face = db.face_by_id(g.font_id)?; - let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0; + let runs = edit::slice_runs(&t.runs, g.byte, g.byte + g.len); + let style = &runs.first()?.style; + // The glyph's own scale takes in the Horizontal Scale. + let h_scale = style.h_scale / 100.0; let [a, b, ..] = g.xf.as_coeffs(); - Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0) + Some(a.hypot(b) * face.units_per_em() / h_scale * vectorcraft_text::spacing_scale(style, t.vertical)).filter(|em| em.is_finite() && *em > 0.0) } /// The current pair correction in thousandths of an em, including an automatic correction. diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index e584e3e328..e04c2c7289 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -280,6 +280,37 @@ fn metrics_pair_step_preserves_the_drawn_auto_position() { assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}"); } +/// At 50% Horizontal Scale the font's pair reads as the same thousandths of an em as at 100%: +/// kerning is measured in the em as the scale draws it (`vectorcraft_text::spacing_scale`), so the +/// value read keeps V where the font's kerning draws it, and a step moves V half as far as at 100%. +#[test] +fn horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "hScale": 50})).unwrap(); + let before = obj(&s, id); + assert_eq!(before.runs[0].style.h_scale, 50.0); + let auto = vectorcraft_text::layout(db, &before); + let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4]; + let read = crate::cmd::effective_kerning(db, &before, &auto, 0, 1); + assert!((read + 160.0).abs() < 0.01, "the font's -160/1000 em: {read}"); + let mut same = before.clone(); + vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(read)); + assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01); + + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01); + let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto); + assert!((moved - s.prefs.tracking_increment * 0.05).abs() < 0.01, "V moves by half a kerning increment at 100%: {moved}"); +} + #[test] fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() { use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index 5bc09827b9..f96193a6c4 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -345,3 +345,27 @@ fn scale_text_attributes_bakes_group_scale_and_undoes() { s.execute("edit.undo", &json!({})).unwrap(); near(text(&s, id).runs[0].style.size, 12.0); } + +/// Scale Text Attributes bakes a horizontal stretch into the Horizontal Scale: tracked type stays +/// where the stretch drew it, as tracking is measured in the em the Horizontal Scale draws +/// (`vectorcraft_text::spacing_scale`). It used to lose the stretch's share of the tracking. +#[test] +fn scale_text_attributes_keeps_tracked_type_where_it_was() { + let mut s = session(); + let id = create(&mut s, 20.0); + s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 300})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let pens = |s: &Session| { + let t = text(s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect::>() + }; + let before = pens(&s); + s.execute("type.scaleTextAttributes", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.h_scale, 200.0); + let after = pens(&s); + assert_eq!(before.len(), after.len()); + for (b, a) in before.iter().zip(&after) { + assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}"); + } +} diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index a90d6a33be..b7163c0e58 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -633,7 +633,7 @@ impl TextLine { let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); let size = self.at.size; if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 { - let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size); + let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size, spacing_em(&t, size)); t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); } } @@ -675,7 +675,7 @@ impl TextLine { // left in the file's order. let total: usize = t.runs.iter().map(|r| r.text.len()).sum(); let gaps: Vec<(usize, f64)> = if t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] }; - let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size); + let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size, spacing_em(&t, size)); t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); // Tracked: laid out again for its bounds. bounds = vectorcraft_text::layout(db, &t).bounds; @@ -701,16 +701,19 @@ fn pens(laid: &TextLayout, chars: &[usize]) -> Vec> { } /// `t`'s runs with kerning `kern` and each character's tracking from `own` (points, one per -/// character, in thousandths of each run's em), characters alike kept in one run. +/// character, in thousandths of each run's em as its Horizontal Scale draws it), characters alike +/// kept in one run. fn restyled(t: &TextObject, kern: Option, own: &[f64]) -> Vec { let mut out: Vec = Vec::with_capacity(t.runs.len()); // The run of `t` the last character came from. let mut from = None; let mut k = 0; for (i, r) in t.runs.iter().enumerate() { - let size = r.style.size.max(1e-3); + // A PDF scales its character spacing by its horizontal scaling (ISO 32000-1 §9.4.4), as + // layout scales tracking ([`vectorcraft_text::spacing_scale`]). + let em = (r.style.size * vectorcraft_text::spacing_scale(&r.style, t.vertical)).max(1e-3); for c in r.text.chars() { - let tracking = own.get(k).map_or(0.0, |e| (e / size * 1000.0).clamp(-1000.0, 10000.0)); + let tracking = own.get(k).map_or(0.0, |e| (e / em * 1000.0).clamp(-1000.0, 10000.0)); k += 1; // Hundredths of a thousandth of an em: no drift along a line, no noise in the panels. let tracking = (tracking * 100.0).round() / 100.0; @@ -971,8 +974,9 @@ pub(crate) fn median(mut v: Vec) -> Option { /// as `laid`, `extra` points longer, as the file set it: the same after every character, except /// the spaces read from gaps or drawn between glyphs (`gaps`: byte offset, gap in points) where /// that would put the glyphs after them more than a tenth of an em off (a barcode's digits, set in -/// groups apart). Those take their own tracking, given with their byte offsets. -fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, size: f64) -> (f64, Vec<(usize, f64)>) { +/// groups apart). Those take their own tracking, given with their byte offsets. `em`: the em the +/// tracking is thousandths of, in points ([`spacing_em`]). +fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, size: f64, em: f64) -> (f64, Vec<(usize, f64)>) { let pairs = chars.saturating_sub(1).max(1) as f64; // The advance of the first glyph laid out at each byte offset. let space: HashMap = laid.glyphs.iter().rev().map(|g| (g.byte, g.advance)).collect(); @@ -995,8 +999,15 @@ fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, s tracking = if rest >= 1.0 { (extra - own.iter().map(|(_, need)| need).sum::()) / rest } else { 0.0 }; } own.sort_by_key(|(b, _)| *b); - let em = |pts: f64| (pts / size * 1000.0).clamp(-1000.0, 10000.0).round(); - (em(tracking), own.into_iter().map(|(b, need)| (b, em(need - tracking))).collect()) + let thousandths = |pts: f64| (pts / em.max(1e-3) * 1000.0).clamp(-1000.0, 10000.0).round(); + (thousandths(tracking), own.into_iter().map(|(b, need)| (b, thousandths(need - tracking))).collect()) +} + +/// The em the tracking of type `t` set `size` points is thousandths of, in points: the size as its +/// first run's Horizontal Scale draws it in horizontal type ([`vectorcraft_text::spacing_scale`]), +/// as a PDF scales its character spacing by its horizontal scaling (ISO 32000-1 §9.4.4). +fn spacing_em(t: &TextObject, size: f64) -> f64 { + size * t.runs.first().map_or(1.0, |r| vectorcraft_text::spacing_scale(&r.style, t.vertical)) } /// `runs` with tracking `tracking`, and each space at a byte offset of `spaces` (in order) a run diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 45bf5e4098..f275def4dd 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -286,6 +286,21 @@ fn spacing_and_scaling_keep_each_glyph_where_the_file_put_it() { } } +/// Character spacing in horizontally scaled type: a PDF scales `Tc` by its horizontal scaling +/// (ISO 32000-1 §9.4.4), as layout scales tracking by the Horizontal Scale +/// (`vectorcraft_text::spacing_scale`), so the type's tracking is the file's `Tc` in thousandths of +/// its size: 1.5 pt at 16 pt is 93.75, set 80% wide. +#[test] +fn character_spacing_in_horizontally_scaled_type_is_the_files_tc() { + let bytes = page("BT /F1 16 Tf 1.5 Tc 80 Tz 20 50 Td (Spaced and narrow) Tj ET", ""); + let t = texts(&open_as(&bytes, TextAs::Text)); + assert_eq!(t.len(), 1); + assert!(t[0].runs.iter().all(|r| (r.style.h_scale - 80.0).abs() < 1e-6), "{:?}", t[0].runs); + let tracking: Vec = t[0].runs.iter().map(|r| r.style.tracking).collect(); + assert!(tracking.iter().all(|v| (v - 93.75).abs() < 0.5), "{tracking:?}"); + assert!(displacement(&bytes) < 0.02); +} + /// Word spacing stays on the spaces, as tracking of their own; evenly spaced letters keep one /// tracking value for the line, and a file that didn't kern opens with kerning off. #[test] diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 78113dcd8c..bdabab2acd 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -160,10 +160,13 @@ pub(crate) fn font_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { /// written by `len`. pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { let mut p = Props::new(); - // Tracking and manual kerning both add space after every character. + // Tracking and manual kerning both add space after every character, in thousandths of the em + // of the font size written (the vertical scale, see `font_props`). The canvas spaces them by + // the horizontal scale: a uniform scale is the same, and `textLength` stretches type scaled + // horizontally alone, glyphs and spacing together, from the one to the other. let spacing = st.tracking + st.kerning.unwrap_or(0.0); if spacing != 0.0 { - p.push(("letter-spacing", len(spacing / 1000.0 * st.size))); + p.push(("letter-spacing", len(spacing / 1000.0 * st.size * st.v_scale / 100.0))); } if st.kerning.is_some() { // Manual kerning replaces the font's pair kerning. diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index adcc101f25..a031de7412 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -554,6 +554,18 @@ fn ragged_lines_keep_their_character_spacing() { } } +/// Tracking and manual kerning in type scaled uniformly, which no `textLength` stretches, take the +/// scale in a viewer as they do on the canvas. +#[test] +fn spacing_in_uniformly_scaled_type_takes_the_scale() { + for st in [ + CharStyle { h_scale: 200.0, v_scale: 200.0, tracking: 100.0, ..style(12.0) }, + CharStyle { h_scale: 150.0, v_scale: 150.0, kerning: Some(80.0), ..style(12.0) }, + ] { + assert_drawn_in_place(&area_doc(vec![run("tracked wide", st)], 280.0, Justify::Left)); + } +} + /// Type scaled horizontally before a tab is stretched to its own width, not to the tab's gap. #[test] fn scaled_type_before_a_tab_keeps_its_width() { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index cbc5157edd..011bb6eb20 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -49,6 +49,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, fit_first_line, fit_source_lines, layout, layout_with, scaled}; +pub use shape::spacing_scale; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ae44ce433d..a58e8ef57e 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -357,6 +357,19 @@ pub(crate) fn cap_x_heights(face: Option<&FontFace>, st: &CharStyle) -> (f64, f6 (face.cap_height * k, face.x_height * k) } +/// The share of the em that tracking and manual kerning (thousandths of an em) of characters in +/// style `st` are measured in. In horizontal type that is the Horizontal Scale: they are +/// thousandths of the em as the scale draws it, so at 50% a tracking of 100 adds 0.05 em, half as +/// much as at 100%, as the page of users' `.ai` files spaces such type (and as PDF scales its +/// character and word spacing by its horizontal scaling, ISO 32000-1 §9.4.4). Baking a horizontal +/// scale of the type's transform into the Horizontal Scale then keeps the spacing. In vertical +/// type, whose advances down the column don't all take the Horizontal Scale, the em itself: 1. A +/// scale that isn't a positive number counts as 100%. +pub fn spacing_scale(st: &CharStyle, vertical: bool) -> f64 { + let hs = st.h_scale / 100.0; + if vertical || !(hs.is_finite() && hs > 0.0) { 1.0 } else { hs } +} + /// Shape `text[range]`, where `runs` gives each run's byte range in `text` and style, `inlines` /// (parallel to `runs`) the inline graphic of each run that is one, and `levels` each byte's bidi /// embedding level from `range.start` (empty: all left to right). Glyphs come out in logical @@ -736,7 +749,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< let right_y = right.dy - right.bshift; let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue }; let em = left.sx * left.face.upem / (left_style.h_scale / 100.0); - let tracking = left_style.tracking / 1000.0 * em; + // The tracking shaping added: thousandths of the em as its Horizontal Scale draws it. + let tracking = left_style.tracking / 1000.0 * em * spacing_scale(left_style, false); // A manual kerning value on the left glyph is part of its advance and, right to left, of // its offset too (it spaces the left glyph from its left neighbor): it is not taken off. let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::() - tracking; @@ -931,8 +945,10 @@ fn shaping_script(c: char) -> Script { /// vertical centre on the middle of the cap height raised by the inline's shift (see /// [`InlineArt`]). Its advance is the scaled art width plus tracking and its character's manual /// kerning, which right to left in horizontal type also moves the art right by the value, as it -/// moves a letter's glyph. The glyph's ascent and descent grow to the art's extent so a tall -/// graphic opens up its line. A missing symbol takes a square of the same height and draws nothing. +/// moves a letter's glyph. The art doesn't take the run's Horizontal Scale; the tracking and the +/// kerning do, as after a letter ([`spacing_scale`]). The glyph's ascent and descent grow to the +/// art's extent so a tall graphic opens up its line. A missing symbol takes a square of the same +/// height and draws nothing. #[allow(clippy::too_many_arguments)] fn inline_glyph( face: &Arc, @@ -959,8 +975,9 @@ fn inline_glyph( } _ => (kurbo::Affine::IDENTITY, h, None), }; - let tracking = st.tracking / 1000.0 * size; - let manual_kern = st.kerning.map(|v| v / 1000.0 * size).filter(|k| k.is_finite()).unwrap_or(0.0); + let spacing_em = size * spacing_scale(st, vertical); + let tracking = st.tracking / 1000.0 * spacing_em; + let manual_kern = st.kerning.map(|v| v / 1000.0 * spacing_em).filter(|k| k.is_finite()).unwrap_or(0.0); let adv = width + if tracking.is_finite() { tracking } else { 0.0 } + manual_kern; SGlyph { face: face.clone(), @@ -1063,6 +1080,9 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let km = full / face.upem; let hs = st.h_scale / 100.0; let vs = st.v_scale / 100.0; + // The em the tracking and manual kerning are thousandths of: in horizontal type, as the + // Horizontal Scale draws it ([`spacing_scale`]; the runs shaped together share the scale). + let spacing_em = size * spacing_scale(st, feats.vertical); let ascent = face.ascent * km * vs; let descent = face.descent * km * vs; let cap = face.cap_height * km * vs; @@ -1379,7 +1399,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if ch == SOFT_HYPHEN || ch == '\u{2028}' { adv = 0.0; } else { - let manual_kern = gst.kerning.map(|v| v / 1000.0 * size).unwrap_or(0.0); + let manual_kern = gst.kerning.map(|v| v / 1000.0 * spacing_em).unwrap_or(0.0); // Manual kerning spaces a character from the next one in reading order. Right to left, // that one is drawn to its left: the cluster's glyphs move right along the baseline by // the value, so that the space its last glyph's advance gains is at the cluster's left. @@ -1387,7 +1407,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe kern_shift = manual_kern; } if last_in_cluster { - let tracking = gst.tracking / 1000.0 * size; + let tracking = gst.tracking / 1000.0 * spacing_em; adv += tracking + manual_kern; } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 2dd3c424c6..a7a0724ee1 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -225,6 +225,46 @@ fn tracking_and_scale() { assert!(b.y1 < -4.0, "shifted up: {b:?}"); } +/// In horizontally scaled type, tracking and manual kerning are thousandths of the em as the scale +/// draws it (`spacing_scale`): at 50% they add half the space they add at 100%, after every +/// character, as the page of users' `.ai` files spaces such type. +#[test] +fn tracking_and_manual_kerning_take_the_horizontal_scale() { + let laid = + |h_scale: f64, tracking: f64, kerning: Option| layout(db(), &point("Wave", CharStyle { h_scale, tracking, kerning, ..style(20.0) })); + let advances = |l: &TextLayout| l.glyphs.iter().map(|g| g.advance).collect::>(); + let line = |l: &TextLayout| l.lines[0].x1 - l.lines[0].x0; + // 200/1000 of a 20 pt em: 4 pt after each character at 100%, 2 pt at 50%. + for (h_scale, extra) in [(100.0, 4.0), (50.0, 2.0)] { + for (name, plain, spaced) in [ + ("tracking", laid(h_scale, 0.0, None), laid(h_scale, 200.0, None)), + ("manual kerning", laid(h_scale, 0.0, Some(0.0)), laid(h_scale, 0.0, Some(200.0))), + ] { + let (a, b) = (advances(&plain), advances(&spaced)); + assert_eq!(a.len(), 4, "{name}: {a:?}"); + assert_eq!(a.len(), b.len(), "{name}"); + for (p, s) in a.iter().zip(&b) { + assert!((s - p - extra).abs() < 1e-9, "{name} at {h_scale}%: {extra} pt more after each character: {a:?} {b:?}"); + } + let longer = line(&spaced) - line(&plain); + assert!((longer - 4.0 * extra).abs() < 1e-9, "{name} at {h_scale}%: the line is {} pt longer, not {longer}", 4.0 * extra); + } + } +} + +/// The factor tracking and manual kerning take from the Horizontal Scale: the scale in horizontal +/// type, 1 in vertical type and for a scale that isn't a positive number. +#[test] +fn spacing_scale_is_the_horizontal_scale_of_horizontal_type() { + let at = |h_scale: f64, vertical: bool| spacing_scale(&CharStyle { h_scale, ..style(20.0) }, vertical); + assert_eq!(at(50.0, false), 0.5); + assert_eq!(at(250.0, false), 2.5); + assert_eq!(at(50.0, true), 1.0, "vertical type keeps the em"); + for junk in [0.0, -50.0, f64::NAN, f64::INFINITY] { + assert_eq!(at(junk, false), 1.0, "{junk}"); + } +} + #[test] fn underline_and_strikethrough_bars() { let mut t = point("ab", style(20.0)); diff --git a/crates/text/src/tests/inline.rs b/crates/text/src/tests/inline.rs index 76c90e65b6..01db5393cf 100644 --- a/crates/text/src/tests/inline.rs +++ b/crates/text/src/tests/inline.rs @@ -71,6 +71,10 @@ fn shift_tracking_and_missing_symbols() { let mut t = text("A", art(1.0), "B", 20.0); t.runs[1].style.tracking = 100.0; assert!((inline_glyph(&layout(db(), &t)).advance - 42.0).abs() < 1e-6); + // At 50% Horizontal Scale the tracking adds half as much, as after a glyph; the art keeps its + // width. + t.runs[1].style.h_scale = 50.0; + assert!((inline_glyph(&layout(db(), &t)).advance - 41.0).abs() < 1e-6); // Unresolved (missing symbol): a square of the height, nothing to draw. let t = text("A", InlineArt::new("gone"), "B", 20.0); let l = layout(db(), &t); diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 4b8bdbc09e..4790b642af 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -66,6 +66,24 @@ fn optical_pairs_cross_paint_runs_and_manual_and_tracking_are_independent() { assert!((pair_advance(&rtl_manual) - pair_advance(&rtl_pair_zero) - 20.0).abs() < 0.01, "manual spacing changes the adjacent right-to-left pair"); } +/// At 50% Horizontal Scale the tracking adds half the space it adds at 100% (`spacing_scale`), +/// and the Optical pairs measure their gaps without it: tracked, each advance is the untracked +/// Optical one and the tracking, the corrections unchanged. +#[test] +fn optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, h_scale: 50.0, ..CharStyle::default() }; + let advances = |st: CharStyle| layout(db(), &TextObject::point(Point::ZERO, "IIAV", st)).glyphs.iter().map(|g| g.advance).collect::>(); + let optical = advances(st.clone()); + let unkerned = advances(CharStyle { kerning: Some(0.0), ..st.clone() }); + assert!((optical[0] - unkerned[0]).abs() > 0.1, "Optical changes the monospaced pair at 50%: {optical:?} {unkerned:?}"); + let tracked = advances(CharStyle { tracking: 100.0, ..st }); + assert_eq!(optical.len(), tracked.len()); + for (o, t) in optical.iter().zip(&tracked) { + // 100/1000 of the 100 pt em drawn 50% wide. + assert!((t - o - 5.0).abs() < 0.01, "{optical:?} {tracked:?}"); + } +} + #[test] fn rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order() { for optical_kerning in [false, true] { diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 225395d348..f05f2c4764 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -343,6 +343,20 @@ fn tracking_spaces_upright_marks_without_moving_them_off_the_centre_line() { assert!((step - 24.0).abs() < 1e-6, "one em plus 200/1000 em of tracking: {step}"); } +/// Vertical type keeps its tracking in thousandths of the em itself at any Horizontal Scale +/// (`spacing_scale`): its advances down the column don't all take the scale. +#[test] +fn vertical_tracking_keeps_the_em_at_any_horizontal_scale() { + let step = |h_scale: f64, tracking: f64| { + let l = layout(FontDb::global(), &vertical_styled("§§", CharStyle { size: 20.0, h_scale, tracking, ..CharStyle::default() })); + ink(&l, 1).center().y - ink(&l, 0).center().y + }; + for h_scale in [100.0, 50.0] { + let more = step(h_scale, 200.0) - step(h_scale, 0.0); + assert!((more - 4.0).abs() < 1e-6, "{h_scale}%: 200/1000 of the 20 pt em: {more}"); + } +} + /// Baseline shift moves an upright glyph across the column, as it moves a letter lying on its /// side, at any Character Rotation, and leaves its neighbors where they are. The glyph turns about /// its shifted pen position (`xf * pivot`), and `xf * unturned` places the shifted glyph without diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6ef0a1d863..f0b4b5bae6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` and EPS import, PDF import, SVG export and `.ai` save: type with a Horizontal Scale other than 100% and tracking or manual kerning is spaced as a `.ai`'s own page spaces it. Layout now measures tracking and manual kerning in thousandths of the em as the scale draws it (see type-parity.md, same date); they were added at the full em, so such type drifted from the page letter by letter. A `.ai`'s page writes that type's character spacing as the tracking itself in a text space as wide as the scale, which PDF scales by it (ISO 32000-1 §9.4.4). In 224 users' files (used locally, never committed), 93 render differently. Of the 25 whose render moved by more than 1% of its pixels against the page, 23 came closer. The note on the type differing from the page shows a smaller share in 5 files (11.0% to 4.4% at most) and a larger one in 2 (by 0.2 to 0.3 points). 9 more envelopes of type open live (113 to 122 of 203, none fewer in any file), and no file switched between its layers and its PDF part. PDF import: the tracking of horizontally scaled type is the file's `Tc` in thousandths of its size (it was that times the scale), the glyphs where they were (test `tests::text_placement::character_spacing_in_horizontally_scaled_type_is_the_files_tc`). SVG export writes the letter spacing in thousandths of the font size it writes (the vertical scale), so type scaled uniformly keeps its spacing in a viewer (test `text_layout::spacing_in_uniformly_scaled_type_takes_the_scale`); tracked type scaled horizontally alone still differs a little there, as before. A `.ai` saved here writes the same values as before; VectorCraft now lays them out as the file's own PDF part draws them. Scores and estimates unchanged. | | 2026-11-11 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. A second try is only made while more checks are left than there are envelopes of type and warped text objects still to come. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box (a rule chosen by measuring real files). An envelope's grid (warp, mesh or top object) now reads its way round from all its rows and columns, not its first row alone: a mesh bent far round (its end columns leaning more than halfway over) reads the way it runs, not turned a quarter round, and a grid symmetric about its middle reads the same wherever it is on the page. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `a_warp_of_type_tried_again_leaves_the_next_envelope_its_check`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs`, `a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: type stroked in the text document keeps its stroke's cap, join and miter limit (keys 61, 62 and 64 of its character attributes, numbered as PostScript's `setlinecap` and `setlinejoin`: 0 butt or miter, 1 round, 2 projecting or bevel). They were left at a miter join with a limit of 10 whatever the file said, so type the file strokes with round joins, or with the usual limit of 4 or less, drew spikes at its sharp corners, some many points long. In users' files, used locally and never committed, the page strokes the type with the cap, join and miter limit these keys give; no file had a bevel join, which is read by the same numbering. A value that isn't one of theirs keeps the default, a miter limit past 500 is 500, and type without a stroke keeps the defaults. Dashes are not read: no file had dashed type to tell which keys hold them. Tests `ate::tests::a_run_keeps_its_stroke_cap_join_and_miter_limit`, `tests_native::stroked_type_keeps_its_cap_join_and_miter_limit`; scores unchanged | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | diff --git a/docs/type-parity.md b/docs/type-parity.md index defb384739..4013f8be19 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -81,6 +81,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Tracking and manual kerning in horizontally scaled type: they are thousandths of the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), so at 50% a tracking of 100 adds 0.05 em after each character, half as much as at 100%. They were added at the full em whatever the scale, so narrow tracked type drifted further right with each letter. Illustrator's own layout in users' `.ai` files (used locally, not committed) spaces such type so, and PDF scales its character spacing by its horizontal scaling alike (ISO 32000-1 §9.4.4). Inline graphics take it after them too; vertical type keeps the full em, its advances down the column not all taking the Horizontal Scale. The automatic kerning the Character panel reads, Touch Type's limits and Artwork Cleanup's Combine Point Text measure in the same em, and Scale Text Attributes now keeps tracked type where a horizontal stretch of its transform drew it. Type that has both a Horizontal Scale other than 100% and tracking or manual kerning lays out differently than before in every document. Tests `tests::tracking_and_manual_kerning_take_the_horizontal_scale`, `tests::typo::optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking`, `tests::inline::shift_tracking_and_missing_symbols`, `tests::vertical::vertical_tracking_keeps_the_em_at_any_horizontal_scale` and the engine's `horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it`, `scale_text_attributes_keeps_tracked_type_where_it_was` and `combine_puts_horizontally_scaled_pieces_back_where_they_were`. Scores and estimates unchanged. | | 2026-11-10 | minor | Edit Custom Dictionary (#4936): Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, applied on Done; the Check Spelling dialog remains. Scores and estimates unchanged. | | 2026-11-10 | minor | Type on a path (#3565): Direct Selection shows the direction handles of selected type on a path's path, as of a path selected whole, and drags them (`text.setPathHandle`; Alt: one side, Shift: 45° steps); the text reflows along the new curve. Scores and estimates unchanged. | | 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on type has Spelling › Auto Spell Check, checked while it is on; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | From a2c09544c814a70cd546be108813bb95d55090c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:22:00 -0800 Subject: [PATCH 44/83] Render: a placed document drawn exactly lends its own composite fonts A placed document drawn without a bitmap (renders without progressive placed art, exports) drew type in the placed document's own composite font in the fallback font: only the outer document's composite fonts were lent to the font database. The placed document's composite fonts are now lent while its art is drawn. --- crates/render/src/placed_document.rs | 3 ++- crates/render/src/tests/fontchange.rs | 28 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 3827829d05..6daf192fc4 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -425,7 +425,8 @@ impl Renderer { if !k.is_finite() || k <= 1e-12 { return; } - // The art in its own coordinates, with its own resources. + // The art in its own coordinates, with its own resources (its composite fonts included). + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&e.doc.composite_fonts); let symbols = e.doc.symbol_boxes().quick(); let visible = m.inverse().transform_rect_bbox(f.visible); let inner = Frame { doc: &e.doc, symbols: &symbols, view: f.view * m, visible, px: f.px / k, output: f.output * m, ..*f }; diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 4ead4a5c1c..8f6d68f575 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -179,6 +179,34 @@ fn a_documents_own_composite_font_draws_without_being_registered() { assert_eq!(thumbnail(&composite, id), thumbnail(&plain, plain_id), "thumbnail"); let placed = |d: &Document| crate::placed_document::render_inside(&mut Renderer::new(), d, &d.layers[0], 300, 150, view).map(|r| r.pixels); assert_eq!(placed(&composite), placed(&plain), "a placed document's art"); + // A page that places the document, drawn exactly (no bitmap of the placed art). + let page = |d: &Document, id: NodeId, key: &str| { + use vectorcraft_doc::{ImageBlob, LinkInfo, PlacedDocument}; + let blob = ImageBlob::new("application/json", key.as_bytes().to_vec()); + let p = PlacedDocument { + link: LinkInfo::new("/art/type.vectorcraft"), + key: key.into(), + bounding: false, + page_box: Default::default(), + width: 300.0, + height: 150.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + let art = d.node(id).unwrap().clone(); + vectorcraft_doc::placed_document::prime(&p, blob.bytes.clone(), (d.clone(), art, Rect::new(0.0, 0.0, 300.0, 150.0))); + let mut page = Document::new(300.0, 150.0); + page.images.insert(key.into(), blob); + let n = Node::new(page.alloc_id(), NodeKind::PlacedDocument(Box::new(p))); + let l = page.layers[0].id; + page.insert(Some(l), 0, n).unwrap(); + Renderer::new().render(&page, 300, 150, view, &opts).pixels + }; + assert_eq!( + page(&composite, id, "fontchange-composite-placed"), + page(&plain, plain_id, "fontchange-plain-placed"), + "a placed document's art drawn exactly" + ); assert!(db.composite_font(NAME).is_none(), "given back after each render"); } From 2443d1250b4b3ae62555da0411bbc97cc441b74c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:27:25 -0800 Subject: [PATCH 45/83] Character Styles: a tint error names the Fill Tint or Stroke Tint field An out-of-range or non-numeric tint in Character Style Options and New Character Style gave "Tint must be a number from 0 to 100" for both fields, so the message did not say which of the two to correct. It now names "Fill Tint" or "Stroke Tint", the names the two fields carry. --- crates/ui-egui/src/dialogs/char_style_options.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 2011d2616a..d1ca76cc58 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -251,7 +251,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "v_scale" => tl!("Vertical Scale"), "baseline_shift" => tl!("Baseline Shift"), "rotation" => tl!("Character Rotation"), - "fill_tint" | "stroke_tint" => tl!("Tint"), + "fill_tint" => tl!("Fill Tint"), + "stroke_tint" => tl!("Stroke Tint"), "stroke_width" => tl!("Weight"), _ => return Err("unknown character style number field".into()), }; @@ -1649,8 +1650,8 @@ mod tests { fn color_tint_and_weight_outside_their_limits_are_errors() { let linked = json!({"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink"}); for (key, value, message) in [ - ("fill_tint", "150", "Tint must be a number from 0 to 100"), - ("stroke_tint", "-1", "Tint must be a number from 0 to 100"), + ("fill_tint", "150", "Fill Tint must be a number from 0 to 100"), + ("stroke_tint", "-1", "Stroke Tint must be a number from 0 to 100"), ("stroke_width", "-1", "Weight must be a number from 0 to 4000000"), ("stroke_width", "thick", "Weight must be a number"), ] { From e76524fd8b6c61ba8fc3dcc458f6f0d4e6289636 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:40:25 -0800 Subject: [PATCH 46/83] Graphs: labels keep paragraph settings and anti-aliasing when the graph is drawn again Paragraph settings given to all of a graph label's text with text.setFormat (indents, spacing, hyphenation, Justification options, composer, direction, kashida, kinsoku, mojikumi, burasagari and the rest) and the label's anti-aliasing method were lost when the graph drew its labels again, because the graph kept only a character style for each kind of label. Each kind now also keeps its paragraph settings and anti-aliasing method, saved with the graph in its label styles, and the graph still sets each label's alignment for its place. The legend spaces its entries by the kept legend settings: Legend Across Top measures each label with its indents and spacing, both legend layouts make room for extra leading or paragraph spacing, and a label with a negative indent or negative space before moves right or down so it stays clear of its swatch and of the entry above it. --- crates/doc/src/graph.rs | 24 ++- crates/engine/src/cmd/graph.rs | 4 +- crates/engine/src/cmd/graph/generate.rs | 16 +- crates/engine/src/cmd/graph/labels.rs | 62 +++++++- crates/engine/src/cmd/graph/series.rs | 71 +++++++-- crates/engine/src/cmd/graph/tests.rs | 199 ++++++++++++++++++++++++ crates/engine/src/cmd/panelcmds.rs | 23 ++- docs/mcp.md | 9 ++ docs/target-app-parity.md | 4 +- 9 files changed, 379 insertions(+), 33 deletions(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 72b066a06e..f3b655d76a 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -136,9 +136,11 @@ impl crate::Document { } } -/// The character style a graph's labels keep through regeneration once formatted (Format the text in graphs): the -/// value axis numbers, the category labels (category axis, radar spokes, pie names) and the legend labels (beside or -/// across the top, or in pie wedges). `None` draws the default 9 pt black. +/// The character style and anti-aliasing method a graph's labels keep through regeneration once formatted (Format +/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the +/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para` +/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each +/// label's alignment. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct LabelStyles { @@ -148,6 +150,22 @@ pub struct LabelStyles { pub categories: Option, #[serde(skip_serializing_if = "Option::is_none")] pub legend: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub values_para: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub categories_para: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub legend_para: Option, + /// The anti-aliasing method the value axis numbers keep once set (Character panel › Anti-aliasing Method). + /// `None` draws them Sharp. + #[serde(skip_serializing_if = "Option::is_none")] + pub values_anti_alias: Option, + /// The anti-aliasing method the category labels keep once set. `None` draws them Sharp. + #[serde(skip_serializing_if = "Option::is_none")] + pub categories_anti_alias: Option, + /// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp. + #[serde(skip_serializing_if = "Option::is_none")] + pub legend_anti_alias: Option, } impl LabelStyles { diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 8c838d421b..f4b6c90c13 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -43,8 +43,8 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - capture_label_styles, capture_series_object_opacity, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets, - series_object_opacity_differs, shown_paint, + capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity, + capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index d1a5ddde06..2f16d5e423 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -2,7 +2,8 @@ use super::axis::{LABEL_SIZE, MAX_CATEGORY_TICKS, MAX_TICK_MARKS, one_line, rada use super::columns::{Allowance, ColumnArt, column_art, column_designs}; use super::data::fmt_value; use super::labels::{ - Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_size, label_width, polyline, recolour_text, runs, shadow_of, + Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_extra_height, label_shift, label_size, label_width, polyline, + recolour_text, runs, shadow_of, }; use super::markers::{MARKER_BUDGET, marker_cost, marker_designs}; use super::series::{series_marks, with_series_opacity}; @@ -901,6 +902,8 @@ impl<'a> Plot<'a> { fn legend_label(&mut self, (x, y): (f64, f64), label: &str) -> Arc { let ls = self.ls; + let (dx, dy) = label_shift(&self.g.label_styles, label); + let (x, y) = (x + dx, y + dy); self.b.label(Role::Legend, Point::new(x + 12.0, y + 7.5 + (ls - LABEL_SIZE) * 0.35), label, Justify::Left, false) } @@ -909,10 +912,11 @@ impl<'a> Plot<'a> { fn legend_across_top(&mut self) -> Vec> { let (g, r, ls) = (self.g, self.r, self.ls); let entries: Vec<(usize, String)> = (0..self.legend_series()).map(|s| (s, self.legend_text(s))).filter(|(_, l)| !blank_label(l)).collect(); - let mut rows: Vec> = vec![vec![]]; + let mut rows: Vec> = vec![vec![]]; let mut used = 0.0; for (s, label) in entries { let w = 12.0 + label_width(&g.label_styles, &label) + 12.0; + let h = ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&g.label_styles, &label); // The gap after an entry may run past the plot's edge. if used + w - 12.0 > r.width() && rows.last().is_some_and(|row| !row.is_empty()) { rows.push(vec![]); @@ -920,10 +924,10 @@ impl<'a> Plot<'a> { } used += w; if let Some(row) = rows.last_mut() { - row.push((s, label, w)); + row.push((s, label, w, h)); } } - let height = |row: &[(usize, String, f64)]| ls * 1.8 * row.iter().map(|(_, l, _)| l.split('|').count()).max().unwrap_or(1) as f64; + let height = |row: &[(usize, String, f64, f64)]| row.iter().map(|(.., h)| *h).fold(ls * 1.8, f64::max); // Above the plot and anything drawn over it (radar and stacked-pie labels). let top = self.b.out.iter().chain(self.on_top.iter()).filter_map(|n| n.geometric_bounds()).map(|bb| bb.y0).fold(r.y0, f64::min); let top = self.bars_reach.map_or(top, |b| top.min(b.y0)); @@ -931,7 +935,7 @@ impl<'a> Plot<'a> { let mut labels = vec![]; for row in &rows { let mut x = r.x0; - for (s, label, w) in row { + for (s, label, w, _) in row { self.legend_swatch(*s, (x, y)); labels.push(self.legend_label((x, y), label)); x += w; @@ -954,7 +958,7 @@ impl<'a> Plot<'a> { y += ls * 1.8; continue; } - y += ls * 1.8 * label.split('|').count() as f64; + y += ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&self.g.label_styles, &label); self.legend_swatch(s, (x, row_y)); labels.push(self.legend_label((x, row_y), &label)); } diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index fdd640a954..7c01272809 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -10,7 +10,7 @@ use super::{ pub(super) struct Gen<'a> { pub(super) d: &'a mut Document, pub(super) out: Vec>, - /// The labels' kept character styles. + /// The labels' kept character styles and paragraph attributes. pub(super) styles: &'a vectorcraft_doc::LabelStyles, /// What the column designs may still add. pub(super) columns: Allowance, @@ -45,6 +45,30 @@ pub(super) fn label_style(styles: &vectorcraft_doc::LabelStyles, role: Role) -> st } +/// The paragraph attributes labels of `role` are set with: the kept ones, else the defaults. The caller sets the +/// alignment. +pub(super) fn label_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::ParaStyle { + let kept = match role { + Role::Value => &styles.values_para, + Role::Category => &styles.categories_para, + Role::Legend => &styles.legend_para, + }; + let mut para = kept.clone().unwrap_or_default(); + // A file's attributes within the limits the Paragraph controls keep to (they are copied onto every label). + para.keep_spacing_in_range(); + para +} + +/// The anti-aliasing method labels of `role` are drawn with: the kept one, else Sharp. +pub(super) fn label_anti_alias(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::text::TypeAntiAlias { + let kept = match role { + Role::Value => styles.values_anti_alias, + Role::Category => styles.categories_anti_alias, + Role::Legend => styles.legend_anti_alias, + }; + kept.unwrap_or_default() +} + /// How big labels of `role` are set: a kept style's size, else 9 pt. The labels' spacing follows it. pub(super) fn label_size(styles: &vectorcraft_doc::LabelStyles, role: Role) -> f64 { label_style(styles, role).size @@ -63,6 +87,8 @@ impl Gen<'_> { pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc { let style = label_style(self.styles, role); let mut t = TextObject::point(at, s, style); + t.para = label_para(self.styles, role); + t.anti_alias = label_anti_alias(self.styles, role); t.para.justify = justify; t.system_layout = self.d.setup.system_layout; refresh_bounds(&mut t); @@ -162,12 +188,40 @@ pub(super) fn shadow_of(d: &mut Document, n: &Node) -> Arc { Arc::new(d.reid(&c)) } -/// How wide label `s` is set (its widest line), without adding it to a document. -pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 { +/// The bounds of legend label `s` set from the origin with paragraph attributes `para`, without adding it to a document. +fn legend_label_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, para: vectorcraft_doc::ParaStyle) -> Option { let style = label_style(styles, Role::Legend); let mut t = TextObject::point(Point::ZERO, &s.replace('|', "\n"), style); + t.para = para; + t.para.justify = Justify::Left; refresh_bounds(&mut t); - Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds().map_or(0.0, |b| b.width()) + Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds() +} + +/// How far label `s` reaches right of where it starts (its widest line and any indent), after the legend moves it right +/// by [`label_shift`], without adding it to a document. +pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 { + legend_label_bounds(styles, s, label_para(styles, Role::Legend)).map_or(0.0, |b| (b.x1 + label_shift(styles, s).0).max(0.0)) +} + +/// The bounds of legend label `s` set with its kept paragraph attributes and with the defaults, when it has kept ones. +fn kept_and_default_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str) -> Option<(Rect, Rect)> { + styles.legend_para.as_ref()?; + Some((legend_label_bounds(styles, s, label_para(styles, Role::Legend))?, legend_label_bounds(styles, s, vectorcraft_doc::ParaStyle::default())?)) +} + +/// How much further left and further up legend label `s` reaches with its kept paragraph attributes than with the +/// defaults (a negative indent or negative spacing), so the legend moves it right and down by that much and it stays +/// clear of its swatch and of the entries before it. +pub(super) fn label_shift(styles: &vectorcraft_doc::LabelStyles, s: &str) -> (f64, f64) { + kept_and_default_bounds(styles, s).map_or((0.0, 0.0), |(kept, default)| ((default.x0 - kept.x0).max(0.0), (default.y0 - kept.y0).max(0.0))) +} + +/// How much further down legend label `s` reaches with its kept paragraph attributes than with the defaults (more +/// leading, or space before or after), after the legend moves it down by [`label_shift`], so the legend makes room +/// for it. +pub(super) fn label_extra_height(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 { + kept_and_default_bounds(styles, s).map_or(0.0, |(kept, default)| (kept.y1 + (default.y0 - kept.y0).max(0.0) - default.y1).max(0.0)) } /// A label with nothing to show (empty, or only `|` line breaks). diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 7d7d75a161..229a4d4b42 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,7 +1,7 @@ use vectorcraft_color::BlendMode; use super::axis::radar_axis; -use super::labels::{Role, filled_lines_on, label_style}; +use super::labels::{Role, filled_lines_on, label_para, label_style}; use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad}; // ---------- generation ---------- @@ -406,23 +406,34 @@ fn graph_labels(doc: &Document) -> HashMap { out } -/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels -/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or -/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so -/// they undo together. Returns whether a kept style changed. -pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { - if ids.is_empty() { - return false; - } +/// Keep the anti-aliasing method `method` given to graph labels `ids` for every label of their kind, as +/// [`capture_label_styles`] keeps a formatting change. Returns whether a kept method changed. +pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], method: vectorcraft_doc::text::TypeAntiAlias) -> bool { let labels = graph_labels(doc); - if labels.is_empty() { - return false; - } let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect(); kinds.sort_by_key(|(g, r)| (g.0, *r as u8)); kinds.dedup(); let mut changed = false; for (graph, role) in kinds { + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = match role { + Role::Value => &mut spec.label_styles.values_anti_alias, + Role::Category => &mut spec.label_styles.categories_anti_alias, + Role::Legend => &mut spec.label_styles.legend_anti_alias, + }; + changed |= *slot != Some(method); + *slot = Some(method); + } + changed +} + +/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels +/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or +/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so +/// they undo together. Returns whether a kept style changed. +pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { + let mut changed = false; + for (graph, role) in label_kinds(doc, ids) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let mut style = label_style(&spec.label_styles, role); change(&mut style); @@ -437,6 +448,42 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: & changed } +/// Keep a paragraph change made to all of the text of graph labels `ids` (Paragraph, on the whole graph or on labels +/// picked with Group Selection) for every label of their kind, as [`capture_label_styles`] does for character +/// formats. Returns whether kept attributes changed, or the error `change` returns for the kept attributes. +pub(crate) fn capture_label_paragraphs( + doc: &mut Document, + ids: &[NodeId], + change: &dyn Fn(&mut vectorcraft_doc::ParaStyle) -> Result<()>, +) -> Result { + let mut changed = false; + for (graph, role) in label_kinds(doc, ids) { + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let mut para = label_para(&spec.label_styles, role); + change(&mut para)?; + let slot = match role { + Role::Value => &mut spec.label_styles.values_para, + Role::Category => &mut spec.label_styles.categories_para, + Role::Legend => &mut spec.label_styles.legend_para, + }; + changed |= slot.as_ref() != Some(¶); + *slot = Some(para); + } + Ok(changed) +} + +/// The graphs and kinds of label among `ids`, each once. +fn label_kinds(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role)> { + if ids.is_empty() { + return vec![]; + } + let labels = graph_labels(doc); + let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect(); + kinds.sort_by_key(|(g, r)| (g.0, *r as u8)); + kinds.dedup(); + kinds +} + /// The series a command on graph `id` (of `count` series) applies to: `seriesIndexes`, else, with no `id` param, a /// selection made only of this graph's series (Group Selection). Empty: the whole graph. pub(super) fn picked_series(s: &Session, p: &Value, id: NodeId, count: usize, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 6cb36431e4..90c5612848 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4055,6 +4055,45 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() { assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default()); } +/// An anti-aliasing method given to one category label is kept for every category label when the graph is drawn +/// again, through save and open, and undoes with the change. +#[test] +fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() { + use vectorcraft_doc::text::TypeAntiAlias; + let methods = |s: &Session, id: NodeId| -> Vec<(String, TypeAntiAlias)> { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let mut out = vec![]; + for g in ["Axes", "Legend"] { + for c in group(&n, g).children().unwrap() { + if let NodeKind::Text(t) = &c.kind { + out.push((t.plain_text(), t.anti_alias)); + } + } + } + out + }; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("text.setFormat", &json!({"ids": [c.0], "antiAlias": "strong"})).unwrap(); + label_looks(&mut s, id); + let drawn = methods(&s, id); + let method = |t: &str| drawn.iter().find(|(x, _)| x == t).map(|(_, m)| *m).unwrap(); + assert_eq!((method("Q1"), method("Q3")), (TypeAntiAlias::Strong, TypeAntiAlias::Strong), "every category label: {drawn:?}"); + assert_eq!((method("0"), method("2024")), (TypeAntiAlias::Sharp, TypeAntiAlias::Sharp), "other labels: {drawn:?}"); + // One undo takes the data change back, the next the method and the kept method together. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None); + s.execute("edit.redo", &json!({})).unwrap(); + let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong)); + assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none()); +} + /// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it. #[test] fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() { @@ -4219,3 +4258,163 @@ fn csv_round_trip_keeps_blank_row_in_single_column_graph() { assert!(c.is_empty()); assert_eq!(r, g.cells()); } + +/// Each generated label's text, paragraph attributes and alignment. +fn label_paras(s: &Session, id: NodeId) -> Vec<(String, vectorcraft_doc::ParaStyle)> { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let mut out = vec![]; + for name in ["Axes", "Legend"] { + for c in group(&n, name).children().unwrap() { + if let NodeKind::Text(t) = &c.kind { + out.push((t.plain_text(), t.para.clone())); + } + } + } + out +} + +#[test] +fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() { + use vectorcraft_doc::{Composer, ParaDirection, text::Kashida}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let aligned: Vec<_> = label_paras(&s, id).into_iter().map(|(t, p)| (t, p.justify)).collect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setFormat", &json!({"composer": "singleLine", "kashida": "long", "direction": "rightToLeft", "wordSpacing": [70, 90, 120]})) + .unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let paras = label_paras(&s, id); + assert!(!paras.is_empty()); + for (text, p) in ¶s { + assert_eq!(p.composer, Composer::SingleLine, "{text}"); + assert_eq!(p.kashida, Kashida::Long, "{text}"); + assert_eq!(p.direction, Some(ParaDirection::RightToLeft), "{text}"); + assert_eq!(p.justification.word_spacing, [70.0, 90.0, 120.0], "{text}"); + } + // The graph still aligns each label to its place. + assert_eq!(paras.iter().map(|(t, p)| (t.clone(), p.justify)).collect::>(), aligned); + // One kind of label: only that kind keeps it, also through save and open. + let col = graph(&mut s, "column"); + let v = text_id(&s, col, "Axes", "4"); + s.execute("select.set", &json!({"ids": [v.0]})).unwrap(); + s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap(); + let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + s.execute("select.set", &json!({"ids": [col.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let paras = label_paras(&s, col); + let composer = |t: &str| paras.iter().find(|(x, _)| x == t).unwrap().1.composer; + assert_eq!(composer("0"), Composer::SingleLine, "every value axis number"); + assert_eq!(composer("Q1"), Composer::default(), "category labels as they were"); + assert_eq!(composer("2024"), Composer::default(), "legend labels as they were"); + // Part of a label's text: nothing kept. + let q = text_id(&s, col, "Axes", "Q2"); + s.execute("select.set", &json!({"ids": [q.0]})).unwrap(); + s.execute("text.setFormat", &json!({"kashida": "short", "start": 0, "end": 1})).unwrap(); + s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(label_paras(&s, col).iter().all(|(_, p)| p.kashida == Kashida::default())); + // Spacing that would be out of order in the kept attributes is refused, even when it is in order on the label. + let v = text_id(&s, col, "Axes", "4"); + s.execute("select.set", &json!({"ids": [col.0]})).unwrap(); + s.execute("text.setFormat", &json!({"wordSpacing": [60, 70, 80]})).unwrap(); + s.execute("select.set", &json!({"ids": [v.0]})).unwrap(); + s.execute("text.setFormat", &json!({"wordSpacing": [80, 100, 133], "start": 0, "end": 1})).unwrap(); + assert!(s.execute("text.setFormat", &json!({"wordSpacing": {"min": 90}})).is_err()); + let kept = spec(&s, col).label_styles.values_para.unwrap(); + assert_eq!(kept.justification.word_spacing, [60.0, 70.0, 80.0]); +} + +#[test] +fn a_legend_across_top_spaces_its_labels_by_their_kept_paragraph_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap(); + let l = text_id(&s, id, "Legend", "2024"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"leftIndent": 40})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "2024")).unwrap(); + let label = label.geometric_bounds().unwrap(); + let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap(); + assert!(next.x0 >= label.x1, "the next swatch starts after the indented label: {label:?} {next:?}"); +} + +#[test] +fn a_legend_label_with_a_kept_negative_indent_stays_clear_of_its_swatch() { + for across_top in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("graph.setType", &json!({"legendAcrossTop": across_top})).unwrap(); + let l = text_id(&s, id, "Legend", "2025"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"leftIndent": -40})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let bounds = |text: &str| { + let label = + group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap(); + label.geometric_bounds().unwrap() + }; + let (first, label) = (bounds("2024"), bounds("2025")); + let swatch = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap(); + assert!(label.x0 >= swatch.x1, "the label starts after its swatch (across top: {across_top}): {swatch:?} {label:?}"); + if across_top { + assert!(swatch.x0 >= first.x1, "the swatch starts after the label before it: {first:?} {swatch:?}"); + } + } +} + +#[test] +fn a_legend_makes_room_for_the_kept_leading_of_its_labels() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",20|24,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let l = text_id(&s, id, "Legend", "20\n24"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let bounds = |text: &str| { + let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap(); + label.geometric_bounds().unwrap() + }; + let (first, next) = (bounds("20\n24"), bounds("2025")); + assert!(next.y0 >= first.y1, "the next legend label starts below the first one: {first:?} {next:?}"); +} + +#[test] +fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,20|25\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let l = text_id(&s, id, "Legend", "20\n25"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"spaceBefore": -60})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let bounds = |text: &str| { + let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap(); + label.geometric_bounds().unwrap() + }; + let (first, next) = (bounds("2024"), bounds("20\n25")); + assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}"); +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 04b1ce6857..77bd4e4c13 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment)", has_doc, set_format ), @@ -786,6 +786,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { } }; s.edit("Character", |d, _| { + // The paragraph change, for the graph labels to keep. + let mut para_change = None; + let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; let baseline_shift = num("baselineShift").map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose()?; @@ -794,7 +797,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let tcy = (local(tcy_up_down)?, local(tcy_left_right)?); super::typecmd::style_chars(t, range, |st| chars(st, baseline_shift, h_scale, tcy)); let span = super::typecmd::para_span(range, t); - t.edit_paras(span, |para| { + let paras = |para: &mut vectorcraft_doc::ParaStyle, out_of_order: &mut Option<&'static str>| { if let Some(v) = num("leftIndent") { para.left_indent = v.clamp(-MAX_PARA, MAX_PARA); } @@ -882,17 +885,27 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = composer { para.composer = v; } - }); + }; + t.edit_paras(span, |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { - return Err(bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); + return Err(out_of_order_error(name)); } super::typecmd::refresh_bounds(t); + para_change = Some(paras); } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); let scale = num("hScale").map(|v| v.clamp(1.0, 10000.0)); super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right))); + if let Some(paras) = para_change { + // The kept attributes are checked too: they may differ from the labels'. + super::graph::capture_label_paragraphs(d, &ids, &|para| { + let mut out_of_order = None; + paras(para, &mut out_of_order); + out_of_order.map_or(Ok(()), |name| Err(out_of_order_error(name))) + })?; + } } if let Some(v) = anti_alias { for id in &ids { @@ -900,6 +913,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { t.anti_alias = v; } } + // Graph labels keep the method through the graph being drawn again. + super::graph::capture_label_anti_alias(d, &ids, v); } Ok(()) })?; diff --git a/docs/mcp.md b/docs/mcp.md index 19f16205cd..5ab211dcb9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -595,6 +595,12 @@ not store a series' paint. An `appearance.*` command or `graphicStyle.apply` giv `graphicStyle.redefine` on a series group linked to the style, edit the group's own rows, and the graph does not store them. +`text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes +it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that +kind takes them when the graph is drawn again. The graph saves the paragraph attributes as `valuesPara`, +`categoriesPara` and `legendPara` in its label styles, and still sets each label's alignment for its place. The legend +leaves room for a legend label's stored indents, spacing and leading. + `effect.apply {"effect": "path.outlineObject"}` (Effect › Path › Outline Object) takes no parameters. Type that carries it is drawn, exported and expanded as its glyph outlines and stays editable type, and the effects after it reshape those outlines. On paths, compound paths and images it does not change what is drawn. @@ -6758,6 +6764,9 @@ With Preferences › General › Anti-aliased Artwork off, the canvas draws all so does an export whose own Anti-aliasing option is None. SVG, PDF and EPS export draw the type unchanged. The native document such a file carries (an EPS VectorCraft wrote, or an SVG or PDF saved with Preserve Editing) keeps each frame's method, and opening the file restores it. +A graph label given a method keeps it for every label of its kind (value axis numbers, category labels or legend +labels) when the graph is drawn again; the graph saves it as `valuesAntiAlias`, `categoriesAntiAlias` or +`legendAntiAlias` in its label styles. Reset Panel sets Sharp. Saved as `antiAlias` only when not `sharp`. One undo step. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8fc74c474..0b7c778495 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -957,7 +957,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. @@ -1115,7 +1115,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. - The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. + The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes: the grid lists the alternate glyphs of the character selected with the Type tool, and a double-click draws that character with the glyph as one undo step (`text.glyphAlternates`, `text.setGlyphAlternate`). The alternates come from the font's `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. The text keeps the character, native files keep the choice with the face it was made in, and type set in another font or version draws the default glyph. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. From 99b7fb0ab8471a0c70f99be059a820d3627ecd15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 23:58:23 -0800 Subject: [PATCH 47/83] Appearance: aligned Remove Item and Duplicate Item keep the active row After an aligned Remove Item or Duplicate Item, the active row was re-pointed by the indices of the first object in paint order. When the first selected object paints above the others, its own rows that changed are different ones, so the active row could be dropped or land on the wrong row, and a later paint edit changed that row instead. The active row now follows the rows removed or copied in the first selected object's own stack. Follows #5591. --- crates/engine/src/cmd/appearance.rs | 9 +++++++-- crates/engine/src/tests/appearance.rs | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 45b23a0cb1..024358adfe 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -939,7 +939,10 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted)) })?; - s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count())); + // The rows removed from the active row's object, which need not come first in `ids`. + let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + let gone = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx); + s.remap_appearance_item(&ids, |a| (!gone.contains(&a)).then(|| a - gone.iter().filter(|i| **i < a).count())); ok() } @@ -1023,10 +1026,12 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { // Rows at or above each copy move up by one (by the block, for copies placed at `to`). let m = idx.len(); let landed = active_at.or(first_at); + // The rows copied in the active row's object, which need not come first in `ids`. + let copied = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx); s.remap_appearance_item(&ids, |a| { Some(match to { Some(_) => a + if landed.is_some_and(|at| at <= a) { m } else { 0 }, - None => a + idx.iter().filter(|i| **i < a).count(), + None => a + copied.iter().filter(|i| **i < a).count(), }) }); ok() diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 8d70237276..8d12c83719 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -647,6 +647,28 @@ fn edits_change_the_active_row_of_the_first_selected_object() { assert!(!e.contains("internal error"), "{e}"); } +/// After an aligned Remove Item or Duplicate Item, the active row follows the rows that changed in +/// the first selected object, also when that object paints above the others. +#[test] +fn aligned_remove_and_duplicate_keep_the_active_row_of_the_first_selected_object() { + let mut s = session(); + let (_, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); // b's red fill + // a's row 0 is b's white fill, row 1, so b's red fill stays at row 0. + run(&mut s, "appearance.removeItem", json!({"indices": [0], "aligned": true})); + assert_eq!(node(&s, b).appearance.items.len(), 2); + assert_eq!(s.appearance_item(), Some(0)); + assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#ff0000"); + + let mut s = session(); + let (_, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); // b's white fill, a's row 0 + // The copy goes above b's white fill, at 2; the active row stays on the original. + run(&mut s, "appearance.duplicateItem", json!({"indices": [0], "aligned": true})); + assert_eq!(node(&s, b).appearance.items.len(), 4); + assert_eq!(s.appearance_item(), Some(1)); +} + /// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is, /// also when the objects painted after it already have effects there. #[test] From cc2ec8f292547a03ec458c100cf3e4cab9decee3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:00:48 -0800 Subject: [PATCH 48/83] =?UTF-8?q?Scripts:=20a=20script=20chosen=20from=20F?= =?UTF-8?q?ile=20=E2=80=BA=20Scripts=20reads=20its=20#include=20files=20an?= =?UTF-8?q?d=20runs=20$.evalFile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Scripts ran an installed script as source text, so the run had no file: an #include line ended it with "script file read refused", and $.evalFile was refused too. The menu now checks the script as before and runs it with script.run {path}, as docs/mcp.md describes, so its included files and the files $.evalFile runs are read beside it. --- crates/ui-egui/src/scripts_menu.rs | 7 ++++--- crates/ui-egui/src/tests/scripts_menu.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index e62a5d8874..9c890d5c39 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -242,13 +242,14 @@ pub fn readable(p: &Value) -> bool { } /// `ui.runInstalledScript {path}`: run the listed script at `path`. A script that is no longer in -/// the folder is not run, and the folder is read again. +/// the folder is not run, and the folder is read again. The script runs from its file, so its +/// `#include` lines and `$.evalFile` read beside it. pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; - let source = app.session.installed_script(path).map_err(|e| { + app.session.installed_script(path).map_err(|e| { let ctx = app.ui_ctx.clone(); refresh(app, ctx.as_ref()); e.to_string() })?; - app.run("script.run", json!({"source": source, "name": vectorcraft_engine::cmd::fileio::file_name(path)})) + app.run("script.run", json!({ "path": path })) } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 3dc66acca2..751bd528a6 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -142,6 +142,20 @@ fn a_script_runs_its_own_file_whatever_its_name_ends_with() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_listed_script_reads_its_included_files_and_runs_files_beside_it() { + let dir = folder("include"); + let mut app = app(&dir); + write(&dir, "lib/two.jsxinc", DRAW); + write(&dir, "lib/one.js", "vc.run('shape.rectangle', {x:40,y:0,width:10,height:10});"); + let main = write(&dir, "Main.jsx", "#include \"lib/two.jsxinc\"\n$.evalFile('lib/one.js');\n"); + read(&app); + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": main })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 3, "{}", app.ui.status); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn script_and_folder_names_are_shown_as_they_are_in_every_language() { let dir = folder("language"); From 668465042537856589a4f62d7a2e761abfe6b916 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:01:48 -0800 Subject: [PATCH 49/83] Reshape: an empty focal list cannot be combined with radius path.reshape refused focal with radius only when focal named an anchor. Since an empty focal list chooses the focal-point rule, a call with "focal": [] and a radius was accepted and used the radius falloff, although the params text and docs/mcp.md say the two cannot be used together. Any focal other than null now goes with radius as an error. --- crates/engine/src/cmd/path.rs | 3 ++- crates/engine/src/tests.rs | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 7d7d635c94..d00ba7192c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1578,7 +1578,8 @@ fn reshape(s: &mut Session, p: &Value) -> Result { Some(v) if v.is_array() => super::select::checked_refs(Some(v), "path.reshape")?.into_iter().collect(), Some(_) => return Err(bad("path.reshape", "`focal` must be an array of [subpath, anchor] pairs")), }; - if radius.is_some() && !focal.is_empty() { + // An empty `focal` chooses the focal-point rule too. + if radius.is_some() && !matches!(p.get("focal"), None | Some(Value::Null)) { return Err(bad("path.reshape", "`focal` and `radius` cannot be used together")); } // A step that names neither `focal` nor `radius` (as the Reshape tool recorded one before it diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5021c879f8..9ad6718436 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3622,9 +3622,12 @@ fn reshape_refuses_a_focal_point_that_is_not_an_anchor() { } assert_eq!(reshape_anchors(&s, id), before); let steps = s.doc().unwrap().history.undo.len(); - let e = - s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": [[0, 2]], "radius": 50.0})).unwrap_err(); - assert!(e.to_string().contains("`focal` and `radius` cannot be used together"), "{e}"); + // An empty `focal` chooses the focal-point rule too, so it cannot go with `radius` either. + for focal in [json!([[0, 2]]), json!([])] { + let e = + s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal, "radius": 50.0})).unwrap_err(); + assert!(e.to_string().contains("`focal` and `radius` cannot be used together"), "{focal}: {e}"); + } assert_eq!(reshape_anchors(&s, id), before); assert_eq!(s.doc().unwrap().history.undo.len(), steps); } From c09e1d3ebedbce1e08ce2c723a13734f17914a89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:33:28 -0800 Subject: [PATCH 50/83] Scripts: closing the quit question when the script it asked about has ended A window-close request while a script waits at its alert, confirm or prompt opens the quit question over that dialog, and Cancel shows the script's dialog again. When the run then ended another way (script.stop, or the run finishing), the quit question stayed open, and Cancel showed a dialog for a script that was no longer running. The running-script poll now closes the quit question once the run ends, and forgets the script's dialog under it once the run no longer waits at that dialog. --- crates/ui-egui/src/dialogs/script_run.rs | 16 +++++++++++++ crates/ui-egui/src/script_runs.rs | 2 ++ crates/ui-egui/src/tests/script_dialogs.rs | 26 ++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index eb89bd174d..8f5e3b1093 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -182,6 +182,22 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { app.ui.dialog = Some(Dialog::new(CLOSE_KIND, fields)); } +/// Closes the question quitting asks once the run it asks about has ended, and forgets the +/// script's dialog it was asked over once the run no longer waits at that dialog, so Cancel does +/// not show it again. +pub(crate) fn settle_close(app: &mut VectorcraftApp) { + if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == CLOSE_KIND) { + return; + } + if !app.session.script_running() { + app.ui.dialog = None; + } else if app.session.script_dialog().is_none() + && let Some(d) = app.ui.dialog.as_mut() + { + d.fields.remove(super::PARENT); + } +} + /// Shows the dialog the running script waits at. pub(crate) fn open_notice(app: &mut VectorcraftApp, d: &ScriptDialog) { let fields = json!({ diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 65a9dc9eb6..02c2229741 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -15,6 +15,7 @@ pub fn poll(app: &mut VectorcraftApp) { if !app.session.script_running() { return; } + script_run::settle_close(app); if ask(app) { return; } @@ -31,6 +32,7 @@ pub fn poll(app: &mut VectorcraftApp) { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { app.ui.dialog = None; } + script_run::settle_close(app); match result { Ok(_) => app.status(format!("Ran {name}")), Err(e) => failed(app, e.to_string()), diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index da09c777ba..b3750001a4 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -220,6 +220,32 @@ fn close_while_notification_waits_abandons_or_resumes() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn close_question_ends_with_a_run_stopped_another_way() { + let mut app = app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + assert!(app.ui.dialog.is_none(), "the question about a run that has ended closes"); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none(), "Cancel does not show the stopped script's dialog again"); + assert_eq!(objects(&app), 0); + // Asked to stop, the run no longer waits at its dialog before its next slice ends it. + let mut app = self::app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + dialogs::script_run::ask_to_close(&mut app); + app.run("script.stop", json!({})).unwrap(); + dialogs::script_run::settle_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND, "the run has not ended yet"); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none(), "Cancel does not show a dialog the run no longer waits at"); +} + #[test] fn notification_layout_with_long_text_and_small_window() { let mut app = app(); From 50bf4fc5a3d0d2967e28b0925d6259e870508ae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabio=20William=20Concei=C3=A7=C3=A3o?= Date: Tue, 10 Nov 2026 16:07:36 +0000 Subject: [PATCH 51/83] G5: built-in Inventory Icons symbol library --- crates/engine/src/cmd/symbollib.rs | 63 +++++++++++++++++++ crates/engine/src/tests/symbollib.rs | 32 +++++++++- crates/ui-egui/src/i18n/bg.tsv | 6 ++ crates/ui-egui/src/i18n/bs.tsv | 6 ++ crates/ui-egui/src/i18n/ca.tsv | 6 ++ crates/ui-egui/src/i18n/cs.tsv | 6 ++ crates/ui-egui/src/i18n/da.tsv | 6 ++ crates/ui-egui/src/i18n/de.tsv | 6 ++ crates/ui-egui/src/i18n/el.tsv | 6 ++ crates/ui-egui/src/i18n/es.tsv | 6 ++ crates/ui-egui/src/i18n/fi.tsv | 6 ++ crates/ui-egui/src/i18n/fr.tsv | 6 ++ crates/ui-egui/src/i18n/hi.tsv | 6 ++ crates/ui-egui/src/i18n/hu.tsv | 6 ++ crates/ui-egui/src/i18n/id.tsv | 6 ++ crates/ui-egui/src/i18n/it.tsv | 6 ++ crates/ui-egui/src/i18n/ja.tsv | 6 ++ crates/ui-egui/src/i18n/ka.tsv | 6 ++ crates/ui-egui/src/i18n/ko.tsv | 6 ++ crates/ui-egui/src/i18n/nl.tsv | 6 ++ crates/ui-egui/src/i18n/pl.tsv | 6 ++ crates/ui-egui/src/i18n/pt-br.tsv | 6 ++ crates/ui-egui/src/i18n/ru.tsv | 6 ++ crates/ui-egui/src/i18n/sv.tsv | 6 ++ crates/ui-egui/src/i18n/tr.tsv | 6 ++ crates/ui-egui/src/i18n/uk.tsv | 6 ++ crates/ui-egui/src/i18n/vi.tsv | 6 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 6 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 6 ++ .../src/panels/tests_symbol_libraries.rs | 2 +- docs/gaps.md | 13 ++-- docs/roadmap.md | 5 +- docs/target-app-parity.md | 13 ++-- 33 files changed, 274 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index fe3f1149da..c757d93ea7 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -158,6 +158,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }, BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames }, BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers }, + BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons }, ]; /// Built-in library `id`, made once. @@ -249,6 +250,68 @@ fn map_markers() -> SymbolLibrary { SymbolLibrary { name: "Map Markers".into(), doc } } +/// Inventory Icons: sword, shield, potion, key and gem for loot/RPG art (original, no 9-slice). +fn inventory_icons() -> SymbolLibrary { + let c = Point::ZERO; + let sword = [ + (0.0, -22.0), + (3.0, -10.0), + (3.0, 6.0), + (8.0, 8.0), + (8.0, 12.0), + (3.0, 12.0), + (3.0, 20.0), + (-3.0, 20.0), + (-3.0, 12.0), + (-8.0, 12.0), + (-8.0, 8.0), + (-3.0, 6.0), + (-3.0, -10.0), + ]; + let shield = [(0.0, -20.0), (16.0, -12.0), (14.0, 8.0), (0.0, 20.0), (-14.0, 8.0), (-16.0, -12.0)]; + let potion = + [(-4.0, -20.0), (4.0, -20.0), (4.0, -12.0), (10.0, -6.0), (12.0, 6.0), (8.0, 18.0), (-8.0, 18.0), (-12.0, 6.0), (-10.0, -6.0), (-4.0, -12.0)]; + let key = [ + (-4.0, -18.0), + (4.0, -18.0), + (6.0, -14.0), + (6.0, -8.0), + (4.0, -6.0), + (4.0, 16.0), + (8.0, 16.0), + (8.0, 20.0), + (-2.0, 20.0), + (-2.0, 12.0), + (0.0, 12.0), + (0.0, -6.0), + (-4.0, -8.0), + (-6.0, -14.0), + ]; + let sword: Vec = sword.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let shield: Vec = shield.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let potion: Vec = potion.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let key: Vec = key.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let icons = [ + ("Sword", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&sword, true)), "#95a5a6"), + ("Shield", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&shield, true)), "#3498db"), + ("Potion", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&potion, true)), "#9b59b6"), + ("Key", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&key, true)), "#f1c40f"), + ("Gem", shapes::polygon(c, 16.0, 6, 0.0), "#1abc9c"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, path, hex) in icons { + let fill = Color::from_hex(hex).unwrap_or(Color::BLACK); + let edge = fill.lerp(&Color::BLACK, 0.35); + let id = doc.alloc_id(); + let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + } + doc.title = "Inventory Icons".into(); + SymbolLibrary { name: "Inventory Icons".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 410bd473da..febc220296 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 3, "{libs:?}"); + assert_eq!(libs.len(), 4, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), @@ -94,6 +94,10 @@ fn the_builtin_library_is_original_art_generated_in_code() { (libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()), (Some("map-markers"), Some("Map Markers"), Some("builtIn")) ); + assert_eq!( + (libs[3]["id"].as_str(), libs[3]["name"].as_str(), libs[3]["category"].as_str()), + (Some("inventory-icons"), Some("Inventory Icons"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -129,6 +133,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() { )); } +#[test] +fn inventory_icons_symbols_add_without_nine_slice() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "inventory-icons"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Sword", "Shield", "Potion", "Key", "Gem"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "inventory-icons", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for name in &names { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Sword" + )); +} + #[test] fn map_markers_symbols_add_without_nine_slice() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 602bc20a7c..2d49498798 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5891,6 +5891,12 @@ axis Y Axis Y ос Flag Флаг Crosshair Мерник Checkpoint Контролна точка + Inventory Icons Икони на инвентара + Sword Меч + Shield Щит + Potion Отвара + Key Ключ + Gem Скъпоценен камък Open Symbol Library Отваряне на библиотека със символи Save Symbol Library Запазване на библиотека със символи Save Symbol Library… Запази библиотека със символи… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9dda9c2c98..912eec6a6f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5935,6 +5935,12 @@ axis Y Axis Y osa Flag Zastava Crosshair Nišan Checkpoint Kontrolna tačka + Inventory Icons Ikone inventara + Sword Mač + Shield Štit + Potion Napitak + Key Ključ + Gem Dragulj Open Symbol Library Otvori biblioteku simbola Save Symbol Library Sačuvaj biblioteku simbola Save Symbol Library… Sačuvaj biblioteku simbola… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 85ceed05f6..f12bb4a6ab 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -455,6 +455,12 @@ antiAlias Sharp Nítid Flag Bandera Crosshair Punt de mira Checkpoint Punt de control + Inventory Icons Icones d’inventari + Sword Espasa + Shield Escut + Potion Poció + Key Clau + Gem Gemm Batch Lot Batch… Lot… Bearing Orientació diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4fbbd523f4..6d7965acd3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6119,6 +6119,12 @@ axis Y Axis osa Y Flag Vlajka Crosshair Zaměřovač Checkpoint Kontrolní bod + Inventory Icons Ikony inventáře + Sword Meč + Shield Štít + Potion Lektvar + Key Klíč + Gem Drahokam Open Symbol Library Otevřít knihovnu symbolů Save Symbol Library Uložit knihovnu symbolů Save Symbol Library… Uložit knihovnu symbolů… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 15ce8a99ff..53036e9dda 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5906,6 +5906,12 @@ axis Y Axis Y-akse Flag Flag Crosshair Sigtekorn Checkpoint Kontrolpunkt + Inventory Icons Inventarikoner + Sword Sværd + Shield Skjold + Potion Eliksir + Key Nøgle + Gem Ædelsten Open Symbol Library Åbn symbolbibliotek Save Symbol Library Gem symbolbibliotek Save Symbol Library… Gem symbolbibliotek… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b60b622165..e46a1b6ea2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5702,6 +5702,12 @@ axis Y Axis Y-Achse Flag Flagge Crosshair Fadenkreuz Checkpoint Kontrollpunkt + Inventory Icons Inventar-Symbole + Sword Schwert + Shield Schild + Potion Trank + Key Schlüssel + Gem Edelstein Open Symbol Library Symbol-Bibliothek öffnen Save Symbol Library Symbol-Bibliothek speichern Save Symbol Library… Symbol-Bibliothek speichern… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c2145c61c7..98015264e0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6070,6 +6070,12 @@ axis Y Axis Άξονας Y Flag Σημαία Crosshair Σταυρόνημα Checkpoint Σημείο ελέγχου + Inventory Icons Εικονίδια αποθέματος + Sword Ξίφος + Shield Ασπίδα + Potion Φίλτρο + Key Κλειδί + Gem Πετράδι Open Symbol Library Άνοιγμα βιβλιοθήκης συμβόλων Save Symbol Library Αποθήκευση βιβλιοθήκης συμβόλων Save Symbol Library… Αποθήκευση βιβλιοθήκης συμβόλων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f91e8ac2fc..d5d844b234 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6061,6 +6061,12 @@ axis Y Axis Eje Y Flag Bandera Crosshair Punto de mira Checkpoint Punto de control + Inventory Icons Iconos de inventario + Sword Espada + Shield Escudo + Potion Poción + Key Llave + Gem Gema Open Symbol Library Abrir biblioteca de símbolos Save Symbol Library Guardar biblioteca de símbolos Save Symbol Library… Guardar biblioteca de símbolos… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a8b2062d75..85b49e77e5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6149,6 +6149,12 @@ axis Y Axis Y-akseli Flag Lippu Crosshair Tähtäin Checkpoint Tarkastuskohta + Inventory Icons Inventaarioikonit + Sword Miekka + Shield Kilpi + Potion Taikajuoma + Key Avain + Gem Jalokivi Open Symbol Library Avaa symbolikirjasto Save Symbol Library Tallenna symbolikirjasto Save Symbol Library… Tallenna symbolikirjasto… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 37fb556c60..43eb6d7579 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6114,6 +6114,12 @@ axis Y Axis Axe Y Flag Drapeau Crosshair Réticule Checkpoint Point de contrôle + Inventory Icons Icônes d’inventaire + Sword Épée + Shield Bouclier + Potion Potion + Key Clé + Gem Gemme Open Symbol Library Ouvrir une bibliothèque de symboles Save Symbol Library Enregistrer la bibliothèque de symboles Save Symbol Library… Enregistrer la bibliothèque de symboles… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1b8eb92c6b..796939065c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -526,6 +526,12 @@ antiAlias Sharp शार्प Flag झंडा Crosshair क्रॉसहेयर Checkpoint चेकपॉइंट + Inventory Icons इन्वेंटरी आइकन + Sword तलवार + Shield ढाल + Potion औषधि + Key कुंजी + Gem रत्न Batch बैच Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7884c05f6b..ec7d13a8c0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6102,6 +6102,12 @@ axis Y Axis Y tengely Flag Zászló Crosshair Célkereszt Checkpoint Ellenőrzőpont + Inventory Icons Leltári ikonok + Sword Kard + Shield Pajzs + Potion Bájital + Key Kulcs + Gem Drágakő Open Symbol Library Szimbólumkönyvtár megnyitása Save Symbol Library Szimbólumkönyvtár mentése Save Symbol Library… Szimbólumkönyvtár mentése… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4de51c5496..45d30eb0f0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5906,6 +5906,12 @@ axis Y Axis Sumbu Y Flag Bendera Crosshair Bidik silang Checkpoint Pos pemeriksaan + Inventory Icons Ikon Inventaris + Sword Pedang + Shield Perisai + Potion Ramuan + Key Kunci + Gem Permata Open Symbol Library Buka pustaka simbol Save Symbol Library Simpan pustaka simbol Save Symbol Library… Simpan pustaka simbol… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index dc8dc1faf5..419cf05828 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5736,6 +5736,12 @@ axis Y Axis Asse Y Flag Bandiera Crosshair Mirino Checkpoint Punto di controllo + Inventory Icons Icone inventario + Sword Spada + Shield Scudo + Potion Pozione + Key Chiave + Gem Gemma Open Symbol Library Apri libreria simboli Save Symbol Library Salva libreria simboli Save Symbol Library… Salva libreria simboli… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8935be5296..effd2a9000 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5801,6 +5801,12 @@ axis Y Axis Y 軸 Flag 旗 Crosshair クロスヘア Checkpoint チェックポイント + Inventory Icons インベントリアイコン + Sword 剣 + Shield 盾 + Potion ポーション + Key 鍵 + Gem 宝石 Open Symbol Library シンボルライブラリを開く Save Symbol Library シンボルライブラリを保存 Save Symbol Library… シンボルライブラリを保存… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 64f744b884..e1b2fceef6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6042,6 +6042,12 @@ axis Y Axis Y ღერძი Flag დროშა Crosshair სამიზნე Checkpoint საკონტროლო წერტილი + Inventory Icons ინვენტარის ხატულები + Sword მახვილი + Shield ფარი + Potion წამალი + Key გასაღები + Gem ძვირფასი ქვა Open Symbol Library სიმბოლოების ბიბლიოთეკის გახსნა Save Symbol Library სიმბოლოების ბიბლიოთეკის შენახვა Save Symbol Library… სიმბოლოების ბიბლიოთეკის შენახვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 88adb5a86b..2fa677459f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5697,6 +5697,12 @@ axis Y Axis Y축 Flag 깃발 Crosshair 십자선 Checkpoint 체크포인트 + Inventory Icons 인벤토리 아이콘 + Sword 검 + Shield 방패 + Potion 포션 + Key 열쇠 + Gem 보석 Open Symbol Library 심볼 라이브러리 열기 Save Symbol Library 심볼 라이브러리 저장 Save Symbol Library… 심볼 라이브러리 저장… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ffced05d3c..10c923cd6e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5957,6 +5957,12 @@ axis Y Axis Y-as Flag Vlag Crosshair Vizier Checkpoint Controlepunt + Inventory Icons Inventarisiconen + Sword Zwaard + Shield Schild + Potion Drank + Key Sleutel + Gem Edelsteen Open Symbol Library Symboolbibliotheek openen Save Symbol Library Symboolbibliotheek opslaan Save Symbol Library… Symboolbibliotheek opslaan… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d73f5ca7e3..a4f8580ff5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5973,6 +5973,12 @@ axis Y Axis Oś Y Flag Flaga Crosshair Celownik Checkpoint Punkt kontrolny + Inventory Icons Ikony ekwipunku + Sword Miecz + Shield Tarcza + Potion Mikstura + Key Klucz + Gem Klejnot Open Symbol Library Otwórz bibliotekę symboli Save Symbol Library Zapisz bibliotekę symboli Save Symbol Library… Zapisz bibliotekę symboli… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1cbf595ae9..2496b775e5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6034,6 +6034,12 @@ axis Y Axis Eixo Y Flag Bandeira Crosshair Mira Checkpoint Ponto de verificação + Inventory Icons Ícones de inventário + Sword Espada + Shield Escudo + Potion Poção + Key Chave + Gem Gema Open Symbol Library Abrir Biblioteca de Símbolos Save Symbol Library Salvar Biblioteca de Símbolos Save Symbol Library… Salvar Biblioteca de Símbolos… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 53f1707a79..5f34c30eca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5730,6 +5730,12 @@ axis Y Axis Ось Y Flag Флаг Crosshair Прицел Checkpoint Контрольная точка + Inventory Icons Иконки инвентаря + Sword Меч + Shield Щит + Potion Зелье + Key Ключ + Gem Самоцвет Open Symbol Library Открыть библиотеку символов Save Symbol Library Сохранить библиотеку символов Save Symbol Library… Сохранить библиотеку символов… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3a62522958..aab2451073 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6142,6 +6142,12 @@ axis Y Axis Y-axel Flag Flagga Crosshair Hårkors Checkpoint Kontrollpunkt + Inventory Icons Inventarieikoner + Sword Svärd + Shield Sköld + Potion Dryck + Key Nyckel + Gem Ädelsten Open Symbol Library Öppna symbolbibliotek Save Symbol Library Spara symbolbibliotek Save Symbol Library… Spara symbolbibliotek… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9e5300b238..12e5a14e33 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6075,6 +6075,12 @@ axis Y Axis Y ekseni Flag Bayrak Crosshair Nişangah Checkpoint Kontrol noktası + Inventory Icons Envanter Simgeleri + Sword Kılıç + Shield Kalkan + Potion İksir + Key Anahtar + Gem Mücevher Open Symbol Library Sembol Kitaplığını Aç Save Symbol Library Sembol Kitaplığını Kaydet Save Symbol Library… Sembol Kitaplığını Kaydet… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 053be196bb..a7854dc666 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5716,6 +5716,12 @@ axis Y Axis Вісь Y Flag Прапор Crosshair Приціл Checkpoint Контрольна точка + Inventory Icons Піктограми інвентарю + Sword Меч + Shield Щит + Potion Зілля + Key Ключ + Gem Самоцвіт Open Symbol Library Відкрити бібліотеку символів Save Symbol Library Зберегти бібліотеку символів Save Symbol Library… Зберегти бібліотеку символів… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7e2989339f..ce683ff038 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5717,6 +5717,12 @@ axis Y Axis Trục Y Flag Cờ Crosshair Tâm ngắm Checkpoint Điểm kiểm tra + Inventory Icons Biểu tượng túi đồ + Sword Kiếm + Shield Khiên + Potion Thuốc + Key Chìa khóa + Gem Ngọc Open Symbol Library Mở thư viện ký hiệu Save Symbol Library Lưu thư viện ký hiệu Save Symbol Library… Lưu thư viện ký hiệu… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 14be622f9b..91d0e4e747 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5957,6 +5957,12 @@ axis Y Axis Y 轴 Flag 旗帜 Crosshair 准星 Checkpoint 检查点 + Inventory Icons 物品栏图标 + Sword 剑 + Shield 盾 + Potion 药水 + Key 钥匙 + Gem 宝石 Open Symbol Library 打开符号库 Save Symbol Library 保存符号库 Save Symbol Library… 保存符号库… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f111796d4c..3993771016 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5754,6 +5754,12 @@ axis Y Axis Y 軸 Flag 旗幟 Crosshair 準星 Checkpoint 檢查點 + Inventory Icons 物品欄圖示 + Sword 劍 + Shield 盾 + Potion 藥水 + Key 鑰匙 + Gem 寶石 Open Symbol Library 開啟符號資料庫 Save Symbol Library 儲存符號資料庫 Save Symbol Library… 儲存符號資料庫… diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 7dee49df2b..a6c1cb4cb5 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -113,7 +113,7 @@ fn the_window_menu_and_the_symbols_panel_open_symbol_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Symbol Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.symbolLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers"), json!("inventory-icons")]); let has = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(has("window.symbolLibrary.other"), Some(true)); assert_eq!(has("ui.saveSymbolLibrary"), Some(false), "no symbols to save yet"); diff --git a/docs/gaps.md b/docs/gaps.md index 8b6a32a29f..f0619ff213 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -622,9 +622,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol - Libraries Menu open each library in a library panel of its own (three original libraries generated in code, - Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, and Map Markers with Pin, - Flag, Crosshair and Checkpoint; User Defined; Other + Libraries Menu open each library in a library panel of its own (four original libraries generated in code, + Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, Map Markers with Pin, + Flag, Crosshair and Checkpoint, and Inventory Icons with Sword, Shield, Potion, Key and Gem; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click adds a symbol to the document's Symbols with its Symbol Options and the resources it uses, as one undo step, and dragging one onto the canvas also places it; Save Symbols / Save Symbol Library writes the @@ -652,10 +652,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). - **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the seven shipped, and further symbol libraries beyond Basic - Shapes, UI Frames and Map Markers; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; + Shapes, UI Frames, Map Markers and Inventory Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 8–18 h. +- **Estimate:** 7–17 h. ## G3 3D and Materials @@ -854,6 +854,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | | 2026-11-10 | minor | G5: built-in Game HUD graphic style library (Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine, Boss Alert); Missing trimmed; estimate 10–20 → 9–19 h. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 6613ebb220..02e0a61fcd 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -148,7 +148,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, four generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, five generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | @@ -189,6 +189,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | M10/G5: Game HUD built-in graphic style library; estimates unchanged | | 2026-11-10 | minor | M10/G5: Map Markers built-in symbol library (Pin, Flag, Crosshair, Checkpoint); estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8bc235f26..cdcda0f6e6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -222,7 +222,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | @@ -231,7 +231,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -495,7 +495,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -538,7 +538,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~38% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have three (Basic Shapes, UI Frames with default 9-slice, Map Markers), graphic style libraries seven (including Game HUD) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~40% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have four (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons), graphic style libraries seven (including Game HUD) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -796,7 +796,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides) and Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides), Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice) and Inventory Icons (Sword, Shield, Potion, Key and Gem, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. @@ -1963,6 +1963,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | | 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | | 2026-11-10 | minor | Bundled content: built-in Game HUD graphic style library; style libraries evidence updated; ~34% → ~36%; more built-in graphic-style libraries remain. | From 1b47f172c2098b8f16bde5dc98c04cc26c51e28c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabio=20William=20Concei=C3=A7=C3=A3o?= Date: Tue, 10 Nov 2026 16:16:49 +0000 Subject: [PATCH 52/83] G5: list Inventory Icons in the UI parity checklist --- docs/ui-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 38297994fa..a0182867cc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -407,7 +407,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | -| Symbol libraries: Window › Symbol Libraries (Basic Shapes, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; only one built-in library (original, generated in code) | +| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; four built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; four built-in libraries (original, generated in code) | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -507,6 +507,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Symbol libraries: Inventory Icons joins Basic Shapes, UI Frames and Map Markers as a fourth built-in library (Sword, Shield, Potion, Key, Gem; no default 9-slice). | | 2026-11-11 | minor | Files that record no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files, importer plug-ins) open and revert in Preferences › Units › General instead of points; native, SVG and DXF files and `.ai`/EPS ruler units are kept (#5820). Scores and estimates unchanged. | | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | From f23f7ef3211a2fba61950a85bb5f3605bce12b83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabio=20William=20Concei=C3=A7=C3=A3o?= Date: Tue, 10 Nov 2026 19:48:58 +0000 Subject: [PATCH 53/83] G5: list Inventory Icons in the MCP symbol libraries docs --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index d8798c6dfb..9c28fbe5be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2991,7 +2991,8 @@ with the same extension and bytes as one there, loads as that User Defined libra ## Symbol libraries -Symbol libraries are read-only sets of symbols: one generated in code (Basic Shapes), the `.vectorcraft` files in +Symbol libraries are read-only sets of symbols: four generated in code (Basic Shapes, UI Frames, Map Markers, +Inventory Icons), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the symbols of any document loaded with `symbol.loadLibrary`. `symbol.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `symbol.library {library}` returns one's symbols (`name`, `size`, `registration`, `exportType`; `library` is an From da765088a0bbbb849d1e82e1b2cb952902d0d37e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:35:52 -0800 Subject: [PATCH 54/83] Graphs: the legend measures its labels with the document's System Layout The legend measured each label with System Layout off, while the graph draws the labels with the document's setting. With System Layout on, a long legend label could run over the next swatch in Legend Across Top. The legend now measures labels with the same setting. --- crates/engine/src/cmd/graph/generate.rs | 10 ++++----- crates/engine/src/cmd/graph/labels.rs | 27 ++++++++++++++++--------- crates/engine/src/cmd/graph/tests.rs | 27 +++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index 2f16d5e423..a789304b24 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -902,7 +902,7 @@ impl<'a> Plot<'a> { fn legend_label(&mut self, (x, y): (f64, f64), label: &str) -> Arc { let ls = self.ls; - let (dx, dy) = label_shift(&self.g.label_styles, label); + let (dx, dy) = label_shift(&self.g.label_styles, label, self.b.d.setup.system_layout); let (x, y) = (x + dx, y + dy); self.b.label(Role::Legend, Point::new(x + 12.0, y + 7.5 + (ls - LABEL_SIZE) * 0.35), label, Justify::Left, false) } @@ -910,13 +910,13 @@ impl<'a> Plot<'a> { /// Add Legend Across Top: swatch and label after swatch and label, in rows as wide as the plot, the last row /// just above it. fn legend_across_top(&mut self) -> Vec> { - let (g, r, ls) = (self.g, self.r, self.ls); + let (g, r, ls, system_layout) = (self.g, self.r, self.ls, self.b.d.setup.system_layout); let entries: Vec<(usize, String)> = (0..self.legend_series()).map(|s| (s, self.legend_text(s))).filter(|(_, l)| !blank_label(l)).collect(); let mut rows: Vec> = vec![vec![]]; let mut used = 0.0; for (s, label) in entries { - let w = 12.0 + label_width(&g.label_styles, &label) + 12.0; - let h = ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&g.label_styles, &label); + let w = 12.0 + label_width(&g.label_styles, &label, system_layout) + 12.0; + let h = ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&g.label_styles, &label, system_layout); // The gap after an entry may run past the plot's edge. if used + w - 12.0 > r.width() && rows.last().is_some_and(|row| !row.is_empty()) { rows.push(vec![]); @@ -958,7 +958,7 @@ impl<'a> Plot<'a> { y += ls * 1.8; continue; } - y += ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&self.g.label_styles, &label); + y += ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&self.g.label_styles, &label, self.b.d.setup.system_layout); self.legend_swatch(s, (x, row_y)); labels.push(self.legend_label((x, row_y), &label)); } diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 7c01272809..faf301899a 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -188,40 +188,47 @@ pub(super) fn shadow_of(d: &mut Document, n: &Node) -> Arc { Arc::new(d.reid(&c)) } -/// The bounds of legend label `s` set from the origin with paragraph attributes `para`, without adding it to a document. -fn legend_label_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, para: vectorcraft_doc::ParaStyle) -> Option { +/// The bounds of legend label `s` set from the origin with paragraph attributes `para` and the document's System +/// Layout setting `system_layout`, as [`Gen::text`] sets it, without adding it to a document. +fn legend_label_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, para: vectorcraft_doc::ParaStyle, system_layout: bool) -> Option { let style = label_style(styles, Role::Legend); let mut t = TextObject::point(Point::ZERO, &s.replace('|', "\n"), style); t.para = para; t.para.justify = Justify::Left; + t.system_layout = system_layout; refresh_bounds(&mut t); Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds() } /// How far label `s` reaches right of where it starts (its widest line and any indent), after the legend moves it right /// by [`label_shift`], without adding it to a document. -pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 { - legend_label_bounds(styles, s, label_para(styles, Role::Legend)).map_or(0.0, |b| (b.x1 + label_shift(styles, s).0).max(0.0)) +pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 { + legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout) + .map_or(0.0, |b| (b.x1 + label_shift(styles, s, system_layout).0).max(0.0)) } /// The bounds of legend label `s` set with its kept paragraph attributes and with the defaults, when it has kept ones. -fn kept_and_default_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str) -> Option<(Rect, Rect)> { +fn kept_and_default_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> Option<(Rect, Rect)> { styles.legend_para.as_ref()?; - Some((legend_label_bounds(styles, s, label_para(styles, Role::Legend))?, legend_label_bounds(styles, s, vectorcraft_doc::ParaStyle::default())?)) + Some(( + legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout)?, + legend_label_bounds(styles, s, vectorcraft_doc::ParaStyle::default(), system_layout)?, + )) } /// How much further left and further up legend label `s` reaches with its kept paragraph attributes than with the /// defaults (a negative indent or negative spacing), so the legend moves it right and down by that much and it stays /// clear of its swatch and of the entries before it. -pub(super) fn label_shift(styles: &vectorcraft_doc::LabelStyles, s: &str) -> (f64, f64) { - kept_and_default_bounds(styles, s).map_or((0.0, 0.0), |(kept, default)| ((default.x0 - kept.x0).max(0.0), (default.y0 - kept.y0).max(0.0))) +pub(super) fn label_shift(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> (f64, f64) { + kept_and_default_bounds(styles, s, system_layout) + .map_or((0.0, 0.0), |(kept, default)| ((default.x0 - kept.x0).max(0.0), (default.y0 - kept.y0).max(0.0))) } /// How much further down legend label `s` reaches with its kept paragraph attributes than with the defaults (more /// leading, or space before or after), after the legend moves it down by [`label_shift`], so the legend makes room /// for it. -pub(super) fn label_extra_height(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 { - kept_and_default_bounds(styles, s).map_or(0.0, |(kept, default)| (kept.y1 + (default.y0 - kept.y0).max(0.0) - default.y1).max(0.0)) +pub(super) fn label_extra_height(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 { + kept_and_default_bounds(styles, s, system_layout).map_or(0.0, |(kept, default)| (kept.y1 + (default.y0 - kept.y0).max(0.0) - default.y1).max(0.0)) } /// A label with nothing to show (empty, or only `|` line breaks). diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 90c5612848..c5316e765c 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4344,6 +4344,33 @@ fn a_legend_across_top_spaces_its_labels_by_their_kept_paragraph_settings() { assert!(next.x0 >= label.x1, "the next swatch starts after the indented label: {label:?} {next:?}"); } +#[test] +fn a_legend_across_top_measures_its_labels_with_system_layout() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("type.systemLayout", &json!({"on": true})).unwrap(); + // Each `i` at 2 pt advances a whole point with System Layout, far more than its own width. + let name = "i".repeat(60); + let csv = format!(",{name},2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"); + let id = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap(); + let l = text_id(&s, id, "Legend", &name); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 2})).unwrap(); + s.execute("text.setFormat", &json!({"leftIndent": 1})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == name)).unwrap(); + let label = label.geometric_bounds().unwrap(); + let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap(); + assert!(next.x0 >= label.x1, "the next swatch starts after the label set with System Layout: {label:?} {next:?}"); +} + #[test] fn a_legend_label_with_a_kept_negative_indent_stays_clear_of_its_swatch() { for across_top in [true, false] { From ba5eab7349e02277096b0b5e3fc70d3485e260a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:36:07 -0800 Subject: [PATCH 55/83] Docs: Edit Symbol keeps dynamic symbol instances linked The Dynamic symbols entry still said Edit Symbol expands the symbol's own art. Since #5064, Edit Symbol opens symbol editing mode: every instance stays linked and a dynamic symbol's instances keep their changes for the objects the edited art still has. --- 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 a8bc235f26..2103ed6243 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1896,7 +1896,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Dynamic symbols (2026-11-01) -Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. +Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol keeps the instances linked and keeps each change whose object the edited art still has; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. ## Document Tools add-on: Export All Open Documents (2026-11-01) From c941a1da5dc3735a99ab633e8b39a8abc604bc69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:36:08 -0800 Subject: [PATCH 56/83] Contextual Task Bar: screen readers name the text buttons The bar's text buttons (Edit Path, Duplicate, Type on a Path Options and the others) were painted labels on a click area with no accessible name, so a screen reader announced them without one. Each button now reports its label as a button, as the Home screen's file rows do. --- crates/ui-egui/src/canvas/task_bar.rs | 1 + crates/ui-egui/src/canvas/tests.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index b5f8dac668..0ccba73dee 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -233,6 +233,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { for (label, icon, cmd, params) in &items { let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), t.text_strong); let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x + 38.0, 30.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, *label)); if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(3), t.hover); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a9ef2c228d..172475daaa 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9198,6 +9198,20 @@ fn the_task_bar_offers_the_artboard_tools_actions() { assert_eq!(names(&mut app), ["Resize", "Duplicate", "Export"]); } +/// Screen readers name the Contextual Task Bar's text buttons by their labels. +#[test] +fn screen_readers_name_the_task_bars_text_buttons() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 180, "y": 130, "width": 40, "height": 40})).unwrap(); + app.select_tool("selection"); + let tree = tree(|ui| show(&mut app, ui)); + for label in ["Edit Path", "Offset Path", "Simplify", "Duplicate"] { + assert_eq!(named(&tree, label).role(), egui::accesskit::Role::Button, "{label}"); + } +} + /// A selected group's Contextual Task Bar offers Ungroup and Isolate. While an opacity mask is /// edited, when Enter Isolation Mode is off, a group in the mask art gets Ungroup without Isolate. #[test] From bc63dc7285971b2ee7bcae55bd73d0f473131910 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:36:08 -0800 Subject: [PATCH 57/83] =?UTF-8?q?Scripts:=20the=20File=20=E2=80=BA=20Scrip?= =?UTF-8?q?ts=20command=20help=20says=20it=20runs=20the=20script=20by=20pa?= =?UTF-8?q?th?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f1513f8df9..06dcf85bcb 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1536,7 +1536,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with the file's text, under the file's name), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (the script is checked again, then script.run runs it by its path, so its #include lines and $.evalFile read beside it), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", From 68042f0924174ab543f4bf4729a2ba29477bbd63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 00:57:15 -0800 Subject: [PATCH 58/83] Docs: the Dynamic symbols evidence lists the Edit Symbol tests --- 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 2103ed6243..8d2d365fbd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1896,7 +1896,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Dynamic symbols (2026-11-01) -Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol keeps the instances linked and keeps each change whose object the edited art still has; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. +Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol keeps the instances linked and keeps each change whose object the edited art still has; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests, `crates/engine/src/tests/symboledit.rs`. Score unchanged at 87% (estimated); hours 5–9 → 4–8. ## Document Tools add-on: Export All Open Documents (2026-11-01) From afdaa47cd51d65dcaec0044cc100201cfd216092 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 22:54:52 -0800 Subject: [PATCH 59/83] SVG import: a clip path made of text clips by the text A in a was dropped with a warning, so a clip path made only of text had no content and the art it clipped was hidden. The clipPath content model in CSS Masking Module Level 1 lists text and use (https://www.w3.org/TR/css-masking-1/#ClipPathElement). The importer now clips by the text's glyph outlines, together with any shapes in the same clip path, and keeps clipPathUnits, the transforms, clip-rule, visibility, the conditional processing attributes and a clip path on the text. A in a clip path that shows a text clips the same way, placed by the ; a clip path on the applies in the 's user space, and a reference goes to the first element with the id. When the clip path holds only one visible text, with no clip path of its own and no even-odd clip rule, the clipping path of the clip group is the text object with no fill or stroke, the same structure Make Clipping Mask produces for type. A text or a with an id in a clip path can still be shown by a outside it. Each text's outlines are laid out once, however many elements use the clip path. A transform set by a style rule or a style attribute on a text now places it, as it does a shape. Before, only the transform attribute was read, inside and outside clip paths. --- crates/engine/tests/import_fuzz.rs | 20 ++ crates/svg/src/import/convert.rs | 35 ++- crates/svg/src/import/importer.rs | 54 +++- crates/svg/src/import/text.rs | 251 +++++++++++++++-- crates/svg/src/lib.rs | 7 +- crates/svg/tests/it/clip_text.rs | 429 +++++++++++++++++++++++++++++ crates/svg/tests/it/import_text.rs | 13 + crates/svg/tests/it/main.rs | 1 + 8 files changed, 771 insertions(+), 39 deletions(-) create mode 100644 crates/svg/tests/it/clip_text.rs diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 424f30cdd7..f729ed394c 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -663,6 +663,26 @@ proptest! { survive(&svg, || vectorcraft_svg::import(&svg).ok())?; } + /// Clip paths made of text, of `` elements showing text, and of both with shapes, each with + /// hostile attributes, clipping art that may clip by them in turn. + #[test] + fn svg_text_clip_paths_never_panic( + text in prop::collection::vec(arb_svg_attr(), 0..5), + used in prop::collection::vec(arb_svg_attr(), 0..5), + clip in prop::collection::vec(arb_svg_attr(), 0..3), + body in prop::collection::vec(arb_svg_element(1), 0..3), + ) { + let svg = format!( + "abcClipit{}", + text.concat(), + clip.concat(), + text.concat(), + used.concat(), + body.concat() + ); + survive(&svg, || vectorcraft_svg::import(&svg).ok())?; + } + #[test] fn svg_mutated_export_never_panics( cut in 0usize..20_000, diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index d8cf3bcd58..8bdadb0318 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -192,49 +192,58 @@ const MAX_CLIP_DEPTH: usize = 16; /// multiply the work at every level: without this, a few lines of SVG would never finish. const MAX_CLIP_READS: usize = 1024; -/// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. -pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { +/// The shapes a text placeholder path in a clip path stands for (the text's glyph outlines), given +/// the path and the transform `m` that maps its user space to the document; `None` for any other +/// path. +pub(super) type ClipText<'a> = &'a dyn Fn(&usvg::Path, Affine) -> Option>; + +/// The shapes of clip path `cp` on an element whose user space `ts` maps to the document, with the +/// glyph outlines `text` gives for the text in it. +pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine, text: ClipText) -> Vec<(BezPath, FillRule)> { let mut reads = MAX_CLIP_READS; - clip_shapes_depth(cp, ts, 0, &mut reads) + clip_shapes_depth(cp, ts, 0, &mut reads, text) } /// Recursively collect shapes for `cp` in document space up to `MAX_CLIP_DEPTH`, and while `reads` /// are left. -fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize) -> Vec<(BezPath, FillRule)> { +fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize, text: ClipText) -> Vec<(BezPath, FillRule)> { if depth > MAX_CLIP_DEPTH || *reads == 0 { return Vec::new(); } *reads -= 1; - fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, out: &mut Vec<(BezPath, FillRule)>) { + fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, text: ClipText, out: &mut Vec<(BezPath, FillRule)>) { for c in g.children() { match c { usvg::Node::Group(g) => { let m_child = m * aff(g.transform()); if let Some(child_cp) = g.clip_path() { let mut child_shapes = Vec::new(); - collect(g, m_child, depth + 1, reads, &mut child_shapes); + collect(g, m_child, depth + 1, reads, text, &mut child_shapes); if !child_shapes.is_empty() { - let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads); + let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads, text); intersect_shapes(&child_shapes, &clip_paths, out); } } else { - collect(g, m_child, depth, reads, out); + collect(g, m_child, depth, reads, text, out); } } - usvg::Node::Path(p) => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), + usvg::Node::Path(p) => match text(p, m) { + Some(glyphs) => out.extend(glyphs), + None => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), + }, _ => {} } } } let mut shapes = Vec::new(); - collect(cp.root(), ts * aff(cp.transform()), depth, reads, &mut shapes); + collect(cp.root(), ts * aff(cp.transform()), depth, reads, text, &mut shapes); if !shapes.is_empty() && depth > 0 && depth < MAX_CLIP_DEPTH && *reads > 0 && let Some(parent_cp) = cp.clip_path() { - let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads); + let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads, text); let mut intersected = Vec::new(); intersect_shapes(&shapes, &parent_shapes, &mut intersected); shapes = intersected; @@ -267,7 +276,7 @@ fn intersect_shapes(shapes: &[(BezPath, FillRule)], clips: &[(BezPath, FillRule) /// Does clip path `cp` (on an element whose user space `ts` maps to the document) leave `art`, /// placed by `xf`, whole? (Only its bounds are checked: the box must be inside a clip shape.) -pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> bool { +pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine, text: ClipText) -> bool { let Some(b) = art.visual_bounds() else { return false }; if cp.clip_path().is_some() { return false; @@ -275,7 +284,7 @@ pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> // Art touching the clip's edge isn't cut by it. let e = 1e-6 * (b.width() + b.height()).max(1e-9); let b = b.inflate(-e, -e); - let shapes = clip_shapes(cp, ts); + let shapes = clip_shapes(cp, ts, text); let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; corners.iter().all(|c| shapes.iter().any(|(s, _)| kurbo::Shape::contains(s, xf * *c))) } diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 6324e53809..56efe7b3a8 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -194,7 +194,7 @@ impl Importer { _ => self.named("", NodeKind::Group { children: kids, clip: false })?, }; // usvg clips a `` of a symbol to its viewport: that only counts when it cuts the art. - let whole = g.clip_path().is_none_or(|cp| uncut(cp, ts, &art, xf)); + let whole = g.clip_path().is_none_or(|cp| uncut(cp, ts, &art, xf, &|p, m| self.clip_text(p, m))); let name = match self.symbols.get(&sym) { Some(made) if whole && made.art == without_ids(&art) && made.reuse.allows(xf) => made.name.clone(), Some(_) => return None, @@ -519,7 +519,10 @@ impl Importer { } fn clip_node(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { - let mut shapes = clip_shapes(cp, ts); + if let Some(n) = self.clip_type(cp, ts) { + return Some(n); + } + let mut shapes = clip_shapes(cp, ts, &|p, m| self.clip_text(p, m)); let id = cp.id().to_string(); if shapes.len() == 1 { let (bp, r) = shapes.pop()?; @@ -540,6 +543,53 @@ impl Importer { self.named(&id, NodeKind::Group { children, clip: false }) } + /// The glyph outlines, in the document, of the text a clip placeholder path `p` stands for (see + /// [`text`]), whose user space `m` maps to the document; nothing when the text is hidden. `None` + /// when `p` isn't a placeholder: in a clip path only its id tells (usvg paints clip path content + /// black). + fn clip_text(&self, p: &usvg::Path, m: Affine) -> Option> { + if p.id().is_empty() { + return None; + } + let i = self.slots.find(p)?; + let t = self.slots.texts.get(i)?; + if !p.is_visible() { + return Some(vec![]); + } + let mut bp = BezPath::clone(&*self.slots.outlines(i)?); + bp.apply_affine(m * self.slots.inner(p) * t.obj.xf); + let r = p.fill().map(|f| rule(f.rule())).unwrap_or_default(); + Some(if bp.elements().is_empty() { vec![] } else { vec![(bp, r)] }) + } + + /// Clip path `cp` (on an element whose user space `ts` maps to the document) as live type, when + /// all it holds is one visible text that clips by the non-zero rule and has no clip path of its + /// own: the text object with no fill or stroke, the same structure Make Clipping Mask produces + /// for type. + fn clip_type(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { + let mut m = ts * aff(cp.transform()); + let mut kids = cp.root().children(); + while let [usvg::Node::Group(g)] = kids + && g.clip_path().is_none() + { + m *= aff(g.transform()); + kids = g.children(); + } + let [usvg::Node::Path(p)] = kids else { return None }; + if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { + return None; + } + let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + obj.xf = m * self.slots.inner(p) * obj.xf; + let grow = text::size_scale(&obj, obj.xf); + for run in &mut obj.runs { + run.style.fill = Paint::None; + run.style.stroke = Paint::None; + } + text::fold_scale(&mut obj, grow); + self.named(cp.id(), NodeKind::Text(Box::new(obj))) + } + /// One clip path child: a path, or a compound path of its subpaths when it has several. fn clip_shape(&mut self, bp: &BezPath, r: FillRule, clipping: bool) -> Option { let subs = PathData::from_bezpath(bp).subpaths; diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 2502bd2bd6..904b76cd13 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -10,6 +10,13 @@ //! gradients and patterns in the text's user space; the importer swaps each placeholder for the //! [`PendingText`] it stands for. //! +//! usvg accepts only shapes, `` and `` as the children of a ``, so a `` +//! there (and a `` there that shows one) becomes a placeholder path instead, which the importer +//! finds by its id (`{prefix}{i}-…`). The importer clips by the text's glyph outlines, or uses the +//! text itself as live type. A `` in a clip path that has an id also gets the usual +//! placeholder group after its path, and a `` there with an id keeps a copy in a `` +//! after its path, for `` elements outside the clip path. +//! //! Characters keep SVG's per-character `x`/`y`/`dx`/`dy`/`rotate` lists: a character with an //! absolute `x` that moves down by at least half a line starts a new line (the leading becomes the //! line spacing), other vertical moves become baseline shift, horizontal moves become kerning (an @@ -166,14 +173,21 @@ pub(super) struct PendingText { pub(super) struct TextSlots { prefix: String, pub texts: Vec, + /// The transform between a clip placeholder path's user space and its text's, by placeholder + /// id, where the placeholder leaves it out (see [`clip_uses`]). + inner: HashMap, + /// The glyph outlines of each text laid out so far, in text space, by index. + outlines: RefCell>>, } impl TextSlots { - /// The text a placeholder's main path stands for: by its id, or inside `` instances - /// (where usvg drops ids) by its colour (the index) and its rectangle. + /// The text a placeholder's main path stands for: by its id (`{prefix}{index}`, or + /// `{prefix}{index}-{k}` for the clip placeholders), or inside `` instances (where usvg + /// drops ids) by its colour (the index) and its rectangle. pub fn find(&self, p: &usvg::Path) -> Option { if !p.id().is_empty() { - return p.id().strip_prefix(&self.prefix)?.parse().ok(); + let rest = p.id().strip_prefix(&self.prefix)?; + return rest.split_once('-').map_or(rest, |(i, _)| i).parse().ok(); } let Some(usvg::Paint::Color(c)) = p.fill().map(|f| f.paint()) else { return None }; if p.stroke().is_some() || p.data().segments().count() != 5 { @@ -185,6 +199,23 @@ impl TextSlots { let near = |a: f32, b: f64| (a as f64 - b).abs() <= 1e-3 * b.abs().max(1.0); (near(b.left(), m.x0) && near(b.top(), m.y0) && near(b.right(), m.x1) && near(b.bottom(), m.y1)).then_some(i) } + + /// The transform from the user space of clip placeholder path `p` to the space of the text it + /// stands for (the identity unless [`clip_uses`] left the text's transform out of it). + pub fn inner(&self, p: &usvg::Path) -> Affine { + self.inner.get(p.id()).copied().unwrap_or(Affine::IDENTITY) + } + + /// The glyph outlines of text `i` in text space, laid out once however many clips use it. + pub fn outlines(&self, i: usize) -> Option> { + if let Some(bp) = self.outlines.borrow().get(&i) { + return Some(bp.clone()); + } + let t = self.texts.get(i)?; + let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + self.outlines.borrow_mut().insert(i, bp.clone()); + Some(bp) + } } /// Replace every `` usvg would draw by a placeholder group (see the module docs). @@ -200,10 +231,11 @@ pub(super) fn prepare<'s>( while xml.descendants().any(|n| n.attribute("id").is_some_and(|id| id.starts_with(&prefix))) { prefix.insert(0, '_'); } - let mut slots = TextSlots { prefix, texts: vec![] }; + let mut slots = TextSlots { prefix, ..TextSlots::default() }; let style_xml = original_xml.unwrap_or(xml); let cx = Ctx::new(style_xml, dpi); - let mut out = String::new(); + // The replacements, in source order: each element's range and what takes its place. + let mut edits: Vec<(Range, String)> = vec![]; let mut copied = 0; let is_text = |n: &XNode| { n.is_element() @@ -211,52 +243,227 @@ pub(super) fn prepare<'s>( && n.tag_name().namespace() == Some(SVG_NS) && !n.ancestors().any(|a| a.has_tag_name("style")) }; + // The slot of each text, by element, for the `` elements in clip paths below. + let mut slot_of = HashMap::new(); for (t, style_t) in xml.descendants().filter(is_text).zip(style_xml.descendants().filter(is_text)) { let label = t.attribute("id").map_or_else(|| "a text".to_string(), |id| format!("text '{id}'")); - if t.ancestors().skip(1).any(|a| a.is_element() && a.tag_name().name() == "clipPath") { + // CSS Masking Module Level 1 §6.1 (https://www.w3.org/TR/css-masking-1/#ClipPathElement): + // text is clip path content only as a child of the ``. + let clip_child = in_clip_path(t); + if !clip_child && t.ancestors().skip(1).any(|a| a.is_element() && a.tag_name().name() == "clipPath") { warnings.push(format!("{label} in a clip path ignored")); continue; } let r = t.range(); - // The element's qualified name (`text` or `svg:text`), so the placeholder lands in the same - // namespace; skip anything whose source range isn't the element itself (entity expansions). - let Some(qname) = svg - .get(r.start..r.end) - .and_then(|s| s.strip_prefix('<')) - .map(|s| s.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next().unwrap_or("")) - else { - continue; - }; + let Some(q) = qualifier(svg, t) else { continue }; let flowed = t.tag_name().name() == "flowRoot"; - let Some(q) = qname.strip_suffix(t.tag_name().name()).filter(|q| q.is_empty() || q.ends_with(':')) else { continue }; if cx.css.own(style_t, "display").as_deref() == Some("none") || r.start < copied { continue; } let built = if flowed { cx.build_flow(style_t, &label, warnings) } else { cx.build(style_xml, style_t, &label, warnings) }; let Some((text, paints)) = built else { continue }; - out.push_str(&svg[copied..r.start]); - placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, slots.texts.len(), text.marker, &paints); + let mut out = String::new(); + let index = slots.texts.len(); + if clip_child { + let id = format!("{}{index}-c", slots.prefix); + let props = clip_props(&cx.css, Some(style_t), None); + clip_placeholder(&mut out, q, &id, &own_transform(&cx.css, style_t), &props, t, text.marker); + // A `` elsewhere can still show the text by its id: the clip path leaves out this + // group (a group isn't clip path content), but the `` finds it. + if t.attribute("id").is_some() { + placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, index, text.marker, &paints); + } + } else { + placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, index, text.marker, &paints); + } copied = r.end; + edits.push((r, out)); + slot_of.insert(t.id(), index); slots.texts.push(text); } if slots.texts.is_empty() { return (Cow::Borrowed(svg), slots); } - out.push_str(&svg[copied..]); + clip_uses(svg, xml, style_xml, &cx, &slot_of, &mut slots, &mut edits, warnings); + edits.sort_by_key(|(r, _)| r.start); + let mut out = String::with_capacity(svg.len()); + let mut copied = 0; + for (r, s) in edits { + if r.start < copied { + continue; + } + out.push_str(svg.get(copied..r.start).unwrap_or("")); + out.push_str(&s); + copied = r.end; + } + out.push_str(svg.get(copied..).unwrap_or("")); (Cow::Owned(out), slots) } +/// Is `n` a child of a ``? +fn in_clip_path(n: XNode) -> bool { + n.parent_element().is_some_and(|p| p.tag_name().name() == "clipPath" && p.tag_name().namespace() == Some(SVG_NS)) +} + +/// The namespace prefix of element `n` as the source writes it (empty, or `svg:` and the like), so +/// what replaces it lands in the same namespace. `None` when its source range isn't the element +/// itself (entity expansions). +fn qualifier<'s>(svg: &'s str, n: XNode) -> Option<&'s str> { + let r = n.range(); + let qname = svg + .get(r.start..r.end) + .and_then(|s| s.strip_prefix('<')) + .map(|s| s.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next().unwrap_or(""))?; + qname.strip_suffix(n.tag_name().name()).filter(|q| q.is_empty() || q.ends_with(':')) +} + +/// Replace each `` in a clip path that shows a text by the clip placeholder of that text, +/// placed by the `` (usvg drops ids and paints clip path content black, so the text a +/// placeholder group stands for couldn't be found again inside one). +#[allow(clippy::too_many_arguments)] +fn clip_uses( + svg: &str, + xml: &roxmltree::Document, + style_xml: &roxmltree::Document, + cx: &Ctx, + slot_of: &HashMap, + slots: &mut TextSlots, + edits: &mut Vec<(Range, String)>, + warnings: &mut Vec, +) { + let is_use = |n: &XNode| n.is_element() && n.tag_name().name() == "use" && n.tag_name().namespace() == Some(SVG_NS) && in_clip_path(*n); + if !xml.descendants().any(|n| is_use(&n)) { + return; + } + let (ids, style_ids) = (first_ids(xml), first_ids(style_xml)); + for (k, (u, style_u)) in xml.descendants().filter(is_use).zip(style_xml.descendants().filter(is_use)).enumerate() { + let Some(id) = href(u).and_then(|h| h.strip_prefix('#')) else { continue }; + let Some(t) = ids.get(id) else { continue }; + let Some(&i) = slot_of.get(&t.id()) else { continue }; + let Some(marker) = slots.texts.get(i).map(|text| text.marker) else { continue }; + let Some(q) = qualifier(svg, u) else { continue }; + // An undisplayed `` adds nothing to the clip (usvg leaves it out as it is). + if cx.css.own(style_u, "display").is_some_and(|d| d.trim() == "none") { + continue; + } + let style_t = style_ids.get(id).copied().filter(|s| s.tag_name() == t.tag_name()); + let em = cx.font_size(style_u); + let length = |a: &str, pct: f64| u.attribute(a).and_then(|v| cx.length(v, em, pct)).unwrap_or(0.0); + let (x, y) = (length("x", cx.viewport.0), length("y", cx.viewport.1)); + let placed = format!("{} translate({x} {y})", own_transform(&cx.css, style_u)); + let text_xf = match style_t { + Some(s) => own_transform(&cx.css, s), + None => t.attribute("transform").unwrap_or("").to_string(), + }; + // One element can carry one clip path. The text's own clip path is in the text's user space + // and wins; a clip path of the `` is in the ``'s, so the text's transform moves + // to the importer instead. + let clipped = |n: XNode| cx.css.own(n, "clip-path").is_some_and(|v| v.trim() != "none"); + let id = format!("{}{i}-{k}", slots.prefix); + let transform = if style_t.is_some_and(clipped) { + if clipped(style_u) { + let label = u.attribute("id").map_or_else(|| "a use of a text".to_string(), |id| format!("'{id}'")); + warnings.push(format!("clip path of {label} in a clip path ignored: the text's own applies")); + } + format!("{placed} {text_xf}") + } else { + slots.inner.insert(id.clone(), parse_transform(Some(&text_xf))); + placed + }; + let props = clip_props(&cx.css, style_t, Some(style_u)); + let mut out = String::new(); + clip_placeholder(&mut out, q, &id, &transform, &props, u, marker); + // Another `` can still show this one by its id: a copy of it stays in a ``, which + // the clip path leaves out, with the properties style rules gave it written out. + if u.attribute("id").is_some() { + use_copy(&mut out, q, &cx.css, u, style_u); + } + edits.push((u.range(), out)); + } +} + +/// Write a copy of `` `u` in a ``: its attributes in no namespace, its link as `href`, +/// and the properties set on it by rules and its `style` (from `style_u`) as its `style`. +fn use_copy(out: &mut String, q: &str, css: &Styles, u: XNode, style_u: XNode) { + let _ = write!(out, "<{q}defs><{q}use"); + for a in u.attributes().filter(|a| a.namespace().is_none() && !matches!(a.name(), "style" | "href")) { + let _ = write!(out, " {}=\"{}\"", a.name(), xml_escape(a.value())); + } + if let Some(h) = href(u) { + let _ = write!(out, " href=\"{}\"", xml_escape(h)); + } + let declared = css.declared(style_u); + let mut props: Vec<_> = declared.iter().collect(); + props.sort(); + let style: String = props.into_iter().map(|(k, v)| format!("{k}:{v};")).collect(); + let _ = write!(out, " style=\"{}\"/>", xml_escape(&style)); +} + +/// The identity transform, as a `transform` value usvg reads. +const IDENTITY: &str = "matrix(1 0 0 1 0 0)"; + +/// The transform of element `n`: a `transform` declaration in a rule or its `style` (which the +/// prepass has written in SVG syntax), else its `transform` attribute; empty when it has none. +fn own_transform(css: &Styles, n: XNode) -> String { + css.own(n, "transform").filter(|v| !v.eq_ignore_ascii_case("none")).unwrap_or_default() +} + +/// Each id of `doc` with the first element that has it (a reference goes to that one, as in usvg). +fn first_ids<'a, 'i>(doc: &'a roxmltree::Document<'i>) -> HashMap<&'a str, XNode<'a, 'i>> { + let mut ids = HashMap::new(); + for n in doc.descendants() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } + ids +} + +/// The properties of clip path content that the placeholder of text `t` keeps, as a `style` value: +/// its `clip-path` (or that of the `` `u` showing it, when the text has none), and its +/// computed `clip-rule` and `visibility`, inherited from `u` when there is one. Every value is +/// written out, so no style rule that matches the placeholder path applies to it. +fn clip_props(css: &Styles, t: Option, u: Option) -> String { + let set = |n: XNode, p: &str| css.own(n, p).filter(|v| v.trim() != "inherit"); + let clip = |n: XNode| css.own(n, "clip-path").filter(|v| v.trim() != "none"); + let mut style = format!("clip-path:{};", t.and_then(clip).or_else(|| u.and_then(clip)).unwrap_or_else(|| "none".into())); + for (p, initial) in [("clip-rule", "nonzero"), ("visibility", "visible")] { + let v = t.and_then(|t| set(t, p)).or_else(|| u.or(t).and_then(|n| css.prop(n, p))).unwrap_or_else(|| initial.into()); + let _ = write!(style, "{p}:{v};"); + } + style +} + +/// Write the placeholder of a text in a clip path: a path over the text's bounds `b` with id `id`, +/// transform `transform`, properties `props` ([`clip_props`]) and the conditions of element `n`. +/// usvg drops a group in a clip path and paints clip path content black whatever its fill, so the +/// placeholder is a path, and the importer finds it by its id ([`TextSlots::find`]). +fn clip_placeholder(out: &mut String, q: &str, id: &str, transform: &str, props: &str, n: XNode, b: Rect) { + let _ = write!(out, "<{q}path id=\"{}\"", xml_escape(id)); + for a in ["systemLanguage", "requiredFeatures", "requiredExtensions"] { + if let Some(v) = n.attribute(a) { + let _ = write!(out, " {a}=\"{}\"", xml_escape(v)); + } + } + // In `style`, so no rule that matches the path moves it. + let transform = if transform.trim().is_empty() { IDENTITY } else { transform }; + let _ = write!(out, " style=\"transform:{};{}display:inline\"", xml_escape(transform), xml_escape(props)); + let _ = write!(out, " d=\"M{} {}H{}V{}H{}Z\"/>", b.x0, b.y0, b.x1, b.y1, b.x0); +} + /// Write the placeholder group for text `t` (namespace prefix `q`), slot `index`. #[allow(clippy::too_many_arguments)] fn placeholder(out: &mut String, q: &str, css: &Styles, t: XNode, style_t: XNode, prefix: &str, index: usize, b: Rect, paints: &[String]) { let _ = write!(out, "<{q}g"); - for a in ["id", "transform", "systemLanguage", "requiredFeatures", "requiredExtensions"] { + for a in ["id", "systemLanguage", "requiredFeatures", "requiredExtensions"] { if let Some(v) = t.attribute(a) { let _ = write!(out, " {a}=\"{}\"", xml_escape(v)); } } - // The text's own non-inherited properties, overriding any rule that matches the ``. - let mut style = String::new(); + // The text's own non-inherited properties, overriding any rule that matches the ``. The + // transform too: a `transform` declaration in a rule or `style` beats the attribute. + let transform = own_transform(css, style_t); + let mut style = format!("transform:{};", if transform.is_empty() { IDENTITY } else { &transform }); for (p, initial) in [("opacity", "1"), ("clip-path", "none"), ("mask", "none"), ("filter", "none"), ("mix-blend-mode", "normal"), ("isolation", "auto")] { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index a3ad7a069e..8a447f6c38 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -78,8 +78,11 @@ //! 64 periods). //! * `` files are read through [`ImportOptions`]: rasters stay linked, SVG files (and SVG //! `data:` URLs) become art (without their text), missing ones a placeholder keeping the link. -//! * Text lines after the first start at the first line's x; text in a clip path is ignored; -//! absolute positions inside type on a path are ignored; vertical text sets every glyph sideways. +//! * Text lines after the first start at the first line's x; absolute positions inside type on a +//! path are ignored; vertical text sets every glyph sideways. +//! * A `` in a ``, or a `` there that shows one, clips by its glyph outlines. +//! When a clip path holds only one text, and that text has no clip path of its own and no +//! even-odd clip rule, the clip group's clipping path is the text as live type that paints nothing. //! //! ## Import text //! diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs new file mode 100644 index 0000000000..07773dd5f8 --- /dev/null +++ b/crates/svg/tests/it/clip_text.rs @@ -0,0 +1,429 @@ +//! SVG import of clip paths made of text (CSS Masking Module Level 1 §6.1, +//! https://www.w3.org/TR/css-masking-1/#ClipPathElement: `` and `` are clip path +//! content). + +use vectorcraft_color::Paint; +use vectorcraft_doc::{Document, Node, NodeKind, TextKind}; +use vectorcraft_geom::kurbo::Shape; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_svg::{ExportOptions, export, import, import_with_report}; + +fn svg(body: &str) -> String { + format!(r#"{body}"#) +} + +fn open(body: &str) -> Document { + import(&svg(body)).unwrap_or_else(|e| panic!("{e}")) +} + +/// The top-level objects of the first layer. +fn top(d: &Document) -> &[std::sync::Arc] { + d.layers[0].children().unwrap() +} + +/// The clip group `n` is, with its clipping path and the art it clips. +fn clip_group(n: &Node) -> (&Node, &[std::sync::Arc]) { + let NodeKind::Group { children, clip: true } = &n.kind else { panic!("not a clip group: {:?}", n.kind) }; + let (first, rest) = children.split_first().unwrap(); + (first, rest) +} + +/// The bounds of the region a clipping path clips to. +fn clip_bounds(clip: &Node) -> Rect { + let (bp, _) = vectorcraft_effects::clip_outline(clip).expect("the clipping path clips to something"); + bp.bounding_box() +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +#[test] +fn a_text_clip_path_clips_by_the_text_as_live_type() { + let d = open( + r##"HI + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 1, "{objects:?}"); + let (clip, art) = clip_group(&objects[0]); + assert_eq!(art.len(), 1); + assert_eq!(art[0].name.as_deref(), Some("art")); + // The clipping path is the text object with no fill or stroke, as after Make Clipping Mask. + let NodeKind::Text(t) = &clip.kind else { panic!("the clipping path is {:?}", clip.kind) }; + assert_eq!(t.plain_text(), "HI"); + assert!(t.runs.iter().all(|r| r.style.fill == Paint::None && r.style.stroke == Paint::None)); + assert!(near(t.runs[0].style.size, 100.0, 1e-9), "{}", t.runs[0].style.size); + assert!(t.xf.translation().to_point().distance(Point::new(20.0, 150.0)) < 1e-9, "{:?}", t.xf); + let p = clip.clip_paint(); + assert!(p.fill.is_none() && p.stroke.is_none(), "a clip path paints nothing"); + // It clips to the glyphs: inside the line, not the whole rectangle. + let b = clip_bounds(clip); + assert!(b.x0 >= 20.0 - 1e-6 && b.x1 < 220.0 && b.y1 <= 150.0 + 1e-6 && b.y0 > 50.0 && b.width() > 40.0, "{b:?}"); +} + +#[test] +fn text_and_shapes_in_one_clip_path_clip_to_their_union() { + let d = open( + r##"O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 2, "the rectangle and the glyph outlines: {shapes:?}"); + let rect = shapes[0].0.bounding_box(); + assert!(near(rect.x0, 300.0, 1e-6) && near(rect.y1, 50.0, 1e-6), "{rect:?}"); + let glyphs = shapes[1].0.bounding_box(); + assert!(glyphs.x0 >= 20.0 - 1e-6 && glyphs.x1 < 120.0 && glyphs.y1 < 160.0 && glyphs.y0 > 50.0, "{glyphs:?}"); + let b = clip_bounds(clip); + assert!(near(b.x1, 350.0, 1e-6) && near(b.y0, 10.0, 1e-6), "{b:?}"); +} + +#[test] +fn a_text_clip_path_keeps_its_units_and_transforms() { + // The clip path's box units and the text's own transform place the type. + let d = open( + r##" + I + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // The box maps x 0.5…1 to 200…300 and y 0…1 to 100…200. + assert!(b.x0 >= 200.0 - 1e-6 && b.x1 <= 300.0 && b.y0 >= 100.0 && b.y1 <= 180.0 + 1e-6 && b.height() > 30.0, "{b:?}"); + // The clip path's transform moves it, as it moves a shape in it. + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(120.0, 170.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines() { + // The text's own clip path cuts its glyphs: the clip keeps their part inside the rectangle. + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "outlines, as the clip of the text cuts them"); + let b = clip_bounds(clip); + assert!(b.y1 <= 120.0 + 1e-6 && b.y0 > 50.0 && b.x0 >= 20.0 - 1e-6, "{b:?}"); + // An even-odd text clip keeps its rule on the outlines. + let d = open( + r##"O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 1); + assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); +} + +#[test] +fn tspans_and_type_on_a_path_clip_too() { + let d = open( + r##"AB + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.plain_text().contains('A') && t.plain_text().contains('B'), "{:?}", t.plain_text()); + let b = clip_bounds(clip); + assert!(b.y0 < 80.0 && b.y1 > 150.0, "both lines clip: {b:?}"); + + let d = open( + r##" + Around + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(matches!(t.kind, TextKind::OnPath { .. }), "{:?}", t.kind); + assert!(clip_bounds(clip).width() > 50.0); +} + +#[test] +fn a_use_of_a_text_in_a_clip_path_clips_where_the_use_places_it() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(20.0, 150.0)) < 1e-9, "{:?}", t.xf); + // Font-relative positions count in the ``'s font size; an undisplayed `` adds nothing. + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("only the displayed use: {:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(80.0, 120.0)) < 1e-9, "{:?}", t.xf); + // The same text drawn as well as used in a clip path. + let d = open( + r##"HI + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + assert!(matches!(objects[0].kind, NodeKind::Text(_))); + let (clip, _) = clip_group(&objects[1]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 2, "{shapes:?}"); + let glyphs = shapes[0].0.bounding_box(); + assert!(glyphs.x0 >= 200.0 - 1e-6 && glyphs.y1 <= 100.0 + 1e-6 && glyphs.y0 > 40.0, "{glyphs:?}"); +} + +#[test] +fn a_clip_path_on_a_use_of_a_text_is_in_the_use_s_user_space() { + // The text's transform moves its glyphs to x 200…; the ``'s clip keeps x < 250 of its own + // user space, which the text's transform doesn't move. + let d = open( + r##" + HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(b.x0 >= 200.0 - 1e-6 && near(b.x1, 250.0, 1e-6), "{b:?}"); + // Without a clip on the ``, the text's transform still places the type. + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(200.0, 160.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_css_transform_places_a_text_in_a_clip_path() { + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(120.0, 170.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn css_transforms_place_a_use_of_a_text_in_a_clip_path() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(25.0, 150.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_use_refers_to_the_first_element_with_its_id() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "the rectangle clips: {:?}", clip.kind); + let b = clip_bounds(clip); + assert!(near(b.x0, 300.0, 1e-6) && near(b.x1, 350.0, 1e-6) && near(b.y1, 50.0, 1e-6), "{b:?}"); +} + +#[test] +fn a_text_in_a_clip_path_can_be_shown_by_a_use_elsewhere() { + let d = open( + r##"HI + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + let (clip, _) = clip_group(&objects[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let mut shown = vec![]; + objects[1].walk(&mut |n: &Node| { + if let NodeKind::Text(t) = &n.kind { + shown.push(t.plain_text()); + } + }); + assert_eq!(shown, ["HI"], "the use shows the text: {:?}", objects[1]); +} + +#[test] +fn a_use_in_a_clip_path_can_be_shown_by_another_use() { + let d = open( + r##"HI + + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + let (clip, _) = clip_group(&objects[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let mut shown = vec![]; + objects[1].walk(&mut |n: &Node| match &n.kind { + NodeKind::Text(t) => shown.push(t.plain_text()), + NodeKind::Path { .. } => shown.push("a path".into()), + _ => {} + }); + assert_eq!(shown, ["HI"], "the other use shows the text: {:?}", objects[1]); + // A rule that styles the `` where it stands still applies to what the other use shows. + let d = open( + r##" + HI + + + "##, + ); + let objects = top(&d); + let mut at = vec![]; + objects[1].walk(&mut |n: &Node| { + if let NodeKind::Text(t) = &n.kind { + at.push(t.xf.translation().to_point()); + } + }); + assert!(at.len() == 1 && at[0].distance(Point::new(60.0, 200.0)) < 1e-9, "{at:?}"); +} + +#[test] +fn style_rules_for_paths_do_not_reach_a_text_in_a_clip_path() { + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "the visible, non-zero text: {:?}", clip.kind); + // The text's own values, and those it inherits, still apply. + let d = open( + r##" + O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 1); + assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); +} + +#[test] +fn a_hidden_text_alone_in_a_clip_path_is_not_live_type() { + let d = open( + r##"HI + "##, + ); + let objects = top(&d); + let clips = objects.iter().filter_map(|n| match &n.kind { + NodeKind::Group { children, clip: true } => children.first(), + _ => None, + }); + for clip in clips { + assert!(!matches!(clip.kind, NodeKind::Text(_)), "a hidden text clips nothing: {:?}", clip.kind); + } +} + +#[test] +fn a_text_left_out_by_its_conditions_clips_nothing() { + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(near(b.x1, 10.0, 1e-6) && near(b.y1, 10.0, 1e-6), "only the rectangle: {b:?}"); +} + +#[test] +fn a_text_clip_on_a_symbol_instance_cuts_art_between_the_letters() { + // The art sits in the space between the two letters, inside the text's box: the glyphs cut it, + // so it stays clipped art instead of becoming an instance without the clip. + let body = |clip: &str| { + format!( + r##" + {clip} + "## + ) + }; + let instances = |d: &Document| { + let mut n = 0; + d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::SymbolInstance { .. }))); + n + }; + let d = open(&body(r#"I I"#)); + assert_eq!(instances(&d), 0, "{:?}", top(&d)[0].kind); + assert!(matches!(top(&d)[0].kind, NodeKind::Group { clip: true, .. })); + // A clip around the art leaves it whole: an instance. + let d = open(&body(r#""#)); + assert_eq!(instances(&d), 1); +} + +#[test] +fn a_clip_path_clipped_by_a_text_clip_path_nests() { + let d = open( + r##"HI + + "##, + ); + let (clip, art) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "the outermost clip is the text: {:?}", clip.kind); + let (inner, _) = clip_group(&art[0]); + assert!(matches!(inner.kind, NodeKind::Path { clipping: true, .. }), "{:?}", inner.kind); +} + +#[test] +fn hidden_text_in_a_clip_path_clips_nothing() { + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(near(b.x1, 10.0, 1e-6) && near(b.y1, 10.0, 1e-6), "only the rectangle: {b:?}"); +} + +#[test] +fn text_further_down_in_a_clip_path_is_still_not_clip_path_content() { + let body = r##"No + "##; + let (_, warnings) = import_with_report(&svg(body)).unwrap(); + assert!(warnings.iter().any(|w| w.contains("in a clip path ignored")), "{warnings:?}"); +} + +#[test] +fn a_text_clip_survives_a_round_trip_through_svg_export() { + let d = open( + r##"HI + "##, + ); + let before = clip_bounds(clip_group(&top(&d)[0]).0); + let again = import(&export(&d, &ExportOptions::default())).unwrap(); + let mut clips = vec![]; + again.walk(|n| { + if let NodeKind::Group { children, clip: true } = &n.kind { + clips.push(children[0].clone()); + } + }); + assert_eq!(clips.len(), 1); + let after = clip_bounds(&clips[0]); + let tol = 0.01 * before.width().max(before.height()); + assert!( + near(after.x0, before.x0, tol) && near(after.x1, before.x1, tol) && near(after.y0, before.y0, tol) && near(after.y1, before.y1, tol), + "{before:?} → {after:?}" + ); +} diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 7d0e08c0be..a30bc193b0 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -108,6 +108,19 @@ fn text_keeps_its_z_order_between_shapes() { assert!(t.xf.translation().to_point().distance(Point::new(5.0, 20.0)) < 1e-9); } +#[test] +fn a_css_transform_places_text() { + // A `transform` declaration in a rule or `style` beats the attribute, as on shapes. + for body in [ + r#"Moved"#, + r#"Moved"#, + ] { + let d = open(body); + let t = only_text(&d); + assert!(t.xf.translation().to_point().distance(Point::new(10.0, 40.0)) < 1e-9, "{body}: {:?}", t.xf); + } +} + #[test] fn text_keeps_its_parent_group_clip_and_mask() { let d = open( diff --git a/crates/svg/tests/it/main.rs b/crates/svg/tests/it/main.rs index 3605bd014d..09c175a37a 100644 --- a/crates/svg/tests/it/main.rs +++ b/crates/svg/tests/it/main.rs @@ -4,6 +4,7 @@ mod basic_shapes; mod blend_export; +mod clip_text; mod colorized_images; mod colour_glyphs; mod container_export; From 1851f8769a34fd305bad2c039378e9cd03debf15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:05:16 -0800 Subject: [PATCH 60/83] Glyphs: text.setGlyphAlternate with gid null reports the glyph drawn With no glyph choice left on the character, text.setGlyphAlternate returned the font's default glyph for it: 0 for a character the font lacks, which a fallback font draws, and the lowercase glyph for a letter under All Caps. It now reports the glyph the character is drawn with, as text.glyphAlternates does. --- crates/engine/src/cmd/textedit.rs | 20 ++++++++----- crates/engine/src/tests/textedit.rs | 44 +++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 689a73ea08..86cc050812 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1276,19 +1276,25 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { // out (overflowing text) is shaped alone in its writing direction, with the rest of its grapheme // in the grapheme's own styles. let plain = t.plain_text(); - let unchosen = holder.as_ref().filter(|_| !styled).and_then(|_| { - let mut probe = t.clone(); - edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); - own_glyph(&plain, &lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0) - }); + let mut probe = t.clone(); + edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); + let probe_lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); + let unchosen = holder + .as_ref() + .filter(|_| !styled) + .and_then(|_| own_glyph(&plain, &probe_lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0)); let substituted = unchosen.is_some_and(|g| g != default); let choice = match gid.filter(|g| *g != default || substituted) { None => None, Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)), Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))), }; - let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid); + // Without a choice, the glyph drawn in whatever face draws the character, as + // `text.glyphAlternates` reports it (a fallback face's glyph, the capital of All Caps). + let drawn = match &choice { + Some(c) => c.gid, + None => drawn_glyph(&plain, &probe_lay, ch, &bytes, &face).or_else(|| shaped_alone(&probe, ch, &bytes, &face).1).unwrap_or(default), + }; // The run holding the character. The request changes nothing when the choice is the one the // character's run holds and that run holds the character alone; otherwise the edit splits the // run, so that the following text does not take the character into a ligature. diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index e584e3e328..69f7bc6441 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3436,6 +3436,50 @@ fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { assert_eq!(query["chosen"], json!(glyph.gid), "an overflowing character reports the fallback glyph it is drawn with"); } +/// `text.setGlyphAlternate` with `gid: null` reports the glyph the character is drawn with, as +/// `text.glyphAlternates` does: the fallback face's glyph for a character the font lacks, laid out +/// or overflowing, and the capital that All Caps draws for an a. +#[test] +fn a_glyph_choice_taken_away_reports_the_glyph_drawn() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let mut s = session(); + let reset = |s: &mut Session, id: NodeId, start: usize| { + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": null})).unwrap()["gid"].clone() + }; + let chosen = |s: &mut Session, id: NodeId, start: usize| { + s.execute("text.glyphAlternates", &json!({"id": id.0, "start": start})).unwrap()["chosen"].clone() + }; + + let ch = 'Ƃ'; + assert_eq!(face.glyph_for(ch), 0); + let point = json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)}); + let id = NodeId(s.execute("text.create", &point).unwrap()["id"].as_u64().unwrap()); + let drawn = vectorcraft_text::layout(db, &obj(&s, id)).glyphs[0].gid; + assert_ne!(drawn, 0); + assert_eq!(reset(&mut s, id, 0), json!(drawn), "the fallback glyph"); + assert_eq!(chosen(&mut s, id, 0), json!(drawn)); + + let area = json!({"x": 0, "y": 300, "text": ch.to_string(), "font": alternates_family(true), "area": {"width": 200, "height": 2}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + assert_eq!(reset(&mut s, boxed, 0), json!(drawn), "the overflowing character's fallback glyph"); + + let caps = NodeId( + s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": caps.0, "start": 0, "end": 4, "allCaps": true})).unwrap(); + let drawn = vectorcraft_text::layout(db, &obj(&s, caps)).glyphs.iter().find(|g| g.byte == 1).expect("the a is laid out").gid; + assert_ne!(drawn, face.glyph_for('a'), "All Caps draws the a as A"); + assert_eq!(reset(&mut s, caps, 1), json!(drawn), "the capital drawn"); + assert_eq!(chosen(&mut s, caps, 1), json!(drawn)); +} + /// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph /// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel /// sign's. From d13f7324f9eb81878317fd92a9b7004a756f7c15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:25:58 -0800 Subject: [PATCH 61/83] Dimension tool: a dimension selected with its art stays live through Expand and Outline Stroke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dimension selected with the art it measures became a plain group of paths and text when Object › Expand, Object › Expand Appearance or Object › Path › Outline Stroke ran, so it no longer redrew when moved or restyled. These commands now leave such a dimension's lines and label as they are, also inside selected groups without fills, strokes or effects of their own, and change only the other art. The dimension keeps its export assets and variable bindings. When the new art no longer fits the dimension's link, for example because the outlined stroke has other anchors, the dimension stays where it was, no longer linked, as it does when its art is deleted. Undo links it again. When the dimension is all the command would change, the command changes nothing and reports the error it gives for a selection with nothing to change. Object › Expand… is no longer dimmed for the label of such a dimension. A dimension selected without the art it measures, a part of one, and one inside a selected group with an appearance of its own still become plain groups, and Type › Create Outlines still outlines the label. Docs: docs/dimensions.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/dimension.rs | 168 ++++++++++++++-- crates/engine/src/cmd/effectcmd.rs | 35 +++- crates/engine/src/cmd/expand.rs | 46 +++-- crates/engine/src/cmd/pathops.rs | 16 +- crates/engine/src/cmd/typecmd.rs | 5 +- crates/engine/tests/it/dimensions.rs | 249 +++++++++++++++++++++--- crates/engine/tests/plugin_safe_mode.rs | 40 ++++ docs/dimensions.md | 29 ++- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 10 files changed, 510 insertions(+), 84 deletions(-) diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index fa2137c9d1..e1b88d5d9f 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -272,9 +272,9 @@ impl EndedLink { } /// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it -/// measured. A command that replaces art calls this before it changes anything, since replacing -/// the art a dimension measures would otherwise leave the dimension unlinked, and then -/// [`restore_unchanged`]. +/// measured. A command that replaces art calls this before it changes anything and +/// [`restore_unchanged`] after, so that a dimension whose own art the command changed stays a +/// plain group. pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec { let mut ended = Vec::new(); for id in reached(doc, roots) { @@ -287,18 +287,156 @@ pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec ended } -/// The dimensions in `ended` whose art is as it was are live again. -pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec) { +/// The dimensions in `ended` whose own art is as it was are live again. One whose measured art the +/// command changed from `before` so that the art no longer fits its link stays where it was, no +/// longer linked, as [`refresh`] leaves a dimension whose art was deleted. +pub(crate) fn restore_unchanged(before: &Document, doc: &mut Document, ended: Vec) { for e in ended { - if doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art) - && let Some(n) = doc.node_mut(e.id) - { - n.extras_mut().dimension = Some(Box::new(e.recipe)); + if !doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art) { + continue; + } + let recipe = if e.source_kept(before, doc) { e.recipe } else { unlinked(&e.recipe) }; + if let Some(n) = doc.node_mut(e.id) { + n.extras_mut().dimension = Some(Box::new(recipe)); doc.dimensions = true; } } } +/// `old` where it was, no longer linked. A move it had on its own and not yet drawn is kept when +/// the moved dimension is valid. +fn unlinked(old: &Dimension) -> Dimension { + let mut unlinked = old.clone(); + unlinked.source = None; + unlinked.moved = None; + if let Some(v) = old.moved { + let mut shifted = unlinked.clone(); + (shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v); + if shifted.validate().is_ok() { + unlinked = shifted; + } + } + unlinked +} + +/// The whole dimensions under `roots` that are selected together with art they measure (art under +/// `roots`), each one a root or held by groups without fills, strokes or effects of their own. +/// Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave their +/// lines and label as they are. A group with an appearance of its own changes everything it holds +/// when it expands, its dimensions included. +pub(crate) fn with_their_art(doc: &Document, roots: &[NodeId]) -> Vec { + if !doc.dimensions { + return Vec::new(); + } + let mut found = Vec::new(); + for root in roots { + let Some(n) = doc.node(*root) else { continue }; + n.walk(&mut |c| { + if let Some(source) = c.extras().dimension.as_ref().and_then(|d| d.source.as_ref()) { + found.push((*root, c.id, source.nodes())); + } + }); + } + let under_roots = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().any(|a| roots.contains(a))); + found + .into_iter() + .filter(|(root, id, _)| { + let Some(ancestry) = doc.ancestry(*id) else { return false }; + let from = ancestry.iter().position(|a| a == root).unwrap_or(ancestry.len()); + ancestry.get(from..ancestry.len().saturating_sub(1)).unwrap_or_default().iter().all(|a| doc.node(*a).is_some_and(plain_group)) + }) + .filter(|(_, _, measured)| measured.iter().any(|m| under_roots(*m))) + .map(|(_, id, _)| id) + .collect() +} + +/// A group or layer without fills, strokes or effects of its own. +fn plain_group(n: &Node) -> bool { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && n.appearance.items.is_empty() && n.appearance.effects.is_empty() +} + +/// A dimension [`lift`] took out of the document, with its place, the export assets that list it or +/// its parts (with their places in the asset list) and its parts' variable bindings. +pub(crate) struct Lifted { + parent: Option, + index: usize, + node: Arc, + assets: Vec<(usize, vectorcraft_doc::assets::ExportAsset)>, + bindings: Vec<(NodeId, std::collections::BTreeSet)>, +} + +impl Lifted { + pub(crate) fn id(&self) -> NodeId { + self.node.id + } +} + +/// Takes the [`with_their_art`] dimensions under `roots` out of `doc`, so a command that replaces +/// art does not reach them; [`put_back`] puts them back. +pub(crate) fn lift(doc: &mut Document, roots: &[NodeId]) -> Vec { + let mut lifted = Vec::new(); + for id in with_their_art(doc, roots) { + let Some((parent, index, _)) = doc.position(id) else { continue }; + let mut parts = std::collections::BTreeSet::new(); + if let Some(n) = doc.node(id) { + n.walk(&mut |c| { + parts.insert(c.id); + }); + } + let assets = doc.assets.iter().enumerate().filter(|(_, a)| a.nodes.iter().any(|n| parts.contains(n))).map(|(i, a)| (i, a.clone())).collect(); + let bindings = doc.variables.bindings.iter().filter(|(n, _)| parts.contains(n)).map(|(n, b)| (*n, b.clone())).collect(); + if let Ok(node) = doc.remove(id) { + lifted.push(Lifted { parent, index, node, assets, bindings }); + } + } + lifted +} + +/// Each dimension [`lift`] took out, as it was, back in its place in `doc`, with its parts back in +/// the export assets that listed them and their variable bindings back: edits made while it was out +/// let go of them. A dimension whose group is gone goes on top of the first layer. +pub(crate) fn put_back(doc: &mut Document, lifted: Vec) { + for l in lifted.into_iter().rev() { + let parent = if doc.children(l.parent).is_some() { l.parent } else { doc.layers.first().map(|layer| layer.id) }; + let Ok(ch) = doc.children_mut(parent) else { continue }; + let i = if parent == l.parent { l.index.min(ch.len()) } else { ch.len() }; + ch.insert(i, l.node); + doc.dimensions = true; + for (at, saved) in l.assets { + let there: Vec = saved.nodes.iter().copied().filter(|n| doc.node(*n).is_some()).collect(); + if let Some(a) = doc.assets.iter_mut().find(|a| a.id == saved.id) { + for (k, n) in there.iter().enumerate() { + if !a.nodes.contains(n) { + let k = k.min(a.nodes.len()); + a.nodes.insert(k, *n); + } + } + } else if !there.is_empty() { + let at = at.min(doc.assets.len()); + doc.assets.insert(at, vectorcraft_doc::assets::ExportAsset { nodes: there, ..saved }); + } + } + for (n, b) in l.bindings { + doc.variables.bindings.entry(n).or_insert(b); + } + } +} + +/// `doc` without the [`with_their_art`] dimensions under `roots`, to see what a command that leaves +/// them alone would change: `doc` itself when there are none. +pub(crate) fn without_kept<'a>(doc: &'a Document, roots: &[NodeId]) -> std::borrow::Cow<'a, Document> { + let ids = with_their_art(doc, roots); + if ids.is_empty() { + return std::borrow::Cow::Borrowed(doc); + } + let mut view = doc.clone(); + for id in ids { + // A dimension already gone (inside another one removed) needs nothing more. + let _ = view.remove(id); + } + std::borrow::Cow::Owned(view) +} + /// Called inside every edit, so dimensions and their undo history stay in step with the art they /// measure. Returns at once in documents without dimensions. pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { @@ -320,17 +458,7 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { // The art it measured was deleted, or rebuilt with other anchors, or no longer fits // (an ellipse that was a circle): it stays where it was, no longer linked, in this // same undo step, rather than attaching to a different edge. - let mut unlinked = old.clone(); - unlinked.source = None; - unlinked.moved = None; - if let Some(v) = moved { - let mut shifted = unlinked.clone(); - (shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v); - if shifted.validate().is_ok() { - unlinked = shifted; - } - } - if replace(doc, id, unlinked).is_err() + if replace(doc, id, unlinked(&old)).is_err() && let Some(n) = doc.node_mut(id) { // Its recipe cannot be drawn again: its art stays as it is, as a plain group. diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index a19455bd51..ade33d4bea 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", can_expand, expand_appearance ), @@ -674,11 +674,19 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> { /// fills, strokes or effects of its own or such members, other objects with effects, or type with /// fills or strokes of its own? pub(crate) fn expandable(n: &Node) -> bool { + expandable_except(n, &[]) +} + +/// [`expandable`], leaving out the objects `skip` lists and what they hold. +pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool { + if skip.contains(&n.id) { + return false; + } match &n.kind { NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } => false, NodeKind::Path { .. } | NodeKind::Compound { .. } => !n.appearance.is_basic() || vectorcraft_brush::has_brush(n), NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - !n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable(c)) + !n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip)) } NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(), NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), @@ -688,9 +696,11 @@ pub(crate) fn expandable(n: &Node) -> bool { fn can_expand(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; - let d = &s.doc().map_err(|e| e.to_string())?.doc; let ids = appearance_targets(s, &Value::Null).map_err(|e| e.to_string())?; - if ids.iter().filter_map(|id| d.node(*id)).any(expandable) { + let d = &s.doc().map_err(|e| e.to_string())?.doc; + // A dimension selected with the art it measures is left as it is. + let kept = super::dimension::with_their_art(d, &ids); + if ids.iter().filter_map(|id| d.node(*id)).any(|n| expandable_except(n, &kept)) { Ok(()) } else { Err("select (or target) objects whose appearance isn't basic".into()) @@ -975,7 +985,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the // geometry it hasn't changed. if vectorcraft_plugins::safe_mode::active() { - let d = &s.doc()?.doc; + // A dimension selected with the art it measures is left as it is. + let d = &*super::dimension::without_kept(&s.doc()?.doc, &roots); let mut seen = std::collections::HashSet::new(); if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) { return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into())); @@ -985,20 +996,24 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); let ids = s.edit("Expand Appearance", |d, _| { let before = d.clone(); - let mut ended = super::dimension::end_links(d, &roots); + // A dimension selected with the art it measures keeps its own lines and label: it is out + // of the document while the art expands. + let lifted = super::dimension::lift(d, &roots); + let kept = !lifted.is_empty(); + let ended = super::dimension::end_links(d, &roots); let brushes = vectorcraft_brush::library(d); let mut out = vec![]; let threaded = super::threads::frames(d); for id in &roots { expand_node(d, *id, &brushes, &mut out); } - // A dimension whose source was replaced stays plain: its link no longer fits that art. - ended.retain(|e| e.source_kept(&before, d)); - super::dimension::restore_unchanged(d, ended); + super::dimension::put_back(d, lifted); + // A dimension whose source was replaced stays where it was, no longer linked. + super::dimension::restore_unchanged(&before, d, ended); // Outlined frames of threaded text leave their threads with the text they show; type that // stays type under a new id takes its frame's place. super::threads::leave_threads(d, &threaded); - if out.is_empty() { + if out.is_empty() || (kept && d.layers == before.layers) { return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?; diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index c5c0fbd65b..ffb58d9d4b 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -5,7 +5,8 @@ //! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform //! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip //! group shaped like the object. Create Gradient Mesh shares the sampling. A dimension whose art -//! Expand changes becomes a plain group of that art. +//! Expand changes becomes a plain group of that art, except one selected with art it measures, +//! which Expand leaves as it is. use std::collections::BTreeSet; use std::sync::Arc; @@ -43,7 +44,7 @@ pub fn specs() -> Vec { "Expand…", ["Object"], None, - "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art → {ids}", + "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}", has_selection, expand ), @@ -55,7 +56,8 @@ pub fn specs() -> Vec { "{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)", has_selection, |s, _| { - let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); + let roots = selected_roots(s)?; + let e = Expandable::of(&super::dimension::without_kept(&s.doc()?.doc, &roots), &roots); let mut info = json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)}); if e.symbols { @@ -74,7 +76,9 @@ pub fn specs() -> Vec { /// (#3089); `object.expand` itself still bakes them. pub fn has_appearance(s: &Session) -> bool { let (Ok(st), Ok(roots)) = (s.doc(), selected_roots(s)) else { return false }; - roots.iter().filter_map(|r| st.doc.node(*r)).any(super::effectcmd::expandable) + // A dimension selected with the art it measures is left as it is. + let kept = super::dimension::with_their_art(&st.doc, &roots); + roots.iter().filter_map(|r| st.doc.node(*r)).any(|n| super::effectcmd::expandable_except(n, &kept)) } /// Every placed document in `roots` of `d` (at any depth) replaced by an editable copy of the art it @@ -241,9 +245,18 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result { let stroke = switch_or(p, "stroke", true, C)?; let to = GradientTo::parse(p)?; let from = s.doc()?.history.undo.len(); - let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); // Before anything expands: outlining the art a dimension measures would leave the dimension unlinked. let before = s.doc()?.doc.clone(); + let selected = s.doc()?.selection.objects.clone(); + // A dimension selected with the art it measures keeps its own lines and label: it is out of the + // document while the art expands, so no step below reaches it. + let roots = selected_roots(s)?; + let mut lifted = vec![]; + if !super::dimension::with_their_art(&before, &roots).is_empty() { + lifted = s.edit("Expand", |d, _| Ok(super::dimension::lift(d, &roots)))?; + } + let kept: Vec = lifted.iter().map(super::dimension::Lifted::id).collect(); + let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); let mut ended = vec![]; end_dimension_links(s, &mut ended)?; let rev0 = s.doc()?.revision; @@ -339,14 +352,25 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result { if s.doc()?.revision == rev0 { return Err(EngineError::Other("Expand: nothing to expand".into())); } - if !ended.is_empty() { - // A dimension whose source Expand replaced stays plain: its link no longer fits that art. - let after = s.doc()?.doc.clone(); - ended.retain(|e| e.source_kept(&before, &after)); - s.edit("Expand", |d, _| { - super::dimension::restore_unchanged(d, std::mem::take(&mut ended)); + if !ended.is_empty() || !lifted.is_empty() { + s.edit("Expand", |d, sel| { + if !lifted.is_empty() { + super::dimension::put_back(d, lifted); + // The dimensions put back follow what Expand made of the art they measure: a + // dimension whose art no longer fits its link stays where it was, no longer linked. + super::dimension::refresh(&before, d)?; + let mut ids = sel.objects.clone(); + let again: Vec = kept.iter().copied().filter(|id| selected.contains(id) && !ids.contains(id)).collect(); + ids.extend(again); + sel.set(ids); + } + // A dimension whose source Expand replaced stays where it was, no longer linked. + super::dimension::restore_unchanged(&before, d, ended); Ok(()) })?; + if !kept.is_empty() && s.doc()?.doc.layers == before.layers { + return Err(EngineError::Other("Expand: nothing to expand".into())); + } } squash(s, from, "Expand"); Ok(json!({ "ids": s.doc()?.selection.objects.iter().map(|i| i.0).collect::>() })) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 82de6fa93e..c8453c8c01 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Outline Stroke", ["Object", "Path"], None, - "{} replace stroked paths with filled outlines; a dimension whose lines are outlined, or selected with the art it measures when that art is outlined, becomes a plain group of its art → {ids}", + "{} replace stroked paths with filled outlines; a dimension whose lines are outlined becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines stay as they are, and if the outlined art no longer fits its link it stays where it was, no longer linked → {ids}", has_selection, outline_stroke ), @@ -1074,7 +1074,11 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Outline Stroke", |d, sel| { let before = d.clone(); - let mut ended = super::dimension::end_links(d, &roots); + // A dimension selected with the art it measures keeps its own lines: it is out of the + // document while the art is outlined. + let lifted = super::dimension::lift(d, &roots); + let kept = !lifted.is_empty(); + let ended = super::dimension::end_links(d, &roots); let brushes = vectorcraft_brush::library(d); let mut new_sel = vec![]; let mut changed = 0; @@ -1083,10 +1087,10 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { new_sel.push(id); changed += n; } - // A dimension whose source was outlined stays plain: its link no longer fits that art. - ended.retain(|e| e.source_kept(&before, d)); - super::dimension::restore_unchanged(d, ended); - if changed == 0 { + super::dimension::put_back(d, lifted); + // A dimension whose source was outlined stays where it was, no longer linked. + super::dimension::restore_unchanged(&before, d, ended); + if changed == 0 || (kept && d.layers == before.layers) { return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into())); } sel.set(new_sel.iter().copied()); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 0ddd145942..48959c54e2 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -596,6 +596,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { if texts.is_empty() { return Err(EngineError::Other("Create Outlines: select text objects".into())); } + let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone()); let ended = super::dimension::end_links(d, &roots); let mut new_sel: Vec = roots.iter().copied().filter(|r| !texts.contains(r)).collect(); let mut out = vec![]; @@ -691,7 +692,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { new_sel.push(gid); } } - super::dimension::restore_unchanged(d, ended); + if let Some(before) = &before { + super::dimension::restore_unchanged(before, d, ended); + } // Outlined frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); sel.set(new_sel); diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 934108905c..56ee67be17 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -1164,16 +1164,10 @@ fn an_expand_that_changes_no_art_leaves_a_dimension_live() { assert_eq!(art(&s, id), live); } -/// A dimension selected with the art it measures, or held by a selected group, expands the same -/// way: outlining that art does not remove it. +/// A dimension held by a selected group without the art it measures expands as a dimension +/// selected on its own does. #[test] -fn a_dimension_expanded_with_its_art_or_in_a_group_stays_plain_art() { - let mut s = session(); - let line = edge(&mut s); - let id = dim(&mut s, line); - run(&mut s, "select.set", json!({"ids":[line, id]})); - run(&mut s, "object.expand", json!({})); - stays_plain_art(&mut s, id); +fn a_dimension_expanded_in_a_group_without_its_art_stays_plain_art() { let mut s = session(); let line = edge(&mut s); let id = dim(&mut s, line); @@ -1183,8 +1177,176 @@ fn a_dimension_expanded_with_its_art_or_in_a_group_stays_plain_art() { stays_plain_art(&mut s, id); } -/// Expand replacing only the art a selected dimension measures leaves the dimension's art as it -/// is, without a link to the art that went. +/// `command` on a dimension selected with the art it measures, or on a group holding both, leaves +/// the dimension's own lines and label as they are and replaces only the art: the dimension stays +/// where it was, no longer linked, and one undo links it again. +fn keeps_its_own_lines_and_label(command: &str) { + for grouped in [false, true] { + let context = format!("{command}, grouped: {grouped}"); + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + run(&mut s, "select.set", json!({"ids":[art_id]})); + run(&mut s, "appearance.addStroke", json!({})); + let id = dim(&mut s, art_id); + let live = art(&s, id); + let label = text(&s, id); + let at = bounds(&s, id); + let linked = recipe(&s, id); + let measured = s.doc().unwrap().doc.node(NodeId(art_id)).unwrap().clone(); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + if grouped { + run(&mut s, "object.group", json!({})); + } + let steps = s.doc().unwrap().history.undo.len(); + let result = run(&mut s, command, json!({})); + if command == "effect.expandAppearance" { + let mut own = vec![]; + s.doc().unwrap().doc.node(NodeId(id)).unwrap().walk(&mut |c| own.push(json!(c.id.0))); + assert!(result["ids"].as_array().unwrap().iter().all(|i| !own.contains(i)), "{context}: {result}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{context}: one undo step"); + assert_ne!(s.doc().unwrap().doc.node(NodeId(art_id)), Some(&measured), "{context}: the art is replaced"); + assert_eq!(art(&s, id), live, "{context}: its own lines and label"); + assert_eq!(bounds(&s, id), at, "{context}: where it was"); + stays_unlinked(&mut s, id, &label, &context); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "{context}"); + assert_eq!(recipe(&s, id), linked, "{context}: one undo links it again"); + assert_eq!(s.doc().unwrap().doc.node(NodeId(art_id)), Some(&measured), "{context}"); + } +} + +#[test] +fn expand_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("object.expand"); +} + +#[test] +fn expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("effect.expandAppearance"); +} + +#[test] +fn outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("object.path.outlineStroke"); +} + +/// A selected group whose blur Expand Appearance turns into an image takes the dimension it holds, +/// with the art it measures, into that image. +#[test] +fn a_blurred_group_expanded_takes_its_dimension_into_the_image() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + let id = dim(&mut s, art_id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[group]})); + run(&mut s, "effect.apply", json!({"effect":"blur.gaussian"})); + run(&mut s, "effect.expandAppearance", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(id)).is_none(), "the dimension is part of the image"); + let mut images = 0; + d.walk(|n| images += usize::from(matches!(n.kind, NodeKind::Image(_)))); + assert_eq!(images, 1); +} + +/// Object › Expand keeps a dimension selected with its art in the export assets that list it and +/// bound to its variables. +#[test] +fn expand_keeps_a_dimension_in_its_asset_and_its_variable_binding() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + let id = dim(&mut s, art_id); + let asset = run(&mut s, "assets.add", json!({"ids":[id]}))["assets"][0].as_u64().unwrap(); + run(&mut s, "variable.define", json!({"name":"Shown","kind":"visibility"})); + run(&mut s, "variable.bind", json!({"variable":"Shown","ids":[id]})); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + run(&mut s, "object.expand", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(id)).is_some_and(|n| n.extras().dimension.is_some()), "still a dimension"); + let listed = d.assets.iter().find(|a| a.id == asset).map(|a| a.nodes.clone()); + assert_eq!(listed, Some(vec![NodeId(id)]), "in its asset"); + assert!(d.variables.bindings.get(&NodeId(id)).is_some_and(|b| b.contains("Shown")), "bound to its variable"); +} + +/// A selected group with a geometry effect of its own bakes that effect into everything it holds +/// when its appearance expands, the dimension's lines and label included: the dimension becomes a +/// plain group of that art, as one selected without its art does. +#[test] +fn a_group_effect_expanded_reaches_the_dimension_it_holds() { + for command in ["effect.expandAppearance", "object.expand"] { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + let id = dim(&mut s, art_id); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[group]})); + run(&mut s, "effect.apply", json!({"effect":"distort.puckerBloat"})); + run(&mut s, command, json!({})); + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap_or_else(|| panic!("{command}: the dimension's group is still there")); + assert!(n.extras().dimension.is_none(), "{command}: a plain group"); + assert_ne!(art(&s, id), live, "{command}: its art is baked with the group's effect"); + } +} + +/// When the dimension selected with its art is all there is to change, the command fails and +/// changes nothing. +#[test] +fn a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[art_id]})); + run(&mut s, "paint.setStroke", json!({"none": true})); + // A plain path: Expand would make a live rectangle a path. + run(&mut s, "object.expand", json!({})); + let id = dim(&mut s, art_id); + for grouped in [false, true] { + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + if grouped { + run(&mut s, "object.group", json!({})); + } + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["appearance"], json!(false), "grouped: {grouped}: Object › Expand… is not dimmed for the dimension's label"); + assert_eq!(info["stroke"], json!(false), "grouped: {grouped}: {info}"); + assert!(!vectorcraft_engine::cmd::expand::has_appearance(&s), "grouped: {grouped}: the menus read this"); + for (command, p) in [ + ("object.expand", json!({})), + ("object.expand", json!({"object":false,"fill":false})), + ("object.path.outlineStroke", json!({})), + ("effect.expandAppearance", json!({})), + ] { + assert!(s.execute(command, &p).is_err(), "grouped: {grouped}: {command} {p}"); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "grouped: {grouped}: {command} {p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "grouped: {grouped}: {command} {p}"); + } + } +} + +/// The dimension `id` is a dimension that measures nothing, still showing `label`, and a move +/// takes it along without redrawing it from other art. +fn stays_unlinked(s: &mut Session, id: u64, label: &str, context: &str) { + let live = art(s, id); + assert!(live.2, "{context}: still a dimension"); + assert!(recipe(s, id).source.is_none(), "{context}: no longer linked"); + assert_eq!(text(s, id), label, "{context}"); + let at = bounds(s, id); + run(s, "select.set", json!({"ids":[id]})); + run(s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(s, id), live, "{context}"); + assert_eq!(text(s, id), label, "{context}"); + let moved = bounds(s, id); + assert!((moved[0] - at[0] - 30.0).abs() < 1e-6 && (moved[1] - at[1]).abs() < 1e-6, "{context}: {at:?} moved to {moved:?}"); + run(s, "edit.undo", json!({})); +} + +/// Expand replacing only the art a selected dimension measures leaves the dimension where it was, +/// still a dimension, without a link to the art that went; undo links it again. #[test] fn a_dimension_keeps_no_link_to_the_art_expand_replaced() { for circle in [false, true] { @@ -1197,18 +1359,21 @@ fn a_dimension_keeps_no_link_to_the_art_expand_replaced() { } else { dim(&mut s, art_id) }; - let (nodes, labels, _) = art(&s, id); + let live = art(&s, id); + let label = text(&s, id); run(&mut s, "select.set", json!({"ids":[art_id, id]})); run(&mut s, "object.expand", json!({"object":false,"stroke":false})); - assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); - run(&mut s, "select.set", json!({"ids":[id]})); - run(&mut s, "object.move", json!({"dx":30,"dy":0})); - assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); + stays_unlinked(&mut s, id, &label, &format!("circle: {circle}")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "circle: {circle}"); + assert!(recipe(&s, id).source.is_some(), "circle: {circle}: one undo links it again"); } } -/// Outline Stroke and Expand Appearance replacing the art a selected dimension measures leave the -/// dimension as a plain group, whether or not they change its own art. +/// Outline Stroke and Expand Appearance replacing only the art a selected dimension measures +/// leave the dimension where it was, still a dimension, no longer linked; undo links it again. +/// Here the dimension's lines are guides, which neither command changes, and the selection holds +/// the whole dimension or one of its lines. #[test] fn a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced() { for command in ["object.path.outlineStroke", "effect.expandAppearance"] { @@ -1225,19 +1390,44 @@ fn a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced() { }; run(&mut s, "select.set", json!({"ids":lines})); run(&mut s, "view.guides.make", json!({})); + let live = art(&s, id); + let label = text(&s, id); let picked = if whole { id } else { lines[0] }; run(&mut s, "select.set", json!({"ids":[art_id, picked]})); run(&mut s, command, json!({})); assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "{command} removed the dimension, whole: {whole}"); - let plain = art(&s, id); - assert!(!plain.2, "{command}: no recipe left, whole: {whole}"); - run(&mut s, "select.set", json!({"ids":[id]})); - run(&mut s, "object.move", json!({"dx":30,"dy":0})); - assert_eq!(art(&s, id), plain, "{command}, whole: {whole}"); + stays_unlinked(&mut s, id, &label, &format!("{command}, whole: {whole}")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "{command}, whole: {whole}"); + assert!(recipe(&s, id).source.is_some(), "{command}, whole: {whole}: one undo links it again"); } } } +/// Object › Expand that outlines only the stroke of the art a selected dimension measures leaves +/// the dimension a dimension, no longer linked, as Outline Stroke does. +#[test] +fn a_dimension_outlasts_the_stroke_expand_outlined() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + let id = dim(&mut s, art_id); + let lines: Vec = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().filter(|c| matches!(c.kind, NodeKind::Path { .. })).map(|c| c.id.0).collect() + }; + run(&mut s, "select.set", json!({"ids":lines})); + run(&mut s, "view.guides.make", json!({})); + let live = art(&s, id); + let label = text(&s, id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + run(&mut s, "object.expand", json!({"object":false,"fill":false})); + stays_unlinked(&mut s, id, &label, "object.expand stroke"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live); + assert!(recipe(&s, id).source.is_some(), "one undo links it again"); +} + /// A part of a dimension expanded on its own ends the link too, so the move does not undo it. #[test] fn expanding_a_part_of_a_dimension_ends_its_link() { @@ -1271,10 +1461,11 @@ fn a_dimension_in_an_expanded_symbol_instance_stays_plain_art() { stays_plain_art(&mut s, root); } -/// Create Outlines on a dimension, or on its label alone, ends the link in the same undo step. +/// Create Outlines on a dimension, also one selected with the art it measures, or on its label +/// alone, ends the link in the same undo step. #[test] fn outlining_a_dimension_or_its_label_ends_its_link() { - for label_alone in [false, true] { + for target in ["dimension", "label", "with its art"] { let mut s = session(); let line = edge(&mut s); let id = dim(&mut s, line); @@ -1283,8 +1474,12 @@ fn outlining_a_dimension_or_its_label_ends_its_link() { let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); children.iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().id }; - let target = if label_alone { label.0 } else { id }; - run(&mut s, "select.set", json!({"ids":[target]})); + let ids = match target { + "label" => vec![label.0], + "with its art" => vec![line, id], + _ => vec![id], + }; + run(&mut s, "select.set", json!({"ids":ids})); run(&mut s, "type.createOutlines", json!({})); stays_plain_art(&mut s, id); run(&mut s, "edit.undo", json!({})); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 878ec6bf59..2c5fc1c307 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -462,3 +462,43 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { safe_mode::set_active(Some(safe_mode::Source::Flag)); s.execute("effect.expandAppearance", &json!({})).unwrap(); } + +/// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop +/// Expand Appearance: the dimension is left as it is, its effect included, and the art expands. +#[test] +fn expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.dim", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 72, "height": 72})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [art], "color": "#000000"})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + let source = json!({"kind": "segment", "edge": {"node": art, "subpath": 0, "segment": 0}}); + let dim = s.execute("dimension.create", &json!({"source": source})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [dim]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.dim"})).unwrap(); + s.execute("select.set", &json!({"ids": [art, dim]})).unwrap(); + let node = |s: &mut Session, id: &Value| { + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + let mut found = Value::Null; + let mut stack = vec![inspect["layers"].clone()]; + while let Some(v) = stack.pop() { + match v { + Value::Array(a) => stack.extend(a), + Value::Object(o) if o.get("id") == Some(id) => found = Value::Object(o), + Value::Object(o) => stack.extend(o.into_iter().map(|(_, v)| v)), + _ => {} + } + } + found + }; + let kept = node(&mut s, &dim); + let measured = node(&mut s, &art); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + safe_mode::set_active(None); + assert_ne!(node(&mut s, &art), measured, "the art expands"); + assert_eq!(node(&mut s, &dim), kept, "the dimension and its effect stay as they are"); +} diff --git a/docs/dimensions.md b/docs/dimensions.md index bcd08c3b83..6f11a29c96 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -74,14 +74,27 @@ paths and text as ordinary art. Object › Expand, Object › Expand Appearance, and Object › Path › Outline Stroke turn a dimension whose art they change into a plain group of that art, also when they reach only a part of it: moving or scaling the group does not redraw it, it does not follow the art it measured, and undoing the command gives the live dimension back. The menus dim -Object › Expand… while a whole dimension is selected, because its label has appearance items; -Object › Expand Appearance and the `object.expand` command still reach it. A dimension selected with -the art it measures also becomes a plain group when Object › Expand, Object › Expand Appearance or -Object › Path › Outline Stroke changes only that art and the art no longer fits the dimension's link, -for example because its number of anchors changed. When the art keeps its id and anchor count and the -dimension's own art does not change, the dimension stays live and its label shows the new length. Pasted -dimensions keep their geometry and drop their links, so they never bind to unrelated art in another -document. +Object › Expand… while a whole dimension is selected without the art it measures, because its label +has appearance items; Object › Expand Appearance and the `object.expand` command still reach it. + +When a whole dimension is selected together with art it measures, directly or in selected groups +without fills, strokes or effects of their own, Object › Expand, Object › Expand Appearance and +Object › Path › Outline Stroke leave the dimension's lines and label as they are and change only the +other art. The menus do not dim Object › Expand… for the label of such a dimension. If the new art no +longer fits the dimension's link, for example because its number of anchors changed, the dimension +stays where it was, no longer linked, as it does when its art is deleted. Undoing the command links +it again. When the art keeps its id and anchor count, the dimension stays linked and its label shows +the new length. When the dimension is all the command would change, the command changes nothing and +reports the error it gives for a selection with nothing to change: "Expand: nothing to expand", +"Expand Appearance: the selection has a basic appearance" or "Outline Stroke: no stroked paths +selected". A selected group with fills, strokes or effects of its own changes everything it holds +when its appearance expands, its dimensions included: a geometry effect is baked into their lines +and label, which become a plain group, and a blur, feather or inner glow turns them into part of the +image that replaces the group's art. Type › Create Outlines still outlines the label of a dimension +selected with its art, which turns the dimension into a plain group. + +Pasted dimensions keep their geometry and drop their links, so they never bind to unrelated art in +another document. ## Commands diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..21ab8a4149 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3602,7 +3602,10 @@ holds symbol instances that `object` expands, whether only their art holds it, w `object` on), and `object.mesh.create` on a gradient-filled object colours the mesh points as the gradient paints them, with the colors Object › Expand gives them. `object.expand`, `effect.expandAppearance`, `type.createOutlines` and `object.path.outlineStroke` turn a dimension whose -art they change into a plain group of that art, in the same undo step (see [dimensions.md](dimensions.md)). +art they change into a plain group of that art, in the same undo step. `object.expand`, `effect.expandAppearance` and +`object.path.outlineStroke` leave a dimension selected with art it measures, directly or in groups without fills, +strokes or effects of their own, as it is and change only the other art; if the new art no longer fits the dimension's +link, the dimension stays where it was, no longer linked (see [dimensions.md](dimensions.md)). `object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and changes nothing. Omitting a param or giving null keeps its default. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cdcda0f6e6..70eb7877c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -566,6 +566,7 @@ since 2026-10-01. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. +**Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. From 3c44a8ad7c98995861c412aae061a3d984bab785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabio=20William=20Concei=C3=A7=C3=A3o?= Date: Tue, 10 Nov 2026 20:36:20 +0000 Subject: [PATCH 62/83] G5: built-in Status Effects graphic style library Eight style libraries; MCP docs list Status Effects and catch up Symbol libraries with UI Frames and Map Markers. --- crates/doc/src/style_libs.rs | 42 +++++++++++++++++++++++++++++ crates/engine/src/tests/stylelib.rs | 12 ++++++++- crates/ui-egui/src/i18n/bg.tsv | 7 +++++ crates/ui-egui/src/i18n/bs.tsv | 7 +++++ crates/ui-egui/src/i18n/ca.tsv | 7 +++++ crates/ui-egui/src/i18n/cs.tsv | 7 +++++ crates/ui-egui/src/i18n/da.tsv | 7 +++++ crates/ui-egui/src/i18n/de.tsv | 7 +++++ crates/ui-egui/src/i18n/el.tsv | 7 +++++ crates/ui-egui/src/i18n/es.tsv | 7 +++++ crates/ui-egui/src/i18n/fi.tsv | 7 +++++ crates/ui-egui/src/i18n/fr.tsv | 7 +++++ crates/ui-egui/src/i18n/hi.tsv | 7 +++++ crates/ui-egui/src/i18n/hu.tsv | 7 +++++ crates/ui-egui/src/i18n/id.tsv | 7 +++++ crates/ui-egui/src/i18n/it.tsv | 7 +++++ crates/ui-egui/src/i18n/ja.tsv | 7 +++++ crates/ui-egui/src/i18n/ka.tsv | 7 +++++ crates/ui-egui/src/i18n/ko.tsv | 7 +++++ crates/ui-egui/src/i18n/nl.tsv | 7 +++++ crates/ui-egui/src/i18n/pl.tsv | 7 +++++ crates/ui-egui/src/i18n/pt-br.tsv | 7 +++++ crates/ui-egui/src/i18n/ru.tsv | 7 +++++ crates/ui-egui/src/i18n/sv.tsv | 7 +++++ crates/ui-egui/src/i18n/tr.tsv | 7 +++++ crates/ui-egui/src/i18n/uk.tsv | 7 +++++ crates/ui-egui/src/i18n/vi.tsv | 7 +++++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 +++++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 +++++ docs/gaps.md | 14 +++++----- docs/mcp.md | 2 +- docs/roadmap.md | 3 ++- docs/target-app-parity.md | 7 ++--- 33 files changed, 257 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 90424d5bc2..f64bdb4300 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -159,6 +159,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud }, + BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects }, ]; /// Built-in library `id`, made once. @@ -482,6 +483,43 @@ fn game_hud() -> Vec { ] } +/// Status Effects: buffs and debuffs for RPG/gamedev art (original, catalogue stylize effects only). +fn status_effects() -> Vec { + let stealth = GraphicStyle { + opacity: 0.45, + blend: BlendMode::Normal, + ..style("Stealth Fade", vec![F(fill("#7f8c8d")), S(stroke("#2c3e50", 1.0))], vec![]) + }; + vec![ + style( + "Poison Tint", + vec![F(fill("#2ecc71"))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 80.0, "blur": 6.0, "color": "#58d68d"}))], + ), + style( + "Freeze Edge", + vec![F(fill("#aed6f1")), S(stroke("#5dade2", 2.0))], + vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 70.0, "blur": 5.0, "color": "#d6eaf8", "source": "edge"}))], + ), + style( + "Burn Aura", + vec![F(fill("#e67e22"))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 8.0, "color": "#f39c12"}))], + ), + style( + "Stun Pulse", + vec![F(fill("#f4d03f"))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 7.0, "color": "#f7dc6f"}))], + ), + stealth, + style( + "Shield Buff", + vec![F(fill("#85c1e9")), S(round("#2874a6", 2.0))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 70.0, "blur": 5.0, "color": "#5dade2"}))], + ), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -508,6 +546,10 @@ mod tests { assert_eq!(game.name, "Game HUD"); let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect(); assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); + let status = builtin_style_library("status-effects").unwrap(); + assert_eq!(status.name, "Status Effects"); + let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); } #[test] diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 43838ff8e0..5124fb4502 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -41,8 +41,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let mut s = session(); let list = run(&mut s, "graphicStyle.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -60,6 +61,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"})); let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); + let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"})); + let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); @@ -67,6 +71,12 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap())); assert_eq!(node.appearance.stroke_paint(), Paint::None); assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); + let id2 = rect(&mut s, 60.0, 20.0, 40.0, 30.0); + let r2 = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "status-effects", "name": "Poison Tint", "apply": true, "ids": [id2.0]})); + assert_eq!((names(&r2["added"]), r2["applied"].as_str()), (vec!["Poison Tint"], Some("Poison Tint"))); + let node2 = doc(&s).node(id2).unwrap(); + assert_eq!(node2.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#2ecc71").unwrap())); + assert_eq!(node2.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); // By name in any case. assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows"); assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2d49498798..ffe3c0bd9c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3071,6 +3071,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Бос + Status Effects Статус ефекти + Poison Tint Отрова + Freeze Edge Замразяване + Burn Aura Изгаряне + Stun Pulse Зашеметяване + Stealth Fade Скритост + Shield Buff Щит Shape Фигура Shape Builder Създател на фигури Shape Builder Regions Области на създателя на фигури diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 912eec6a6f..56075d8502 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -776,6 +776,13 @@ Quest Outline Zadatak Coin Shine Novčić Boss Alert Bos + Status Effects Statusni efekti + Poison Tint Otrov + Freeze Edge Zamrzavanje + Burn Aura Izgaranje + Stun Pulse Omamljenost + Stealth Fade Nevidljivost + Shield Buff Štit Outlines and Rules Obrisi i linije Hand-Drawn Ručno crtano Gradient Finishes Gradijentne završnice diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f12bb4a6ab..ee00ace343 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3955,6 +3955,13 @@ digits Malayalam Malaiàlam Quest Outline Missió Coin Shine Moneda Boss Alert Cap + Status Effects Efectes d’estat + Poison Tint Verí + Freeze Edge Congelació + Burn Aura Cremada + Stun Pulse Atordiment + Stealth Fade Sigil + Shield Buff Escut Shape Forma Shape Builder Constructor de formes Shape Builder Delete Suprimeix del constructor de formes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6d7965acd3..be4d6c4b0b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -783,6 +783,13 @@ Quest Outline Úkol Coin Shine Mince Boss Alert Boss + Status Effects Stavové efekty + Poison Tint Jed + Freeze Edge Zmrazení + Burn Aura Spálení + Stun Pulse Omráčení + Stealth Fade Plížení + Shield Buff Štít Outlines and Rules Obrysy a linky Hand-Drawn Ručně kreslené Gradient Finishes Přechodové povrchy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 53036e9dda..523d80dd0a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -722,6 +722,13 @@ Quest Outline Quest Coin Shine Mønt Boss Alert Boss + Status Effects Statuseffekter + Poison Tint Gift + Freeze Edge Frost + Burn Aura Brænd + Stun Pulse Bedøvelse + Stealth Fade Snige + Shield Buff Skjold Outlines and Rules Konturer og linjer Hand-Drawn Håndtegnet Gradient Finishes Gradientfinish diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e46a1b6ea2..a1fe39b994 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3117,6 +3117,13 @@ digits Malayalam Malayalam Quest Outline Quest Coin Shine Münze Boss Alert Boss + Status Effects Statuseffekte + Poison Tint Gift + Freeze Edge Frost + Burn Aura Brand + Stun Pulse Betäubung + Stealth Fade Schleichen + Shield Buff Schild Shape Form Shape Builder Formerstellung Shape Builder Regions Formerstellungsbereiche diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 98015264e0..33a13e502c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3624,6 +3624,13 @@ digits Malayalam Μαλαγιάλαμ Quest Outline Αποστολή Coin Shine Νόμισμα Boss Alert Αρχηγός + Status Effects Εφέ κατάστασης + Poison Tint Δηλητήριο + Freeze Edge Πάγωμα + Burn Aura Κάψιμο + Stun Pulse Ζάλη + Stealth Fade Αορασία + Shield Buff Ασπίδα Shape Builder Regions Περιοχές δημιουργίας σχημάτων Shape Effects Εφέ σχημάτων Shape Mode Λειτουργία σχήματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d5d844b234..6153e45ede 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3156,6 +3156,13 @@ digits Malayalam Malayálam Quest Outline Misión Coin Shine Moneda Boss Alert Jefe + Status Effects Efectos de estado + Poison Tint Veneno + Freeze Edge Congelación + Burn Aura Quemadura + Stun Pulse Aturdimiento + Stealth Fade Sigilo + Shield Buff Escudo Shape Forma Shape Builder Generador de formas Shape Builder Regions Regiones del generador de formas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 85b49e77e5..f4a0f90d7d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -774,6 +774,13 @@ Quest Outline Tehtävä Coin Shine Kolikko Boss Alert Bossi + Status Effects Tilatehosteet + Poison Tint Myrkky + Freeze Edge Jäädytys + Burn Aura Poltto + Stun Pulse Tainnutus + Stealth Fade Hiipiminen + Shield Buff Kilpi Outlines and Rules Ääriviivat ja viivat Hand-Drawn Käsin piirretyt Gradient Finishes Liukuväriviimeistelyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 43eb6d7579..14bbc40db7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3148,6 +3148,13 @@ digits Malayalam Malayalam Quest Outline Quête Coin Shine Pièce Boss Alert Boss + Status Effects Effets de statut + Poison Tint Poison + Freeze Edge Gel + Burn Aura Brûlure + Stun Pulse Étourdissement + Stealth Fade Furtivité + Shield Buff Bouclier Shape Forme Shape Builder Concepteur de forme Shape Builder Regions Zones du Concepteur de forme diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 796939065c..95bfbf3a21 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4267,6 +4267,13 @@ antiAlias Sharp शार्प Quest Outline क्वेस्ट Coin Shine सिक्का Boss Alert बॉस + Status Effects स्थिति प्रभाव + Poison Tint ज़हर + Freeze Edge ठंड + Burn Aura जलन + Stun Pulse स्तब्ध + Stealth Fade छिपना + Shield Buff ढाल Shaft: दस्ता: Shape शेप Shape Builder शेप बिल्डर diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ec7d13a8c0..14b27cda42 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3771,6 +3771,13 @@ mark-style Japanese Japán Quest Outline Küldetés Coin Shine Érme Boss Alert Főellenség + Status Effects Állapot hatások + Poison Tint Méreg + Freeze Edge Fagy + Burn Aura Égés + Stun Pulse Kábítás + Stealth Fade Lopakodás + Shield Buff Pajzs Shape Alakzat Shape Builder Alakzatépítő Shape Builder Regions Alakzatépítő területei diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 45d30eb0f0..4328a522ef 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -722,6 +722,13 @@ Quest Outline Quest Coin Shine Koin Boss Alert Boss + Status Effects Efek Status + Poison Tint Racun + Freeze Edge Beku + Burn Aura Bakar + Stun Pulse Pingsan + Stealth Fade Menghilang + Shield Buff Perisai Outlines and Rules Garis luar dan garis Hand-Drawn Gambar tangan Gradient Finishes Finishing gradien diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 419cf05828..0f383b9a63 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3193,6 +3193,13 @@ digits Malayalam Malayalam Quest Outline Missione Coin Shine Moneta Boss Alert Boss + Status Effects Effetti di stato + Poison Tint Veleno + Freeze Edge Gelo + Burn Aura Bruciatura + Stun Pulse Stordimento + Stealth Fade Furtività + Shield Buff Scudo Shape Forma Shape Builder Generatore forme Shape Builder Regions Aree del Generatore forme diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index effd2a9000..bbf0cd6e29 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -807,6 +807,13 @@ digits Malayalam マラヤーラム数字 Quest Outline クエスト Coin Shine コイン Boss Alert ボス + Status Effects ステータス効果 + Poison Tint 毒 + Freeze Edge 凍結 + Burn Aura 火傷 + Stun Pulse 気絶 + Stealth Fade ステルス + Shield Buff シールド Outlines and Rules アウトラインと罫線 Hand-Drawn 手描き風 Gradient Finishes グラデーション仕上げ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e1b2fceef6..f58d58c207 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -670,6 +670,13 @@ Quest Outline ქვესტი Coin Shine მონეტა Boss Alert ბოსი + Status Effects სტატუსის ეფექტები + Poison Tint შხამი + Freeze Edge გაყინვა + Burn Aura დაწვა + Stun Pulse დაბნეულობა + Stealth Fade შენიღბვა + Shield Buff ფარი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული Gradient Finishes გრადიენტული ზედაპირები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2fa677459f..e94dd0cef5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -800,6 +800,13 @@ digits Malayalam 말라얄람어 Quest Outline 퀘스트 Coin Shine 코인 Boss Alert 보스 + Status Effects 상태 효과 + Poison Tint 독 + Freeze Edge 빙결 + Burn Aura 화상 + Stun Pulse 기절 + Stealth Fade 은신 + Shield Buff 방패 Outlines and Rules 윤곽선과 괘선 Hand-Drawn 손그림 Gradient Finishes 그레이디언트 마감 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 10c923cd6e..7cc1b78018 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -736,6 +736,13 @@ Quest Outline Quest Coin Shine Munt Boss Alert Baas + Status Effects Statuseffecten + Poison Tint Gif + Freeze Edge Bevriezing + Burn Aura Brand + Stun Pulse Verdoving + Stealth Fade Sluipen + Shield Buff Schild Outlines and Rules Omtrekken en lijnen Hand-Drawn Handgetekend Gradient Finishes Verloopafwerkingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a4f8580ff5..f2e9e3bfee 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -730,6 +730,13 @@ Quest Outline Zadanie Coin Shine Moneta Boss Alert Boss + Status Effects Efekty statusu + Poison Tint Trucizna + Freeze Edge Mróz + Burn Aura Oparzenie + Stun Pulse Ogłuszenie + Stealth Fade Ukrycie + Shield Buff Tarcza Outlines and Rules Kontury i linie Hand-Drawn Rysowane odręcznie Gradient Finishes Wykończenia gradientowe diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2496b775e5..5c5ed5314a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2648,6 +2648,13 @@ digits Malayalam Malaiala Quest Outline Missão Coin Shine Moeda Boss Alert Chefe + Status Effects Efeitos de status + Poison Tint Veneno + Freeze Edge Congelamento + Burn Aura Queimadura + Stun Pulse Atordoamento + Stealth Fade Furtividade + Shield Buff Escudo Shape Forma Shape Builder Construtor de Formas Shape Builder Regions Regiões do Construtor de Formas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5f34c30eca..d97ce00b2c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3188,6 +3188,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Босс + Status Effects Эффекты статуса + Poison Tint Яд + Freeze Edge Заморозка + Burn Aura Ожог + Stun Pulse Оглушение + Stealth Fade Скрытность + Shield Buff Щит Shape Фигура Shape Builder Создание фигур Shape Builder Regions Области создания фигур diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index aab2451073..bf3fa9cf6a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3080,6 +3080,13 @@ digits Malayalam Malayalam Quest Outline Uppdrag Coin Shine Mynt Boss Alert Boss + Status Effects Statuseffekter + Poison Tint Gift + Freeze Edge Frost + Burn Aura Bränna + Stun Pulse Bedövning + Stealth Fade Smyga + Shield Buff Sköld Shape Form Shape Builder Formbyggare Shape Builder Regions Formbyggarområden diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 12e5a14e33..28b08c8b56 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2984,6 +2984,13 @@ digits Malayalam Malayalam Quest Outline Görev Coin Shine Jeton Boss Alert Boss + Status Effects Durum Etkileri + Poison Tint Zehir + Freeze Edge Donma + Burn Aura Yanma + Stun Pulse Sersemletme + Stealth Fade Gizlilik + Shield Buff Kalkan Shape Şekil Shape Builder Şekil Oluşturucu Shape Builder Regions Şekil Oluşturucu Bölgeleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a7854dc666..8c958e5b41 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3185,6 +3185,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Бос + Status Effects Ефекти статусу + Poison Tint Отрута + Freeze Edge Заморозка + Burn Aura Опік + Stun Pulse Оглушення + Stealth Fade Невидимість + Shield Buff Щит Shape Фігура Shape Builder Створення фігур Shape Builder Regions Області створення фігур diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ce683ff038..558dab9a9d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3517,6 +3517,13 @@ mark-style Japanese Kiểu Nhật Quest Outline Nhiệm vụ Coin Shine Xu Boss Alert Trùm + Status Effects Hiệu ứng trạng thái + Poison Tint Độc + Freeze Edge Đóng băng + Burn Aura Bỏng + Stun Pulse Choáng + Stealth Fade Ẩn thân + Shield Buff Khiên Shape Hình dạng Shape Builder Tạo hình dạng Shape Builder Regions Vùng Tạo hình dạng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 91d0e4e747..4e5debe0da 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3023,6 +3023,13 @@ digits Malayalam 马拉雅拉姆数字 Quest Outline 任务 Coin Shine 金币 Boss Alert 首领 + Status Effects 状态效果 + Poison Tint 中毒 + Freeze Edge 冰冻 + Burn Aura 灼烧 + Stun Pulse 眩晕 + Stealth Fade 隐身 + Shield Buff 护盾 Shape 形状 Shape Builder 形状生成器 Shape Builder Regions 形状生成器区域 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3993771016..c859122298 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4134,6 +4134,13 @@ digits Malayalam 馬來亞拉姆數字 Quest Outline 任務 Coin Shine 金幣 Boss Alert 首領 + Status Effects 狀態效果 + Poison Tint 中毒 + Freeze Edge 冰凍 + Burn Aura 灼燒 + Stun Pulse 暈眩 + Stealth Fade 隱身 + Shield Buff 護盾 Shape 形狀 Shape Builder 形狀建立 Shape Builder Regions 形狀建立區域 diff --git a/docs/gaps.md b/docs/gaps.md index f0619ff213..92ba84be3d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -89,7 +89,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 9–19 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 7–17 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -648,14 +648,15 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, Eyedropper), for that instance only; - graphic style libraries (Window › Graphic Style Libraries; seven original libraries generated in code, including - Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert; User Defined; Other + graphic style libraries (Window › Graphic Style Libraries; eight original libraries generated in code, including + Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert, and Status Effects + with Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade and Shield Buff; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the seven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the eight shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers and Inventory Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 7–17 h. +- **Estimate:** 6–16 h. ## G3 3D and Materials @@ -854,6 +855,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | | 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..1238fe8d05 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2967,7 +2967,7 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD). `graphicStyle.libraries` lists them +Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects). `graphicStyle.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `graphicStyle.library {library}` returns one's styles in the `graphicStyle.list` shape (`library` is an id or a name). `graphicStyle.addFromLibrary {library, name? | names?}` copies styles into the document's Graphic Styles as one undo step (no names: the whole library); styles the diff --git a/docs/roadmap.md b/docs/roadmap.md index 02e0a61fcd..82362eb94c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -189,6 +189,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M10/G5: Status Effects built-in graphic style library; MCP docs catch-up for UI Frames and Map Markers; estimates unchanged | | 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | M10/G5: Game HUD built-in graphic style library; estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cdcda0f6e6..1a9f630bb1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -538,7 +538,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~40% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have four (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons), graphic style libraries seven (including Game HUD) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~42% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have four (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons), graphic style libraries eight (including Game HUD and Status Effects) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -1315,7 +1315,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; seven generated style libraries (including Game HUD) save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eight generated style libraries (including Game HUD and Status Effects) save and load as `.vcstyles`. In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1963,6 +1963,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | | 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | From bcdb908b47e8d10830f9f939d53f556579c81e5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:38:30 -0800 Subject: [PATCH 63/83] Docs: the Control bar's Paragraph alignment buttons are pinned at 1536 pt #6090 moved the pinned window width in the_control_bar_shows_the_paragraph_alignment_of_the_selected_type from 1440 to 1536 pt, since the bar's right end now keeps room for the panel menu button. The progress line still named 1440 pt. --- 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 cdcda0f6e6..13611caf8d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1949,7 +1949,7 @@ Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custo ## Control bar: Paragraph section while type is selected (2026-11-06) -With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1440 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). +With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). ## Area type: vertical alignment in the Properties and Control panels (2026-11-04) From 0f13edaabedf3013734367cfcaf849e3b239b853 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:40:36 -0800 Subject: [PATCH 64/83] Graphs: centered labels with kept leading stay centered Category labels beside an axis and labels in pie wedges are centered on their place by the default leading. A multi-line label that keeps more leading or paragraph spacing ran down from that place instead. The graph now puts the middle of such a label's first and last baselines on its place. --- crates/engine/src/cmd/graph/labels.rs | 38 ++++++++++++++++++++------- crates/engine/src/cmd/graph/tests.rs | 26 ++++++++++++++++++ 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index faf301899a..9d521c5d9b 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -48,17 +48,21 @@ pub(super) fn label_style(styles: &vectorcraft_doc::LabelStyles, role: Role) -> /// The paragraph attributes labels of `role` are set with: the kept ones, else the defaults. The caller sets the /// alignment. pub(super) fn label_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::ParaStyle { - let kept = match role { - Role::Value => &styles.values_para, - Role::Category => &styles.categories_para, - Role::Legend => &styles.legend_para, - }; - let mut para = kept.clone().unwrap_or_default(); + let mut para = kept_para(styles, role).cloned().unwrap_or_default(); // A file's attributes within the limits the Paragraph controls keep to (they are copied onto every label). para.keep_spacing_in_range(); para } +/// The paragraph attributes labels of `role` keep, if any. +fn kept_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vectorcraft_doc::ParaStyle> { + match role { + Role::Value => styles.values_para.as_ref(), + Role::Category => styles.categories_para.as_ref(), + Role::Legend => styles.legend_para.as_ref(), + } +} + /// The anti-aliasing method labels of `role` are drawn with: the kept one, else Sharp. pub(super) fn label_anti_alias(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::text::TypeAntiAlias { let kept = match role { @@ -85,6 +89,11 @@ impl Gen<'_> { self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5) } pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc { + let t = self.text_object(role, at, s, justify); + Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t)))) + } + /// Label `s` of `role` set at `at` and laid out, not yet in the document. + fn text_object(&self, role: Role, at: Point, s: &str, justify: Justify) -> TextObject { let style = label_style(self.styles, role); let mut t = TextObject::point(at, s, style); t.para = label_para(self.styles, role); @@ -92,14 +101,25 @@ impl Gen<'_> { t.para.justify = justify; t.system_layout = self.d.setup.system_layout; refresh_bounds(&mut t); - Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t)))) + t } /// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred /// on `at` (labels beside an axis or in a wedge) instead of running down from it. pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc { let lines = s.split('|').count(); - let at = if middle { Point::new(at.x, at.y - (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0) } else { at }; - self.text(role, at, &s.replace('|', "\n"), justify) + // Default leading puts the first and last baselines this far above and below `at`. + let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0; + let start = if middle { Point::new(at.x, at.y - half) } else { at }; + let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify); + // Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An + // empty first or last line has no baseline, and such a label stays where the default leading puts it. + if middle && kept_para(self.styles, role).is_some() { + let ys: Vec = t.baselines().map(|(a, _)| a.y).collect(); + if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ys.len() == lines) { + t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf; + } + } + Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t)))) } pub(super) fn group(&mut self, name: &str, children: Vec>) -> Arc { let mut g = Node::group(self.d.alloc_id(), children); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c5316e765c..7f85763a7e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4344,6 +4344,32 @@ fn a_legend_across_top_spaces_its_labels_by_their_kept_paragraph_settings() { assert!(next.x0 >= label.x1, "the next swatch starts after the indented label: {label:?} {next:?}"); } +#[test] +fn a_centered_label_with_kept_leading_stays_centered_when_the_graph_is_drawn_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ|1,3,2\nQ2,5,4\nQ3,-1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let middle = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label = group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n1")).unwrap(); + let b = label.geometric_bounds().unwrap(); + (b.y0 + b.y1) / 2.0 + }; + let before = middle(&s); + let l = text_id(&s, id, "Axes", "Q\n1"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"autoLeading": 400, "spaceBefore": 6})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let after = middle(&s); + assert!((after - before).abs() < 0.01, "the two-line category label keeps its middle: {before} {after}"); +} + #[test] fn a_legend_across_top_measures_its_labels_with_system_layout() { let mut s = Session::new(); From 32e22cb442e8d50712e384905692feea698f1a4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:44:11 -0800 Subject: [PATCH 65/83] Effects: pasted art keeps an SVG filter whose name the document gives another filter Pasted art whose svg.filter effect named one of the document's SVG filters but drew another definition kept that name, so editing or deleting the document's filter rewrote the pasted art's filter. Paste now renames such a filter to a free name ("Soft 2") when the art comes from another document or from SVG, and takes the document's filter when the art is pasted back into the document it was copied from. Symbols, patterns, brushes and graphic styles on the clipboard follow the same rule. --- crates/engine/src/cmd/clipboard/resources.rs | 86 +++++++++++++++++++- crates/engine/src/tests/svgfilter.rs | 52 ++++++++++++ docs/mcp.md | 4 +- 3 files changed, 138 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 4488b4746f..5bea009485 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -21,8 +21,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, - TextStyleDef, + Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, + SymbolRegistration, TextStyleDef, }; use super::super::brushsym::{set_natural_size, stored_natural_size}; @@ -140,6 +140,31 @@ fn node_refs(n: &Node, f: Visit) { }); } +/// The `(name, xml)` of `e` when it is an SVG filter effect. +fn filter_of(e: &Effect) -> Option<(String, String)> { + let text = |k: &str| e.params.get(k).and_then(Value::as_str).map(str::to_string); + if e.id != Appearance::SVG_FILTER { + return None; + } + Some((text("name")?, text("xml")?)) +} + +/// The SVG filter effects of appearance `a` (its own and its fills' and strokes'). +fn appearance_filters(a: &Appearance, out: &mut BTreeSet<(String, String)>) { + let items = a.items.iter().flat_map(|i| i.effects().iter()); + out.extend(a.effects.iter().chain(items).filter_map(filter_of)); +} + +/// The SVG filter effects in the subtree of `n` (opacity-mask art included). +fn node_filters(n: &Node, out: &mut BTreeSet<(String, String)>) { + n.walk(&mut |m| { + appearance_filters(&m.appearance, out); + if let Some(mask) = &m.extras().mask { + node_filters(&mask.art, out); + } + }); +} + /// A global or spot colour of its own (not a tint of another swatch): what colours link to. fn is_base(w: &Swatch) -> bool { (w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. }) @@ -527,6 +552,9 @@ impl SwatchChoices { #[derive(Clone, Debug, Default)] struct Relink { renames: BTreeMap>, + /// An SVG filter effect's `(name, xml)` on the clipboard → its `(name, xml)` in the document + /// ([`Clipboard::filter_links`]). + filters: BTreeMap<(String, String), (String, String)>, /// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped. styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. @@ -566,6 +594,15 @@ impl Relink { }); } fn appearance(&self, a: &mut Appearance) { + if !self.filters.is_empty() { + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items) { + if let Some((name, xml)) = filter_of(e).and_then(|k| self.filters.get(&k)) { + e.params["name"] = json!(name); + e.params["xml"] = json!(xml); + } + } + } for it in &mut a.items { self.paint(it.paint_mut()); if let AppearanceItem::Stroke(l) = it @@ -1013,6 +1050,7 @@ impl Clipboard { /// of definitions that use each other is matched on its own ([`loop_groups`]). fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported { let mut out = Imported::default(); + out.relink.filters = self.filter_links(d, same_doc); self.import_images(d, used, same_doc, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art @@ -1170,10 +1208,52 @@ impl Clipboard { } vectorcraft_brush::store(d, &lib); } - out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty()); + out.relinks = !(out.relink.renames.is_empty() + && out.relink.filters.is_empty() + && out.relink.styles.is_empty() + && out.relink.colors.is_empty() + && used.styles.is_empty()); out } + /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's + /// filter of its name; one that draws another definition than that filter takes the document's + /// filter when pasted back into the document it came from, and elsewhere keeps its own under a + /// free name, so editing or deleting the document's filter leaves it alone. + fn filter_links(&self, d: &Document, same_doc: bool) -> BTreeMap<(String, String), (String, String)> { + let mut found = BTreeSet::new(); + for n in &self.nodes { + node_filters(n, &mut found); + } + for s in &self.symbols { + node_filters(&s.art, &mut found); + } + for a in self.patterns.iter().flat_map(|p| p.art.iter()) { + node_filters(a, &mut found); + } + for a in self.brushes.iter().flat_map(Brush::art) { + node_filters(a, &mut found); + } + for g in &self.graphic_styles { + appearance_filters(&g.appearance, &mut found); + } + let mut taken: BTreeSet = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect(); + let mut links = BTreeMap::new(); + for (name, xml) in found { + let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue }; + let to = if same_doc { + (name.clone(), held.xml.clone()) + } else { + let new = unique_name(&name, |n| taken.contains(n)); + taken.insert(new.clone()); + let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new).unwrap_or_else(|| xml.clone()); + (new, drawn) + }; + links.insert((name, xml), to); + } + links + } + /// Image blobs: a different blob under a key the document uses gets a new key. fn import_images(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) { for (key, blob) in self.images.iter().filter(|(k, _)| used.has(Res::Image, k)) { diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index fcb4581c2c..4edcc6fd11 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -207,6 +207,58 @@ fn deleting_a_filter_in_use_leaves_the_effect_drawing_nothing() { assert_eq!(drawn(&s, a), json!(SHIFT_MORE)); } +/// The `(name, xml)` of every `svg.filter` effect on the document's objects. +fn filter_effects(s: &Session) -> Vec<(String, String)> { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| { + for e in n.appearance.effects.iter().filter(|e| e.id == vectorcraft_render::effects::SVG_FILTER) { + out.push((e.params["name"].as_str().unwrap().to_string(), e.params["xml"].as_str().unwrap().to_string())); + } + }); + out +} + +/// Pasted art whose filter has a name the document gives another filter keeps its own filter +/// under a free name, so editing or deleting the document's filter leaves it alone. Pasted back +/// into the document it came from, it takes the document's filter as it is now. +#[test] +fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, "Shift 2", "renamed: {pasted:?}"); + assert!(pasted[0].1.contains("id=\"Shift 2\"") && pasted[0].1.contains("dx=\"9\""), "its own filter: {pasted:?}"); + assert_eq!(names(&mut s), ["Shift"]); + run(&mut s, "svgFilter.delete", json!({"name": "Shift"})); + assert_eq!(filter_effects(&s), pasted, "the document's filter leaves it alone"); + // The same filter as the document's keeps its name. + let mut t = session(); + run(&mut t, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT}"# + ); + run(&mut t, "clipboard.importSvg", json!({"svg": svg})); + run(&mut t, "edit.pasteInPlace", json!({})); + assert_eq!(filter_effects(&t), [("Shift".to_string(), SHIFT.to_string())]); + // Copied, then the filter edited: pasted back, the copy draws the edited filter. + let mut u = session(); + let a = rect(&mut u, 10.0); + run(&mut u, "svgFilter.define", json!({"xml": SHIFT})); + run(&mut u, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]})); + run(&mut u, "select.set", json!({"ids": [a.0]})); + run(&mut u, "edit.copy", json!({})); + run(&mut u, "svgFilter.define", json!({"xml": SHIFT_MORE, "replace": "Shift"})); + run(&mut u, "edit.pasteInPlace", json!({})); + let both = filter_effects(&u); + assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); +} + /// Art in a symbol's definition that uses a filter follows its edits too. #[test] fn a_symbols_art_follows_a_filter_edit() { diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..63ce0bb032 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3680,7 +3680,9 @@ step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect ` in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml` -empty) until a filter of that name is defined or imported again. Opened from such an effect, Apply SVG Filter shows the +empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's +filters but draws another definition keeps its own filter under a free name (`Soft 2`); pasted back into the document +it was copied from, it takes the document's filter. Opened from such an effect, Apply SVG Filter shows the name above the list, not selectable. `effect.apply {effect: "svg.filter", params: {xml}}` takes a filter directly and names it by its `id`; an `xml` that isn't one such filter is an error. `ui.svgFilterDialog {}` opens Apply SVG Filter (New, Edit, Delete, Import…), and from the Appearance panel it edits which filter an applied effect runs; From 67462cf04926e1c1bd31c402d84667943c5863b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 01:52:06 -0800 Subject: [PATCH 66/83] Glyphs: gid null inside a ligature reports the ligature When text.setGlyphAlternate leaves the text unchanged, it now reads the glyph from the unchanged text. A character after the first in a run that holds a glyph choice could be reported with its own glyph instead of the ligature drawn for it, which text.glyphAlternates reports. --- crates/engine/src/cmd/textedit.rs | 10 ++++++++++ crates/engine/src/tests/textedit.rs | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 095cad3616..79dcee7135 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1321,6 +1321,16 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { } } if held == choice && (choice.is_none() || alone) { + // The text is left as it is, so the glyph is the one the unchanged text draws. The probe + // splits a run that holds an earlier character's choice, and the split can break a ligature + // that takes in this character. + let drawn = match &choice { + None if probe.runs != t.runs => { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + drawn_glyph(&plain, &lay, ch, &bytes, &face).or_else(|| shaped_alone(&t, ch, &bytes, &face).1).unwrap_or(default) + } + _ => drawn, + }; return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn})); } s.edit("Glyphs", |d, _| { diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 3593739115..4447946190 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3511,6 +3511,31 @@ fn a_glyph_choice_taken_away_reports_the_glyph_drawn() { assert_eq!(chosen(&mut s, caps, 1), json!(drawn)); } +/// A run that holds a choice for its first character and goes on past it, as a file may have, +/// draws Source Serif 4's fi ligature for the f and the i after that character. `gid: null` for the +/// i leaves the text as it is and reports the ligature, as `text.glyphAlternates` does. +#[test] +fn a_glyph_choice_taken_away_inside_a_ligature_reports_the_ligature() { + let db = vectorcraft_text::FontDb::global(); + let face = db.face("Source Serif 4", "Regular").expect("the bundled face"); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xfin", "size": 40, "font": "Source Serif 4"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let mut runs = obj(&s, id).runs; + runs[0].style.glyph_alternate = Some(face.choice('x', face.glyph_for('x'))); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(text)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("text") }; + text.runs = runs.clone(); + let ligature = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().find(|g| g.byte == 1 && g.len == 2).expect("f + i is one glyph").gid; + let chosen = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"].clone(); + assert_eq!(chosen, json!(ligature)); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": null})).unwrap(); + assert_eq!(r["gid"], chosen, "the ligature drawn for the i"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no edit"); + assert_eq!(obj(&s, id).runs, runs, "the runs are kept"); +} + /// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph /// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel /// sign's. From 08eca05731f82e557e2e76fbf0542ad88a6baf68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:04:44 -0800 Subject: [PATCH 67/83] Scripts: #strict on runs the script with strict write checks instead of refusing it `#strict on` and `//@strict on` no longer end the run as unsupported. They turn on the checks the dollar-object help page gives for `$.strict` (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/): an assignment to a read-only property throws a TypeError, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only; the objects that take no new properties are the non-extensible ones (preventExtensions, seal, freeze, and the frozen vc and $ objects); the last `#strict` line of the script and its includes sets the whole run, and runs without one are unchanged; eval and Function take the checks of the code that compiles them; a file $.evalFile runs keeps its own line's checks for its code and functions, or takes the caller's without one. The rest of ES5 strict mode stays with 'use strict'. The js crate carries the setting per compiled source (Realm::set_strict_writes, and a strict_writes callback on HostItem::Evaluator), and applies it only to property assignments. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/include.rs | 35 ++++-- crates/engine/src/script/mod.rs | 12 +- crates/engine/src/tests/script_include.rs | 131 +++++++++++++++++++++- crates/js/src/builtins.rs | 2 +- crates/js/src/bytecode.rs | 3 + crates/js/src/heap.rs | 2 +- crates/js/src/host.rs | 24 +++- crates/js/src/interp.rs | 41 ++++++- crates/js/src/interp_tests.rs | 57 +++++++++- crates/js/src/realm.rs | 8 ++ docs/mcp.md | 17 ++- docs/target-app-parity.md | 3 +- 13 files changed, 299 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 66f3f8bf8d..af08dc061d 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict off is taken; #strict on, #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index df7702d771..70bfeac56a 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -1,8 +1,11 @@ //! A script's preprocessor lines, read before it runs, as the public guide lists them //! (): //! `#include` and `//@include` put the text of another file in place of the line, `#includepath` -//! sets the folders `#include` looks in, `#script` names the run, and `#target` and `#strict off` -//! are accepted. The same lines are read in a file `$.evalFile` runs. +//! sets the folders `#include` looks in, `#script` names the run, `#strict on` turns on the checks +//! of `$.strict` (: +//! a write to a read-only property is a runtime error, and objects that take no new properties +//! refuse them), and `#target` and `#strict off` are accepted. The same lines are read in a file +//! `$.evalFile` runs. //! //! VectorCraft's own rules: //! @@ -13,9 +16,15 @@ //! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list. //! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a //! `JSINCLUDE` folder outside the scope, which is passed over. -//! - `#target` takes any value and changes nothing. `#targetengine`, `#engine` and `#strict on` are -//! refused as unsupported, and any other `#name` as unknown; `//@name` with another name stays a -//! comment. +//! - `#target` takes any value and changes nothing. `#targetengine` and `#engine` are refused as +//! unsupported, and any other `#name` as unknown; `//@name` with another name stays a comment. +//! - The last `#strict on` or `#strict off` of the script and the files it includes sets the checks +//! for the whole run; without one they are off. A write to a property that has only a getter is +//! checked as a read-only one, the objects that take no new properties are those that are not +//! extensible (`Object.preventExtensions`, `Object.seal`, `Object.freeze`), and the rest of ES5 +//! strict mode is left to `'use strict'`. Code that `eval` and `Function` compile takes the +//! checks of the code that compiles it; a file `$.evalFile` runs takes its own `#strict` line if +//! it has one, and otherwise the caller's. //! - A run reads at most [`MAX_DEPTH`] levels of nested files, [`MAX_FILES`] files, //! [`MAX_TOTAL_BYTES`] of source in all (the script's own included) and 8 MiB a file, and looks up //! at most [`MAX_PROBES`] paths. A file may be included again once its earlier inclusion has @@ -97,12 +106,13 @@ pub(crate) struct Failure { pub column: u32, } -/// A source with its preprocessor lines read: the text to run, where its lines came from, and the -/// name its `#script` line gave. +/// A source with its preprocessor lines read: the text to run, where its lines came from, the +/// name its `#script` line gave, and what its last `#strict` line set (`None` without one). pub(crate) struct Expanded { pub source: String, pub map: SourceMap, pub name: Option, + pub strict: Option, } /// A file being run: its name for people and the folder its relative paths start from (none for a @@ -130,13 +140,14 @@ pub(crate) struct Files { } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, -/// and whether its last unit is a carriage return. +/// whether its last unit is a carriage return, and what the last `#strict` line so far set. struct Out { units: Vec, line: u32, column: u32, after_cr: bool, map: SourceMap, + strict: Option, } impl Out { @@ -330,7 +341,7 @@ impl Files { /// `text`, the file `shown` in folder `dir`, with its preprocessor lines read. With `script`, /// its `#script` line names the run. fn expand(&mut self, shown: Arc, dir: Option, text: &str, script: bool) -> Result { - let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default() }; + let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default(), strict: None }; let mut name = None; self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?; let source = String::from_utf16(&out.units).map_err(|_| Failure { @@ -341,7 +352,7 @@ impl Files { line: 0, column: 0, })?; - Ok(Expanded { source, map: out.map, name }) + Ok(Expanded { source, map: out.map, name, strict: out.strict }) } /// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place @@ -414,8 +425,8 @@ impl Files { } } Some(DirectiveName::Strict) => match value.to_ascii_lowercase().as_str() { - "off" => {} - "on" => return Err(at(FailKind::Syntax, format!("unsupported strict checking: {label} on"))), + "off" => out.strict = Some(false), + "on" => out.strict = Some(true), _ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))), }, Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f2e4cc5bad..fbaa353dc0 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -489,6 +489,8 @@ struct Host { /// The last error `$.evalFile` raised for a file it could not run, with the file, line and /// column that error is at. eval_failure: RefCell>, + /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). + eval_strict: Cell>, } /// An error `$.evalFile` raised, as thrown, and the file, line and column it is at. @@ -947,7 +949,12 @@ fn dollar_object(host: &Rc) -> Vec<(String, HostItem)> { let eval_file = { let h = host.clone(); let end = host.clone(); - HostItem::Evaluator { source: function(move |a| eval_file(&h, a)), end: Rc::new(move || end.files.borrow_mut().end_eval()) } + let strict = host.clone(); + HostItem::Evaluator { + source: function(move |a| eval_file(&h, a)), + end: Rc::new(move || end.files.borrow_mut().end_eval()), + strict_writes: Rc::new(move || strict.eval_strict.get()), + } }; vec![ ("write".into(), writer(false)), @@ -996,6 +1003,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result Err(preprocessor_error(f)), Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; + realm.set_strict_writes(expanded.strict == Some(true)); realm .define_host_object("vc", vc_object(&host, args)) .and_then(|()| realm.define_host_object("$", dollar_object(&host))) diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 2d857b2301..b8bb507434 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -194,7 +194,6 @@ fn script_target_other_app_does_not_route() { ("#target\nvc.log(1);", "#target needs a value"), ("#targetengine \"session\"", "unsupported script directive: #targetengine"), ("#engine \"main\"", "unsupported script directive: #engine"), - ("#strict on", "unsupported strict checking: #strict on"), ("#strict maybe", "#strict takes on or off"), ("#frobnicate 1", "unknown script directive: #frobnicate"), ("#include \"x.jsxinc", "unterminated quote in #include"), @@ -223,12 +222,134 @@ fn script_name_comes_from_the_script_line() { let _ = std::fs::remove_dir_all(base); } +/// The script's `ro`, with a read-only `x`. +const READ_ONLY: &str = "var ro = {};\nObject.defineProperty(ro, 'x', {value: 1});\n"; + #[test] -fn script_strict_on_is_refused() { +fn strict_on_runs_and_read_only_write_throws() { let mut s = Session::new(); - let e = s.execute("script.run", &json!({"source": "#strict on\nvc.log(1);"})).unwrap_err().to_string(); - assert!(e.contains("unsupported strict checking: #strict on"), "{e}"); - assert_eq!(s.script_report().unwrap()["kind"], "syntax"); + for head in ["#strict on\n", "//@strict on\n", "#strict ON\n", "#strict off\n#strict on\n"] { + let source = format!("{head}{READ_ONLY}vc.log(1);\n ro.x = 2;\nvc.log(2);"); + let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string(); + assert!(e.contains("TypeError: cannot assign to property 'x': it is read-only"), "{head}: {e}"); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "thrown", "{head}"); + assert_eq!(report["log"], json!([1]), "{head}: the script ran up to the write"); + let line = head.lines().count() as u64 + 4; + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(line), Some(3)), "{head}: {report}"); + } + // The error can be caught, and every kind of assignment is checked. + let source = format!( + "#strict on\n{READ_ONLY}var out = [];\nfunction t(f) {{ try {{ f(); out.push('wrote'); }} catch (e) {{ out.push(e.name); }} }}\nt(function () {{ ro.x = 2; }});\nt(function () {{ ro['x'] += 1; }});\nt(function () {{ ro.x++; }});\nt(function () {{ undefined = 1; }});\nt(function () {{ [].concat.length = 0; }});\nvc.log(out);\nvc.log(ro.x);" + ); + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["log"], json!([["TypeError", "TypeError", "TypeError", "TypeError", "TypeError"], 1])); + // Without the line, or with `#strict off` last, the write is ignored as before. + for head in ["", "#strict off\n", "#strict on\n#strict off\n"] { + let r = s.execute("script.run", &json!({"source": format!("{head}{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")})).unwrap(); + assert_eq!(r["log"], json!([1]), "{head}"); + } +} + +#[test] +fn strict_on_rejects_getter_only_and_nonextensible_additions() { + let mut s = Session::new(); + let source = "#strict on\nvar out = [];\nfunction t(f) { try { f(); out.push('wrote'); } catch (e) { out.push(String(e)); } }\n\ + var g = {get v() { return 1; }}, set = {set v(x) { this.got = x; }};\n\ + t(function () { g.v = 2; });\n\ + t(function () { Object.preventExtensions({}).n = 1; });\n\ + t(function () { Object.seal({a: 1}).n = 1; });\n\ + t(function () { Object.freeze({a: 1}).a = 2; });\n\ + t(function () { vc.extra = 1; });\n\ + var open = {};\nt(function () { open.n = 1; });\nt(function () { set.v = 3; });\nt(function () { Object.seal({a: 1}).a = 2; });\n\ + vc.log(out);\nvc.log(open.n);\nvc.log(set.got);"; + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!( + r["log"], + json!([ + [ + "TypeError: cannot assign to property 'v': it has only a getter", + "TypeError: cannot assign to property 'n': the object is not extensible", + "TypeError: cannot assign to property 'n': the object is not extensible", + "TypeError: cannot assign to property 'a': it is read-only", + "TypeError: cannot assign to property 'extra': the object is not extensible", + "wrote", + "wrote", + "wrote" + ], + 1, + 3 + ]) + ); + let r = s.execute("script.run", &json!({"source": source.replacen("#strict on", "#strict off", 1)})).unwrap(); + assert_eq!(r["log"][0], json!(["wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote"]), "off, nothing is refused"); +} + +#[test] +fn strict_on_does_not_enable_es5_early_errors() { + let mut s = Session::new(); + let source = "#strict on\nwith ({w: 1}) { vc.log(w); }\nfunction f(a, a) { return a; }\nvc.log(f(1, 2));\nvc.log(010);\nundeclared = 4;\nvc.log(undeclared);\n\ + vc.log((function () { return typeof this; })());\nvc.log(delete Object.prototype);\nvar eval2 = 5;\nvc.log((function () { arguments = 6; return arguments; })());"; + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["log"], json!([1, 2, 8, 4, "object", false, 6])); + // 'use strict' still makes the code strict mode code. + let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nundeclared2 = 1;"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError"), "{e}"); + let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nwith ({}) {}"})).unwrap_err().to_string(); + assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{e}"); +} + +#[test] +fn strict_on_in_include_controls_expanded_run() { + let base = folder("strict"); + write(&base.join("main/on.jsxinc"), "#strict on\nvar inc = 1;"); + write(&base.join("main/off.jsxinc"), "//@strict off\n"); + write(&base.join("main/writes.jsxinc"), &format!("{READ_ONLY}\n ro.x = 2;\n")); + // An included file's line sets the checks for the script's own code too. + let report = failed(&base, &format!("#include \"on.jsxinc\"\n{READ_ONLY}ro.x = 2;")); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + assert!(report.get("file").is_none(), "{report}"); + // A write in an included file is reported at its own line. + let report = failed(&base, "#strict on\n#include \"writes.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(4), Some(3)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("writes.jsxinc"), "{report}"); + // The last line of the expanded run wins, wherever it is. + let r = run(&base, &format!("#strict on\n#include \"off.jsxinc\"\n{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")).unwrap(); + assert_eq!(r["log"], json!([1])); + let report = failed(&base, &format!("#include \"off.jsxinc\"\n#strict on\n{READ_ONLY}ro.x = 2;")); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn strict_mode_in_eval_file_is_scoped() { + let base = folder("strict-eval"); + write( + &base.join("main/on.jsx"), + &format!( + "#strict on\n{READ_ONLY}function w(o) {{ o.x = 2; }}\nvar inner;\ntry {{ ro.x = 2; inner = 'wrote'; }} catch (e) {{ inner = e.name; }}\n" + ), + ); + write(&base.join("main/off.jsx"), &format!("#strict off\n{READ_ONLY}ro.x = 2;\n'off ran';")); + write(&base.join("main/plain.jsx"), &format!("{READ_ONLY}ro.x = 2;\n'plain ran';")); + // A file's own `#strict on` holds for its code, its functions included, and not the caller's. + let r = run( + &base, + "$.evalFile('on.jsx');\nvar after;\ntry { ro.x = 3; after = 'ignored'; } catch (e) { after = e.name; }\nvar called;\ntry { w(ro); called = 'wrote'; } catch (e) { called = e.name; }\nvc.log([inner, after, called]);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["TypeError", "ignored", "TypeError"]])); + // A file without the line takes the caller's checks, and its own `#strict off` turns them off. + let r = run(&base, "#strict on\nvc.log($.evalFile('off.jsx'));\nvar e1;\ntry { ro.x = 2; } catch (e) { e1 = e.name; }\nvc.log(e1);").unwrap(); + assert_eq!(r["log"], json!(["off ran", "TypeError"]), "the caller keeps its own checks"); + let report = failed(&base, "#strict on\n$.evalFile('plain.jsx');"); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("plain.jsx"), "{report}"); + assert_eq!(report["line"], 3, "{report}"); + assert_eq!(run(&base, "vc.log($.evalFile('plain.jsx'));").unwrap()["log"], json!(["plain ran"])); + let _ = std::fs::remove_dir_all(base); } #[test] diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 62f6ade7a9..5738beb94d 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -472,7 +472,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), }; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { Ok(Some(code)) => code, Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 0a666d1f25..b8bd2783b1 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -173,6 +173,9 @@ pub(crate) struct Source { pub(crate) text: Rc<[u16]>, /// Which source this is, as [`crate::Realm::error_source`] gives it. pub(crate) tag: u32, + /// Writes to read-only and getter-only properties, and new properties on objects that are + /// not extensible, throw in this source's code even where it is not strict mode code. + pub(crate) strict_writes: bool, } #[derive(Debug)] diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index b229ce6e6c..f7e3b32c5a 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -184,7 +184,7 @@ pub(crate) enum Func { Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, text: bool }, - Eval { f: DataFn, end: Rc, name: Rc }, + Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index b725245ce8..ab4334dc33 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -81,10 +81,12 @@ pub enum HostItem { /// the call gives that code's completion value, and its declarations become globals. A result /// that is not a string is the call's result. `end` is called when the source has run, /// normally or not. Each source given has the next tag of [`crate::Realm::error_source`], - /// from 1. + /// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`] + /// for that source alone; with `None` it takes the calling code's. Evaluator { source: HostFunction, end: Rc, + strict_writes: Rc Option>, }, } @@ -302,17 +304,26 @@ impl Interp { /// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the /// source it gives as global code, as an indirect `eval` does, giving that code's completion /// value. A result that is not a string is given to the script as it is. `end` is called once - /// the source has run, normally or not. - pub(crate) fn call_evaluator(&mut self, f: &crate::heap::DataFn, end: &Rc, name: &Rc, args: &[Value]) -> JsResult { + /// the source has run, normally or not. `strict_writes` gives the source's + /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. + pub(crate) fn call_evaluator( + &mut self, + f: &crate::heap::DataFn, + end: &Rc, + strict_writes: &Rc Option>, + name: &Rc, + args: &[Value], + ) -> JsResult { let data = self.read_args(name, args, false)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), Err(e) => return Err(self.host_error(e)?), }; + let writes = strict_writes().unwrap_or_else(|| self.writes_mode()); self.evaluated = self.evaluated.saturating_add(1); let tag = std::mem::replace(&mut self.source_tag, self.evaluated); - let code = self.encode_source(&source).and_then(|units| self.compile_source(&units, false, crate::bytecode::CodeKind::Eval)); + let code = self.encode_source(&source).and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)); self.source_tag = tag; let r = match code { Ok(code) => self.run_global(code, true), @@ -411,9 +422,10 @@ impl Interp { HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE }, HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, - HostItem::Evaluator { source, end } => { + HostItem::Evaluator { source, end, strict_writes } => { let proto = self.intrinsics.function_proto; - let f = self.heap.alloc_object(Object::new(Class::Function(Func::Eval { f: source, end, name: full.into() }), Some(proto))); + let func = Func::Eval { f: source, end, strict_writes, name: full.into() }; + let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto))); Prop::Data { value: Value::Object(f), flags: ENUMERABLE } } }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 22bbb6c0d3..87db42646b 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -191,6 +191,8 @@ pub(crate) struct Interp { pub(crate) evaluated: u32, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, + /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. + pub(crate) strict_writes: bool, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -385,6 +387,7 @@ impl Interp { source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, error_tag: crate::realm::UNKNOWN_SOURCE, + strict_writes: false, }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -691,6 +694,18 @@ impl Interp { self.frames.last().is_some_and(|f| f.code.strict) } + /// Does a property write the running code makes throw when it cannot be made? It does in + /// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`]. + fn strict_writes(&self) -> bool { + self.frames.last().is_some_and(|f| f.code.strict || f.code.source.strict_writes) + } + + /// [`crate::bytecode::Source::strict_writes`] for source compiled now: the running code's, + /// or the realm's between runs. + pub(crate) fn writes_mode(&self) -> bool { + self.frames.last().map_or(self.strict_writes, |f| f.code.source.strict_writes) + } + fn exec(&mut self, op: Op) -> JsResult<()> { match op { Op::Undefined => self.push(Value::Undefined), @@ -909,11 +924,14 @@ impl Interp { _ => Ok(()), } } - Resolved::Obj { object, .. } => self.put(object, name.clone(), v, strict), + Resolved::Obj { object, .. } => { + let throw = self.strict_writes(); + self.put(object, name.clone(), v, throw) + } Resolved::Unresolved if strict => Err(self.not_defined(name)), Resolved::Unresolved => { - let global = self.global; - self.put(global, name.clone(), v, false) + let (global, throw) = (self.global, self.strict_writes()); + self.put(global, name.clone(), v, throw) } } } @@ -1444,7 +1462,10 @@ impl Interp { fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { let strict = self.strict(); match base { - Value::Object(o) => self.put(*o, k, v, strict), + Value::Object(o) => { + let throw = self.strict_writes(); + self.put(*o, k, v, throw) + } Value::Undefined | Value::Null => { let message = format!( "cannot set property '{}' of {}", @@ -1860,7 +1881,9 @@ impl Interp { // keeps itself reachable. return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?)); } - Func::Eval { f, end, name } => return Ok(Prepared::Done(self.call_evaluator(&f, &end, &name, &args)?)), + Func::Eval { f, end, strict_writes, name } => { + return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); + } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); return match host(&js_args) { @@ -2129,11 +2152,17 @@ impl Interp { /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { + let writes = self.writes_mode(); + self.compile_source_writes(units, strict, writes, kind) + } + + /// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`. + pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result, CompileError> { self.source_units = self.source_units.saturating_add(units.len()); let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); let options = Options { strict, max_source_units: remaining, ..self.options.clone() }; let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); compile_program(&program, &source, kind).map_err(|e| match e { CompileFail::Syntax(s) => CompileError::Syntax(s), CompileFail::Internal(m) => CompileError::Internal(m), diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index c7f69ec9b6..b6fec26378 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -691,6 +691,61 @@ fn a_strict_realm_runs_scripts_as_strict_mode_code() { assert_eq!(realm.run("(function () { return typeof this; })()"), Ok(JsValue::String("object".into()))); } +#[test] +fn strict_writes_are_separate_from_es5_strict() { + let setup = "var ro = {}; Object.defineProperty(ro, 'x', {value: 1}); \ + var getter = {get g() { return 1; }}; var shut = Object.preventExtensions({a: 1}); var open = {};"; + let mut realm = Realm::new(); + realm.set_strict_writes(true); + realm.run(setup).unwrap(); + for (src, why) in [ + ("ro.x = 2", "cannot assign to property 'x': it is read-only"), + ("ro['x'] += 1", "cannot assign to property 'x': it is read-only"), + ("ro.x++", "cannot assign to property 'x': it is read-only"), + ("getter.g = 2", "cannot assign to property 'g': it has only a getter"), + ("shut.b = 2", "cannot assign to property 'b': the object is not extensible"), + ("Object.create(ro).x = 2", "cannot assign to property 'x': it is read-only"), + ("NaN = 1", "cannot assign to property 'NaN': it is read-only"), + ("(function () { ro.x = 2; })()", "cannot assign to property 'x': it is read-only"), + ("eval('ro.x = 2')", "cannot assign to property 'x': it is read-only"), + ("(0, eval)('ro.x = 2')", "cannot assign to property 'x': it is read-only"), + ("Function('ro.x = 2')()", "cannot assign to property 'x': it is read-only"), + ] { + let e = realm.run(src).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Thrown, "{src}"); + assert!(e.message.contains("TypeError") && e.message.contains(why), "{src}: {}", e.message); + } + // Writes that can be made, and the rest of strict mode, are as before. + assert_eq!(realm.run("open.n = 1; shut.a = 5; open.n + shut.a"), Ok(JsValue::Number(6.0))); + assert_eq!(realm.run("with ({w: 2}) { w } "), Ok(JsValue::Number(2.0))); + assert_eq!(realm.run("(function (a, a) { return a; })(1, 2)"), Ok(JsValue::Number(2.0))); + assert_eq!(realm.run("010"), Ok(JsValue::Number(8.0))); + assert_eq!(realm.run("undeclared = 3; undeclared"), Ok(JsValue::Number(3.0))); + assert_eq!(realm.run("(function () { return typeof this; })()"), Ok(JsValue::String("object".into()))); + assert_eq!(realm.run("delete Object.prototype"), Ok(JsValue::Bool(false))); + assert_eq!(realm.run("'abc'.length = 1; 'abc'.extra = 1; 1"), Ok(JsValue::Number(1.0)), "a primitive's properties as in sloppy mode"); + // 'use strict' keeps all of ES5 strict mode. + assert_eq!(realm.run("'use strict'; with ({}) {}").map_err(|e| e.kind), Err(RunErrorKind::Syntax)); + assert_eq!(realm.run("'use strict'; delete Object.prototype").map_err(|e| e.kind), Err(RunErrorKind::Thrown)); + // Off, the same writes are ignored, as in sloppy mode code. + realm.set_strict_writes(false); + assert_eq!(realm.run("ro.x = 2; getter.g = 2; shut.b = 2; NaN = 1; ro.x + getter.g + String(shut.b)"), Ok(JsValue::String("2undefined".into()))); + // A function compiled with the writes on keeps them when called from code without. + let mut realm = Realm::new(); + realm.set_strict_writes(true); + realm.run(&format!("{setup} function w() {{ ro.x = 2; }}")).unwrap(); + realm.set_strict_writes(false); + assert!(realm.run("w()").unwrap_err().message.contains("it is read-only")); + assert_eq!(realm.run("ro.x = 3; ro.x"), Ok(JsValue::Number(1.0))); + // An undeclared name added to a global object that is not extensible. + let mut realm = Realm::new(); + realm.set_strict_writes(true); + let e = realm.run("Object.preventExtensions(this); newName = 1").unwrap_err(); + assert!(e.message.contains("cannot assign to property 'newName': the object is not extensible"), "{}", e.message); + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.preventExtensions(this); newName = 1; typeof newName"), Ok(JsValue::String("undefined".into()))); +} + #[test] fn an_apply_that_throws_while_reading_its_arguments_keeps_nothing_alive() { // Each call reads a fresh array at index 0 before index 1 throws; the arrays must not stay @@ -774,7 +829,7 @@ fn deep_nesting_compiles_on_a_small_stack() { // ---- the verifier ---- fn code(ops: Vec) -> Code { - let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()), tag: 0 }); + let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()), tag: 0, strict_writes: false }); Code { positions: vec![0; ops.len()], ops, diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index beaad25574..92452a6090 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -174,6 +174,14 @@ impl Realm { self.unbroken_fuel = fuel; } + /// With `on`, the scripts run next (and the code they define and evaluate) throw a + /// `TypeError` when they assign to a read-only or getter-only property or add a property to + /// an object that is not extensible, as strict mode code does, without the rest of strict + /// mode. Off by default. + pub fn set_strict_writes(&mut self, on: bool) { + self.interp.strict_writes = on; + } + pub fn limits(&self) -> &Limits { &self.interp.limits } diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..d3c056981b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1587,9 +1587,20 @@ VectorCraft reads them by these rules of its own: folder of the file that includes. A later `#includepath` replaces the list. - `#script "name"` names the run in the report and the Script Console, unless `name` is given. A `#script` line in an included file does not rename the run. -- `#target` takes any value and does not change how the script runs. `#strict off` is taken. -- `#strict on`, `#targetengine` and `#engine` end the run with an unsupported-directive error, and any other `#name` - with an unknown-directive error. A `//@` line with another name is a comment. +- `#target` takes any value and does not change how the script runs. +- `#strict on` turns on the checks the dollar-object help page gives for `$.strict`: an assignment to a read-only + property throws a `TypeError`, and so does adding a property to an object that takes no new ones. By VectorCraft's + own rules, an assignment to a property with only a getter is checked as a read-only one, and the objects that take + no new properties are those that are not extensible: objects passed to `Object.preventExtensions`, `Object.seal` or + `Object.freeze`, and the frozen `vc` and `$` objects. Other objects take new properties as before. The rest of ES5 + strict mode (`with`, undeclared variables, `this` in a plain call) is unchanged; a script asks for it with + `'use strict'`. `#strict off` turns the checks off, and they are off in a script without either line. +- The last `#strict` line of the script and the files it includes sets the checks for the whole run. Code that `eval` + and `Function` compile takes the checks of the code that compiles it. A file `$.evalFile` runs takes the checks of + its own last `#strict` line, for its code and the functions it defines, or the caller's when it has none; the + caller's code keeps its own. Any value other than `on` or `off` ends the run with `#strict takes on or off`. +- `#targetengine` and `#engine` end the run with an unsupported-directive error, and any other `#name` with an + unknown-directive error. A `//@` line with another name is a comment. - A script run from a file reads its included files and the files `$.evalFile` runs only in that file's folder and the folders below it. A path with a `..` name, a path that leads out of the folder through a link or a junction, a Windows device name or stream, and a computer on the network are refused, and so is every path for a script given as diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 49713d6612..06b63c5a50 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -729,7 +729,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, and `#strict on`, `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), and `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). From 16cc5c107c6bbfecb2c42c7394f691c86d89d7b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:09:08 -0800 Subject: [PATCH 68/83] Docs: a row without paint leaves the series' stored paint, not its opacity The graph still stores an opacity or blend mode set on a series mark's row that has no paint, as it does for transparency.set. The sentence now says that such a row leaves only the stored paint unchanged. --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..f8c3449813 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -588,7 +588,7 @@ the stored fill, or the stored stroke when no fill is stored and that stroke has outline, so these commands do not store a stroke paint or weight for a series that draws a band. Except for `paint.swap`, they still store a stroke opacity and blend mode set on a band, and the band's outline takes them. Graph designs keep their own paint. A row that had no -paint before the command and has none after it does not change what the graph stores. `paint.setFill`, +paint before the command and has none after it does not change the paint the graph stores. `paint.setFill`, `paint.setStroke`, `paint.none` and the commands that apply one paint kind to the other store the topmost row of the kind even when it is hidden, and store a stroke set on a band. `stroke.set`, `paint.editGradient` and the recolor commands do not store a series' paint. An `appearance.*` command or `graphicStyle.apply` given a series group's id, and From 3a44447aeb29f2da9d4726454c97701a3f521053 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:17:45 -0800 Subject: [PATCH 69/83] Docs: remove the duplicated G9 .ai sentence that says .ai editing data is not written A merge left a second copy of the G9 `.ai`/EPS Missing bullet's opening inside the bullet. That copy says writing the editing data is out of scope, while the same bullet and file-format-parity.md say a PDF-compatible `.ai` carries an editing copy of the art. The bullet now has one copy, with the newer brush wording that matches the 2026-11-05 entry above it. --- docs/gaps.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index f0619ff213..2edc2e5751 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -211,19 +211,14 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi art with strokes, gradients or patterns) and type with an Art brush keep the drawn look. - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead - of 14), open speed on large files (#758), live effects, Scatter, Art, Pattern and Bristle brushes on paths, a - path's own Calligraphic brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). A PDF-compatible `.ai` carries an editing copy of the art in the form + of 14), open speed on large files (#758), live effects, Scatter, Pattern and Bristle brushes on paths, the Art + brushes listed above as keeping the drawn look, a path's own Calligraphic or Art brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). A PDF-compatible `.ai` carries an editing copy of the art in the form VectorCraft's reader reads (layers, groups, paths, colors, gradients, patterns, images, transparency, opacity masks, clipping, type as text and symbols), with live effects kept only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, other objects' effects other than geometry effects left out, and live objects written as their art ([file-format-parity.md](file-format-parity.md)). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and - of 14), open speed on large files (#758), live effects, Scatter, Pattern and Bristle brushes on paths, the Art - brushes listed above as keeping the drawn look, a path's own Calligraphic or Art brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope - (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As - `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification - instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and images, and type as editable text objects (or outlines), one artboard per file (an artboard picker chooses which); transparency, live effects and object names don't survive it (transparent images are flattened or omitted, hidden objects go to a hidden layer, are omitted or made visible), and type is set again in the From c81ae88c85b270c4d2e808db900c88141c9ec924 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:23:59 -0800 Subject: [PATCH 70/83] Flatten Transparency: a long rasterized area is placed whole The flattener limited an image's resolution only by its total pixels, while the renderer draws at most 32,768 pixels a side. A long area, such as a narrow see-through gradient strip down a 2 m banner at 1200 ppi, came back cut off at that length and was placed as if whole, so the rest of the strip was lost in Flatten Transparency and in PDF/X-1a, PDF/X-3 and PDF 1.3 exports. The resolution is now also limited by the longest side, as raster effects are. --- crates/engine/src/cmd/flatten/apply.rs | 3 +++ crates/engine/src/cmd/flatten/commands.rs | 2 +- crates/engine/src/tests/flatten.rs | 25 +++++++++++++++++++++++ docs/mcp.md | 4 +++- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 555058e58f..409db3f1b2 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -484,6 +484,9 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option, o: &FlattenOptions) -> Result { let mut scale = ppi / 72.0; scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt()); + // No side longer than the renderer draws: the image grows by a pixel on each side and is + // rounded up to whole pixels below. + scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0)); let px = 1.0 / scale; let rect = rect.inflate(px, px); let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c)); diff --git a/crates/engine/src/cmd/flatten/commands.rs b/crates/engine/src/cmd/flatten/commands.rs index 53687713b5..4053dcac78 100644 --- a/crates/engine/src/cmd/flatten/commands.rs +++ b/crates/engine/src/cmd/flatten/commands.rs @@ -10,7 +10,7 @@ pub fn specs() -> Vec { "Flatten Transparency…", ["Object"], None, - "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach; an image larger than 64 Mpx or 32,768 px a side is made at a lower resolution), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_doc, flatten ), diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 2e08b99c89..84e4724fe6 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,31 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +#[test] +fn a_long_rasterized_area_is_placed_whole() { + let _settings = settings_lock(); + let mut s = session(); + // 5569 pt long: more than the renderer's 32,768 pixels a side at the 64 Mpx limit's scale. + let g = rect(&mut s, 10.0, 10.0, 100.0, 5569.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "lineArtPpi": 1200, "gradientPpi": 1200})); + assert_eq!(rasterized, 1); + let mut placed = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + placed.push((im.height, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))))); + } + }); + let [(height, b)] = placed[..] else { panic!("one image: {placed:?}") }; + assert!(height <= vectorcraft_render::MAX_RASTER_SIDE, "{height} pixels"); + assert!(b.y0 <= 10.0 && b.y1 >= 5579.0, "the image covers the strip: {b:?}"); +} + #[test] fn flatten_says_when_an_image_could_not_be_decoded() { let _settings = settings_lock(); diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..8a91a5fdc6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3207,7 +3207,9 @@ the group holds only the art inside the clipping layer, drawn over the fill and layer as its own layers draw it (over nothing with `preserveAlpha`), and the art outside is flattened on its own. `preset` is `high`, `medium` (the default) or `low`; option keys (`balance` 0–100, `lineArtPpi`, `gradientPpi`, `textToOutlines`, `strokesToOutlines`, `clipComplexRegions`, `antiAlias`, `preserveAlpha`, `preserveOverprints`) -override it, at the top level or in `options`. `balance: 0` rasterizes everything; lower balances rasterize groups +override it, at the top level or in `options`. An image that would be larger than 64 million pixels or longer than +32,768 pixels a side at `lineArtPpi` or `gradientPpi` is made at the highest resolution that fits, so a long area is +rasterized whole. `balance: 0` rasterizes everything; lower balances rasterize groups that split into many regions. The result reports `{ids, vector, rasterized, options}`. When an image in the art can't be decoded, the image that replaces the art does not show it, and the result also carries `warning`: "an image couldn't be decoded and is missing from the picture", the note raster exports give. From 8b2ff77429630b37ee92c7ba800fa20cfe79f449 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:27:30 -0800 Subject: [PATCH 71/83] Plug-ins: a plug-in may call effect.deferredStatus but not effect.refreshDeferred effect.deferredStatus only lists the document's deferred stages, so it joins reviewed::ALLOWED. effect.refreshDeferred runs plug-in effects again, so it joins reviewed::DENIED, which fixes every_command_is_reviewed. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 7759a57f00..f7c7003b11 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.findNext", "edit.findReplace", "effect.apply", + "effect.deferredStatus", "effect.duplicate", "effect.expandAppearance", "effect.list", @@ -662,11 +663,13 @@ pub(super) const ALLOWED: &[&str] = &[ ]; /// Commands a plug-in may not call although no rule refuses them, in order: they change the -/// preferences, a tool's options, a drag's state or the font names the whole app knows. +/// preferences, a tool's options, a drag's state or the font names the whole app knows, or run +/// plug-ins again. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "effect.refreshDeferred", "graphicStyle.setOptions", "object.blend.options", "object.liquify", From 2b378689d17f4d688dc936a243e6482e4ca0cc0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:38:07 -0800 Subject: [PATCH 72/83] Tests: the command sweep sends file and folder params only into its temp folder The tool-edit sweep sent `{"": "on"}` for every documented key, so `prefs.export` wrote a preferences file named `on` into crates/engine on every run, and `folder`, `destinationFolder` and `diffPath` strings from `junk_params` named locations under the working directory. - `is_path_key` covers `path`, `diffPath`, `folder` and `destinationFolder`; `safe_value` sends a temp file for a file key and a temp folder for a folder key, and both sweeps use it. - A new test builds both sweeps' cases for every command and fails when a string under one of those keys is outside the temp folder, without running any command. --- crates/engine/tests/command_sweep.rs | 67 +++++++++++++++++++++------- crates/testkit/src/strategies.rs | 26 ++++++++--- 2 files changed, 73 insertions(+), 20 deletions(-) diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index de14c38b5a..947cf559d0 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -9,10 +9,11 @@ use vectorcraft_engine::{Session, command_specs}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::Fixture; use vectorcraft_testkit::invariants::{check_all, check_session, doc_json}; -use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys}; +use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys, safe_value}; /// Commands that replace/close the active document or touch the filesystem are fine to call, but a -/// few need their paths redirected into a temp dir (handled by `junk_params`). +/// few need their file and folder params redirected into a temp dir (`safe_value`, which +/// `junk_params` applies). fn safe_path() -> String { vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string() } @@ -230,6 +231,54 @@ fn tool_edit_state(s: &Session) -> ToolEditState { (docs, s.active_index(), s.paint.clone()) } +/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and +/// off, with a string under a file or folder key replaced by a location inside `path`'s folder. +fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = junk_params(c.params, path); + if heavy(c.id) { + cases.truncate(12); + } + for k in param_keys(c.params) { + for v in [json!(true), json!(false), json!(1), json!("on")] { + cases.push(json!({ k.as_str(): safe_value(&k, &v, path) })); + } + } + // Find Objects selects only with a filter, which one key at a time does not give it. + if c.id == "document.find" { + cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]); + } + cases +} + +/// Every string the sweeps send under a key that names a file or folder to write is inside the +/// sweep's temp folder, so no run writes into the working directory. +#[test] +fn sweep_cases_name_files_only_inside_the_temp_folder() { + let path = safe_path(); + let dir = vectorcraft_testkit::temp_dir("sweep"); + let keys = ["path", "diffPath", "folder", "destinationFolder"]; + let mut seen = std::collections::BTreeSet::new(); + let mut outside = std::collections::BTreeSet::new(); + for c in command_specs() { + let mut cases = junk_params(c.params, &path); + cases.extend(tool_edit_cases(c, &path)); + for p in &cases { + let Some(o) = p.as_object() else { continue }; + for (k, v) in o.iter().filter(|(k, _)| keys.contains(&k.as_str())) { + seen.insert(k.clone()); + if let Some(s) = v.as_str() + && !std::path::Path::new(s).starts_with(&dir) + { + outside.insert(format!("{} {{\"{k}\": {v}}}", c.id)); + } + } + } + } + assert_eq!(seen.len(), keys.len(), "the sweeps send only {seen:?}"); + let outside: Vec = outside.into_iter().collect(); + assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n")); +} + /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, @@ -241,19 +290,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { - let mut cases = junk_params(c.params, &path); - if heavy(c.id) { - cases.truncate(12); - } - for k in param_keys(c.params) { - for v in [json!(true), json!(false), json!(1), json!("on")] { - cases.push(json!({ k.as_str(): v })); - } - } - // Find Objects selects only with a filter, which one key at a time does not give it. - if c.id == "document.find" { - cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]); - } + let cases = tool_edit_cases(c, &path); for p in &cases { let mut s = fx.session(); let before = tool_edit_state(&s); diff --git a/crates/testkit/src/strategies.rs b/crates/testkit/src/strategies.rs index 4dbac8f6ec..10b0608001 100644 --- a/crates/testkit/src/strategies.rs +++ b/crates/testkit/src/strategies.rs @@ -502,10 +502,26 @@ pub fn param_keys(doc: &str) -> Vec { out } -/// Parameter-name keys that name filesystem paths: fuzzing these with arbitrary strings could -/// write files anywhere, so callers substitute a temp path. +/// Parameter-name keys that name a file or folder a command may write: fuzzing these with +/// arbitrary strings could write files anywhere, so callers substitute a temp path. pub fn is_path_key(k: &str) -> bool { - k == "path" + matches!(k, "path" | "diffPath") || is_folder_key(k) +} + +/// Path keys that name a folder a command creates or writes files into. +pub fn is_folder_key(k: &str) -> bool { + matches!(k, "folder" | "destinationFolder") +} + +/// The location to send under the path key `k`: `safe_path` for a file, a folder next to it for +/// a folder key. +pub fn safe_location(k: &str, safe_path: &str) -> String { + if is_folder_key(k) { format!("{safe_path}-folder") } else { safe_path.to_string() } +} + +/// `v`, or the temp location for `k` when `k` is a path key and `v` is a string. +pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { + if is_path_key(k) && v.is_string() { json!(safe_location(k, safe_path)) } else { v.clone() } } /// A deterministic list of junk param objects for `doc` (the command's params doc): each @@ -516,7 +532,7 @@ pub fn junk_params(doc: &str, safe_path: &str) -> Vec { let mut out = vec![Value::Null, json!([]), json!("str"), json!(42), json!({"unknownKey": 1})]; for k in &keys { for (i, v) in junk.iter().enumerate() { - let v = if is_path_key(k) && v.is_string() { json!(safe_path) } else { v.clone() }; + let v = safe_value(k, v, safe_path); // Sparse: one key at a time with every junk value, plus a few combos. let mut o = serde_json::Map::new(); o.insert(k.clone(), v.clone()); @@ -524,7 +540,7 @@ pub fn junk_params(doc: &str, safe_path: &str) -> Vec { if i % 5 == 0 { let mut all = serde_json::Map::new(); for k2 in &keys { - let v2 = if is_path_key(k2) { json!(safe_path) } else { v.clone() }; + let v2 = if is_path_key(k2) { json!(safe_location(k2, safe_path)) } else { v.clone() }; all.insert(k2.clone(), v2); } out.push(Value::Object(all)); From fdedff519e615fc79b061e044b46510e558e25e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:40:41 -0800 Subject: [PATCH 73/83] Graphs: centered labels with an empty middle line stay centered A centered label such as Q||1 has no baseline for its empty middle line, so a label that keeps more leading was not moved back to its place. The graph now centers a label whose first and last lines hold characters, whatever the lines between them hold. --- crates/engine/src/cmd/graph/labels.rs | 6 ++++-- crates/engine/src/cmd/graph/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 9d521c5d9b..b115714256 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -112,10 +112,12 @@ impl Gen<'_> { let start = if middle { Point::new(at.x, at.y - half) } else { at }; let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify); // Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An - // empty first or last line has no baseline, and such a label stays where the default leading puts it. + // empty line has no baseline: an empty first or last line leaves the label where the default leading puts it. if middle && kept_para(self.styles, role).is_some() { let ys: Vec = t.baselines().map(|(a, _)| a.y).collect(); - if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ys.len() == lines) { + let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty()); + let set = s.split('|').filter(|l| !l.is_empty()).count(); + if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) { t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf; } } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 7f85763a7e..efcd043208 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4370,6 +4370,33 @@ fn a_centered_label_with_kept_leading_stays_centered_when_the_graph_is_drawn_aga assert!((after - before).abs() < 0.01, "the two-line category label keeps its middle: {before} {after}"); } +#[test] +fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ||1,3,2\nQ2,5,4\nQ3,-1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let middle = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label = + group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n\n1")).unwrap(); + let b = label.geometric_bounds().unwrap(); + (b.y0 + b.y1) / 2.0 + }; + let before = middle(&s); + let l = text_id(&s, id, "Axes", "Q\n\n1"); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let after = middle(&s); + assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}"); +} + #[test] fn a_legend_across_top_measures_its_labels_with_system_layout() { let mut s = Session::new(); From ee40cc10d7dd2574dd22ea3086cb0d9190e35500 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:55:59 -0800 Subject: [PATCH 74/83] Rasterize: art longer than 32,768 pixels at the resolution is refused, not cut off Object > Rasterize and the redrawn path of Crop Image allowed images up to 65,535 pixels a side, but the renderer draws at most 32,768. A 100 x 5569 pt rectangle rasterized at 600 ppi came back 32,768 pixels tall, and the bottom 29% of the art was gone. Such an image is now refused like one over the 64 megapixel limit, and the art stays as it was. --- crates/engine/src/cmd/menucmds.rs | 6 ++++-- crates/engine/src/tests/menucmds.rs | 20 ++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index ed17677790..ba6941eb0d 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -670,7 +670,9 @@ fn render_pixels( opts: &vectorcraft_render::RenderOptions, color: RasterColorModel, ) -> Result<(vectorcraft_render::Rendered, Option<&'static str>)> { - if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > 65535.0 || region.height() * scale > 65535.0 { + // No side longer than the renderer draws: it would cut the image off there. + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > side || region.height() * scale > side { return Err(EngineError::Other("image would be too large; lower the resolution".into())); } let mut r = vectorcraft_render::Renderer::new(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index cf19f3cb1e..7ebe247161 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1461,6 +1461,26 @@ fn rasterize_replaces_selection_with_image() { assert_eq!(selected(&s), vec![img]); } +/// Rasterize refuses art that would be longer than the renderer draws (32,768 pixels a side), and +/// the art stays as it was; at a resolution that fits, the image covers all of it. +#[test] +fn rasterize_refuses_an_image_longer_than_the_renderer_draws() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 5569.0); + sel(&mut s, &[a]); + let vb = s.doc().unwrap().doc.bounds_of(&[a], true).unwrap(); + let before = (undo_len(&s), node(&s, a)); + let e = s.execute("object.rasterize", &json!({"ppi": 600, "padding": 0})).unwrap_err().to_string(); + assert!(e.contains("too large"), "{e}"); + assert_eq!((undo_len(&s), node(&s, a)), before); + let img = id_of(&s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap()); + let n = node(&s, img); + let NodeKind::Image(im) = &n.kind else { panic!() }; + assert!(im.height <= vectorcraft_render::MAX_RASTER_SIDE, "{} pixels", im.height); + let b = n.geometric_bounds().unwrap(); + assert!(close(b.y0, vb.y0) && b.y1 >= vb.y1, "{b:?} covers {vb:?}"); +} + /// Rasterize refuses a resolution given as text or as another value that is not a number, and the /// selected art stays as it was. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..b3eee15f69 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5169,7 +5169,8 @@ fills or strokes carry effects is written as one piece per fill and stroke, so o When an image in the art can't be decoded, `object.rasterize` and `object.cropImage` (without `trim`) make their image without it, and their results carry the `warning` that Flatten Transparency gives. `object.rasterize` takes each frame of threaded text that it rasterizes out of its thread with the text it shows, as `type.createOutlines` does (see -Threading text from the in and out ports), and the other frames keep the text they hold. +Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` +refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. ```json {"name":"run_command","arguments":{"command":"document.rasterEffectsSettings","params":{"resolution":"high","background":"white","addAround":36}}} From 2788707eed2bf1b238032f7578dd04dd7d4161c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 02:57:45 -0800 Subject: [PATCH 75/83] Docs: the script directives gap lists what remains --- docs/gaps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index f0619ff213..2bc5b47c14 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -689,7 +689,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts and script directives (#1183 is +- **Missing:** the document object model for scripts and the `#targetengine` and `#engine` script directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and From 794efc978b8ca283f66c79f33472863a3d83756d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:00:46 -0800 Subject: [PATCH 76/83] Type: an opened file flows its threads in its own composite fonts Threaded type read from a file was flowed through its frames before the document's composite fonts were registered, so a story set in one was measured in the fallback font. Frames then held the wrong share of the story after opening, until a frame was edited. load_with now lends the document's composite fonts while it lays out its threads. --- crates/engine/src/cmd/compositefonts/tests.rs | 26 +++++++++++++++++++ crates/engine/src/cmd/fileio/load.rs | 6 ++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index f51f066dfe..7997ca8f64 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -478,6 +478,32 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() { assert_eq!(actual.cached_bounds, Some(expected)); } +/// Threaded type read from a file flows through its frames in the file's own composite fonts, when +/// no open document defines them. +#[test] +fn an_opened_file_flows_its_threads_in_its_own_composite_fonts() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Threaded")]})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(4); + let a = s + .execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 20, "font": "CF Threaded", "area": {"width": 150, "height": 60}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let first = text(&s, a).plain_text(); + assert!(!first.is_empty() && first.len() < story.len()); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + // A new front document without the font: the font database no longer holds it. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert!(vectorcraft_text::FontDb::global().composite_font("CF Threaded").is_none()); + let file = crate::cmd::fileio::read_for_open("threaded.vectorcraft", &bytes, None, &json!({}), false, false).unwrap(); + crate::cmd::fileio::open_read(&mut s, file).unwrap(); + assert_eq!(text(&s, a).plain_text(), first); +} + /// A document replaced while in the back (File › Revert) is measured in its own composite fonts /// when it comes to the front, not in the front document's. #[test] diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1c1989bb94..9b3223829f 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -506,7 +506,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // document keeps its text as saved), and every frame of a thread takes its first frame's // Optical Margin Alignment setting and writing direction. When that changes the direction of a // frame of a restored document, the story flows through that frame's thread again. Threaded - // frames keep their size: Auto Size is off for them. + // frames keep their size: Auto Size is off for them. The story is laid out in the document's + // own composite fonts. + let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() }; + let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts); if !doc.text_threads.is_empty() && !restored { crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc); } else if !doc.text_threads.is_empty() { @@ -517,6 +520,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // paragraph's first-line indent and list marker. crate::cmd::threads::mark_continued(&mut doc); } + drop(lent); if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) { super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays); } From 8ebcc88c2e7f218cb56fbce022176f129e595a18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:03:53 -0800 Subject: [PATCH 77/83] Effects: a pasted SVG filter at the size limit still draws under its new name Pasted art whose SVG filter is renamed to a free name ("Soft 2") had the new name written into the filter's id. For a filter at the 64 KB limit the longer id made it too long to draw, so the pasted art lost the effect. Paste now takes the first free name under which the filter still fits: a shorter start of its name ("Sof"), else a free letter or digit. The filter's id is always the effect's name. --- crates/engine/src/cmd/clipboard/resources.rs | 19 ++++++++++++--- crates/engine/src/tests/svgfilter.rs | 25 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 5bea009485..22703b467d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1219,7 +1219,9 @@ impl Clipboard { /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a - /// free name, so editing or deleting the document's filter leaves it alone. + /// free name, so editing or deleting the document's filter leaves it alone. When that name would + /// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else + /// a free letter or digit; the filter's id is always its name. fn filter_links(&self, d: &Document, same_doc: bool) -> BTreeMap<(String, String), (String, String)> { let mut found = BTreeSet::new(); for n in &self.nodes { @@ -1244,9 +1246,20 @@ impl Clipboard { let to = if same_doc { (name.clone(), held.xml.clone()) } else { - let new = unique_name(&name, |n| taken.contains(n)); + // Free names made from the starts of the name, longest first, then free letters and + // digits: the first under which the filter still draws. + let mut ends: Vec = name.char_indices().map(|(i, _)| i).skip(1).collect(); + ends.push(name.len()); + let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty()); + let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n))); + let single = ('a'..='z').chain('0'..='9').map(String::from).filter(|n| !taken.contains(n)); + let renamed = shorter.chain(single).find_map(|new| { + let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new) + .filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok())?; + Some((new, drawn)) + }); + let Some((new, drawn)) = renamed else { continue }; taken.insert(new.clone()); - let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new).unwrap_or_else(|| xml.clone()); (new, drawn) }; links.insert((name, xml), to); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 4edcc6fd11..7606cebe4a 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -259,6 +259,31 @@ fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); } +/// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own +/// definition under a free name no longer than its own (a free letter for a one-letter name), and +/// its id is that name. +#[test] +fn pasted_art_with_a_filter_at_the_size_limit_still_draws_when_renamed() { + for (name, held, renamed) in [("Shift", SHIFT, "Shif"), ("S", r#""#, "a")] { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": held})); + let (open, close) = (format!(r#""#); + let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len())); + assert!(vectorcraft_render::effects::svg_filter::check(&big).is_ok()); + let svg = format!( + r#"{big}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, renamed, "renamed: {}", pasted[0].0); + assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(renamed.to_string()), "the pasted filter draws under its name"); + assert!(pasted[0].1.contains("dx=\"9\""), "its own filter"); + assert_eq!(names(&mut s), [name]); + } +} + /// Art in a symbol's definition that uses a filter follows its edits too. #[test] fn a_symbols_art_follows_a_filter_edit() { From dfa6e6ea6096e7fcbf1be2a66a06cafd6aa52d24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:20:14 -0800 Subject: [PATCH 78/83] MCP: ui.menu.list leaves out recent files outside the read roots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under --automation-read-root, a control client's ui.menu.list (and ui.contextMenu.list, which shares the listing) left every File › Open Recent Files row in, so the client saw the names of recent files it may not read. file.recentFiles returned their full paths, and file.openRecentN for such a file answered with a refusal naming the path. Now the listing leaves out a recent file outside the read roots, as it already leaves out listed scripts outside them. The other rows keep their ids, so file.openRecent3 still opens the third file. file.recentFiles returns only the files inside the roots, in order, and file.openRecentN for a file outside them ends with "no such recent file", as an empty slot does. The person's own menus and Home screen are unchanged. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/ui-egui/src/menus/entries.rs | 5 +++ crates/ui-egui/src/menus/run.rs | 6 +-- crates/ui-egui/src/menus/slots.rs | 8 ++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/automation.rs | 51 +++++++++++++++++++++++++ docs/control-protocol.md | 3 +- docs/mcp.md | 3 ++ docs/target-app-parity.md | 1 + 8 files changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 3c308970d6..815a00d6f9 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -1,6 +1,7 @@ use super::context::context_items; use super::invoke::click_target; use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; +use super::slots::{recent_readable, recent_slot}; use super::state::{shortcut_of, shown_state}; use super::tree::menu_tree_named; use super::{Entry, Item, Serialize, Value, VectorcraftApp}; @@ -133,6 +134,10 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve if *id == crate::scripts_menu::COMMAND && !crate::scripts_menu::readable(p) { continue; } + // The other rows keep their ids: `file.openRecent3` still opens the third file. + if id.starts_with("file.openRecent") && recent_slot(app, id).is_some_and(|path| !recent_readable(path)) { + continue; + } let Some((enabled, _)) = shown_state(app, id, p) else { continue }; out.push(MenuEntry { path: path.clone(), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 536ad79eb1..1223e1e426 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1,6 +1,6 @@ use super::bar::home_key; use super::invoke::menu_dialog; -use super::slots::{recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; +use super::slots::{recent_readable, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::state::{checked, selected_image}; use super::ui_commands::UI_COMMANDS; use super::{Brightness, Face, SaveMode, Value, VectorcraftApp, io, json, next_zoom}; @@ -137,7 +137,7 @@ fn run_ui_part1(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(io::hide_exports(app)), "file.cancelOpen" => Ok(crate::opening::cancel_all(app)), "file.openInBackground" => Ok(crate::opening::hide_all(app)), - id if id.starts_with("file.openRecent") => match recent_slot(app, id).cloned() { + id if id.starts_with("file.openRecent") => match recent_slot(app, id).filter(|path| recent_readable(path)).cloned() { Some(path) => io::open_reporting(app, &path), None => Err("no such recent file".into()), }, @@ -164,7 +164,7 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(json!(io::recent_files(app))), + "file.recentFiles" => Ok(json!(io::recent_files(app).iter().filter(|path| recent_readable(path)).collect::>())), "file.place" => crate::place::run(app, p), "file.place.queue" => crate::place::queue(app, p), "file.export.svg" if p.as_object().is_none_or(|o| o.is_empty()) => { diff --git a/crates/ui-egui/src/menus/slots.rs b/crates/ui-egui/src/menus/slots.rs index 2dee19dcff..5bd3bfb006 100644 --- a/crates/ui-egui/src/menus/slots.rs +++ b/crates/ui-egui/src/menus/slots.rs @@ -51,6 +51,14 @@ pub(super) fn recent_slot<'a>(app: &'a VectorcraftApp, id: &str) -> Option<&'a S io::recent_files(app).get(n.checked_sub(1)?) } +/// May the request being served read recent file `path`? Under an automation read root (a control +/// client's request), a recent file outside the root is left out of `ui.menu.list` and +/// `file.recentFiles`, and its `file.openRecentN` slot answers as an empty one, as a listed script +/// outside the root is left out ([`crate::scripts_menu::readable`]). +pub(super) fn recent_readable(path: &str) -> bool { + vectorcraft_engine::file_access::check_read(path).is_ok() +} + /// View → Perspective Grid → One/Two/Three Point Perspective: the saved-preset slots of each type. pub(super) const PERSPECTIVE_SLOTS: [[&str; crate::dialogs::perspective_presets::SLOTS]; 3] = [ [ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 06dcf85bcb..a96f13e67c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -137,7 +137,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{folder?} Type › Find Font's Find in Folder…: asks for a folder (or takes folder), then opens Missing Fonts looking there for the files of the fonts the active document misses (text.findFontFiles). Disabled where there is no folder picker (the web)", ), - ("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first"), + ("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first; under an automation read root, only the files inside it"), ( "file.export.svg", "Export As SVG…", diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index c66cc7cd5a..5eff145b17 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -304,6 +304,57 @@ fn frames_with_injected_input_are_confined() { let _ = std::fs::remove_dir_all(base); } +/// The enabled File › Open Recent Files rows `ui.menu.list` returns: (id, label). +fn recent_rows(entries: &Value) -> Vec<(String, String)> { + let rows = entries.as_array().map(Vec::as_slice).unwrap_or_default(); + rows.iter() + .filter(|e| e["command"].as_str().is_some_and(|c| c.starts_with("file.openRecent")) && e["enabled"] == true) + .map(|e| (e["command"].as_str().unwrap_or_default().to_string(), e["label"].as_str().unwrap_or_default().to_string())) + .collect() +} + +#[test] +fn recent_files_outside_the_read_root_are_not_listed_or_opened() { + let (mut app, tx, base) = confined("recent"); + std::fs::copy(base.join("in/a.svg"), base.join("in/c.svg")).unwrap(); + let (a, b, c) = (s(base.join("in/a.svg")), s(base.join("outside/b.svg")), s(base.join("in/c.svg"))); + app.ui.recent_files = vec![a.clone(), b.clone(), c.clone()]; + let rows = |pairs: &[(&str, &str)]| pairs.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect::>(); + + // The person's menu lists all three. + let person = serde_json::to_value(crate::menus::menu_entries(&app)).unwrap(); + assert_eq!(recent_rows(&person), rows(&[("file.openRecent1", "a.svg"), ("file.openRecent2", "b.svg"), ("file.openRecent3", "c.svg")])); + assert_eq!(app.run("file.recentFiles", json!({})).unwrap(), json!([a, b, c])); + + // The client's listing leaves out the second, and the third keeps its id. + let r = request(&mut app, &tx, "ui.menu.list", json!({})); + assert_eq!(recent_rows(&r["result"]), rows(&[("file.openRecent1", "a.svg"), ("file.openRecent3", "c.svg")]), "{r}"); + let r = request(&mut app, &tx, "engine.execute", json!({"command": "file.recentFiles"})); + assert_eq!(r["result"], json!([a, c]), "{r}"); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent2"})); + assert_eq!(r["error"], "no such recent file", "the reply names no path: {r}"); + assert!(app.session.documents().is_empty()); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent3"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.ui.recent_files, [c.clone(), a.clone(), b.clone()]); + + // A file outside the root that the person has open is still not brought forward. + app.run("file.openRecent3", json!({})).unwrap(); + assert_eq!((app.session.documents().len(), &app.ui.recent_files[0]), (2, &b)); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent1"})); + assert_eq!(r["error"], "no such recent file", "{r}"); + + // Rows past Number of Recent Files to Display stay out, and a write root alone lists none. + app.session.prefs.recent_files_count = 2; + let r = request(&mut app, &tx, "ui.menu.list", json!({})); + assert_eq!(recent_rows(&r["result"]), rows(&[("file.openRecent2", "c.svg")]), "{r}"); + let write_only = AutomationRoots::new(&[], &[&base.join("out")]).unwrap(); + let listed = vectorcraft_engine::file_access::confine(write_only.as_ref(), || serde_json::to_value(crate::menus::menu_entries(&app)).unwrap()); + assert!(recent_rows(&listed).is_empty(), "{listed}"); + let _ = std::fs::remove_dir_all(base); +} + /// Hidden logic-only ticks between the injection and its UI pass must not drain another step: /// one step per settled pass, not per hidden tick. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 02cc5c4384..96e5baffb3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -691,7 +691,8 @@ In the desktop app a Paste from the menus or the keys (`ui.key`) decodes a bitma `edit.paste*` reads it at once. File menu details: `file.openRecent1`…`file.openRecent30` open the recent files the `recentFilesCount` preference -lists (0 hides them all; `file.recentFiles` returns the listed paths), `file.reveal` shows the document's file in the +lists (0 hides them all; `file.recentFiles` returns the listed paths; under a read root, `ui.menu.list` and +`file.recentFiles` leave out the files outside it and `file.openRecentN` answers `no such recent file` for one), `file.reveal` shows the document's file in the system file manager (desktop only; answers `{path}`), and `file.newFromTemplate` without params opens a file picker in the Templates folder (preference `templatesFolder`). Older native files open as " [Converted]" (preference `appendConverted`), so their Save asks for a new `.vectorcraft` name. Native files reopen at the view they were saved diff --git a/docs/mcp.md b/docs/mcp.md index 82f2d1b061..3585c08df1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -112,6 +112,9 @@ the suite) keep the agent to the folders you give it: export commands, Export for Screens, Package, Export for Web, print to file, `screenshot {path}`, library and preset saves to a path, the copies `links.relink {copy}` makes. - `file.list {path}` (through `run_command`) lists a folder's files and folders, held to the read roots like any read, so an agent can see what it was given (#1163). +- `file.recentFiles` and the control channel's `ui.menu.list` leave out the recent files outside the read roots. The + other File › Open Recent Files rows keep their ids (`file.openRecent3` still opens the third file), and + `file.openRecentN` for a file outside the roots ends with `no such recent file`, as an empty slot does. - Each flag may be given more than once (#3546): a path inside any of the read roots may be read, one inside any of the write roots written, so one session can read a project folder and a shared assets folder, or write to an output folder and a scratch folder, without widening a root to their common parent. A folder given twice diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 764b7ebe80..e5c43c84a7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -732,6 +732,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, and `#strict on`, `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). From 68f3095cfd5bf3526b942c029e40c54178e3a188 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:21:57 -0800 Subject: [PATCH 79/83] Print: Print as Bitmap prints all of a page longer than 32,768 pixels Print as Bitmap limited each page's image to 65,535 pixels a side, but the renderer draws at most 32,768. A 9000 x 100 pt artboard at a 300 ppi raster effects resolution printed as an image that stopped at 7,864 pt and was placed as if whole. The resolution is now lowered until the longest side fits. --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/cmd/printadvanced.rs | 6 ++++-- crates/engine/src/tests/printadvanced.rs | 22 ++++++++++++++++++++++ docs/mcp.md | 4 +++- 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 44de123fa9..76e09641f9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index d181541c3d..537658447b 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -76,9 +76,11 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b let mut images = vec![]; for (_, r) in regions { let area = outset(r, bleed); - // At most MAX_PIXELS, and 65535 pixels a side. + // At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole + // pixels below). let side = area.width().max(area.height()).max(1.0); - let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(65_535.0 / side); + let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0; + let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side); if !(scale.is_finite() && scale > 0.0) { continue; } diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index 99cfcd3733..8faa2f7adf 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -130,6 +130,28 @@ fn print_as_bitmap_prints_an_image_of_each_artboard() { assert!(crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().is_none()); } +/// Print as Bitmap of an artboard longer than the renderer draws at the raster effects resolution +/// (32,768 pixels a side) prints an image of all of it, at a lower resolution. +#[test] +fn print_as_bitmap_prints_all_of_a_long_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 9000, "height": 100})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 100})).unwrap(); + let set = settings(json!({"advanced": {"printAsBitmap": true}})); + let saved = s.prefs.flattener_presets.clone(); + let bitmap = crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap(); + let mut placed = vec![]; + bitmap.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + placed.push((im.width, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))))); + } + }); + let [(width, b)] = placed[..] else { panic!("one image: {placed:?}") }; + assert!(width <= vectorcraft_render::MAX_RASTER_SIDE, "{width} pixels"); + assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}"); +} + /// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB /// black when `rich_black` is on. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9c28fbe5be..4bd806c427 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6122,7 +6122,9 @@ as Overprint Preview shows them (darkened); either way the file has no overprint overprints. `flattenerPreset` (High Resolution, Medium Resolution, Low Resolution or a saved preset, `flattener.presets.list`) flattens transparency before printing, as Object → Flatten Transparency does; empty, a PDF keeps it live (PostScript, which has none, uses `file.print`'s `flattenerPreset`, else this one, else medium). -`printAsBitmap` prints each composite page as one image of the art at the document's raster effects resolution. +`printAsBitmap` prints each composite page as one image of the art at the document's raster effects resolution, +or at the highest resolution that fits when the image would be larger than 64 million pixels or longer than 32,768 +pixels a side. `color.profile` names an RGB or CMYK profile: composite PDF colours are converted to it with `color.intent` (CMYK colours keep their numbers with `preserveNumbers`), so a CMYK profile writes device CMYK; separations separate with a CMYK one. Settings saved before these options load with their defaults. From ea0dd5fda548af4918a5b076daf0973b8bb8d9bc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:21:58 -0800 Subject: [PATCH 80/83] Legacy .ai export: a long transparent image is flattened whole Saving a legacy .ai of version 7 flattens each transparent image at its own resolution, limited only by total pixels. The renderer draws at most 32,768 pixels a side, so an image that came out longer than that at its resolution was cut off and placed as if whole: the part past that length showed the art under it without the image. The resolution is now lowered until the longest side fits. --- crates/engine/src/cmd/fileio/legacy_ai.rs | 4 +++- crates/engine/src/tests/legacy_ai.rs | 25 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 9bf7a311a0..a197363b23 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -270,7 +270,9 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result> { let pt = im.xf.determinant().abs().sqrt(); let ppi = if pt.is_finite() && pt > 0.0 { (72.0 / pt).clamp(MIN_PPI, MAX_PPI) } else { MIN_PPI }; let area = (bounds.width() * bounds.height()).max(1.0); - let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt()); + // No side longer than the renderer draws (rounded up to whole pixels below). + let longest = (f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0) / bounds.width().max(bounds.height()).max(1.0); + let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt()).min(longest); if !(scale.is_finite() && scale > 0.0) { return Ok(None); } diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 9a9aafcbac..fefed0ad11 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -368,6 +368,31 @@ fn a_transparent_image_is_flattened_with_the_art_under_it_which_stays() { assert_eq!(colour_at(page, 10.0, 20.0), [255, 0, 0], "the square outside the image"); } +/// A transparent image longer than the renderer draws at its own resolution (32,768 pixels a +/// side) is flattened whole, at a lower resolution. +#[test] +fn a_long_transparent_image_is_flattened_whole() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 4600})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 4600})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(2000, 1600, [0, 0, 0, 128])), "at": [50, 50]}); + s.execute("file.place", &p).unwrap(); + // 10 × 4500 pt: about 600 ppi, so 37,500 pixels long. + s.execute("object.setBounds", &json!({"x": 10, "y": 10, "width": 10, "height": 4500, "reference": 0})).unwrap(); + let before = [colour_at(&s.doc().unwrap().doc, 15.0, 100.0), colour_at(&s.doc().unwrap().doc, 15.0, 4400.0)]; + assert!(before.iter().all(|c| c[0] < 200), "the image darkens the red: {before:?}"); + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("flattened with the art under them")), "{r}"); + s.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let d = &s.doc().unwrap().doc; + let after = [colour_at(d, 15.0, 100.0), colour_at(d, 15.0, 4400.0)]; + for (a, b) in before.iter().zip(&after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "{before:?} {after:?}"); + } +} + /// A `size`×`size` PNG of a black disk of radius `r` pixels with an anti-aliased edge, clear /// around it, 72 ppi. fn disk(size: u32, r: f64) -> Vec { From 8b39cbc324f4a6c818e9ead05aa2ceec1887ee31 Mon Sep 17 00:00:00 2001 From: jmverges Date: Wed, 11 Nov 2026 10:54:30 +0000 Subject: [PATCH 81/83] .ai save: stroked type keeps its cap, join and miter limit The text document writer wrote a type stroke's paint and weight but not its cap, join or miter limit, which .ai import reads since #6500 (keys 61, 62 and 64). A file saved here and opened again came back with butt caps, miter joins and a miter limit of 10, and the save reported those attributes as left out. A stroked run now writes the three keys, numbered as PostScript numbers caps and joins, with the miter limit as import takes it back (1 to 500, else 10), and they no longer count as lost. A run without a stroke no longer counts them as lost either: they draw nothing. Follow-up to #6472. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/ai_editing/tests.rs | 24 +++++++++- crates/eps/src/ai_editing/writer/texts.rs | 56 +++++++++++++++++++++-- docs/file-format-parity.md | 3 +- 3 files changed, 76 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 28f67f2152..2023b8d47c 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3449,6 +3449,9 @@ fn typed() -> Document { v_scale: 90.0, stroke: solid(Color::rgb(0.0, 0.5, 0.0)), stroke_width: 0.5, + stroke_cap: vectorcraft_doc::LineCap::Square, + stroke_join: vectorcraft_doc::LineJoin::Bevel, + stroke_miter_limit: 2.5, all_caps: true, ..regular.clone() }; @@ -3565,7 +3568,7 @@ fn type_lines(doc: &Document) -> Vec { for r in &t.runs { let s = &r.style; out.push(format!( - " run {:?} {} {} {} {:?} {} {} {} {} fill {} stroke {} {} caps={} small={:?} tcy={} roman={}", + " run {:?} {} {} {} {:?} {} {} {} {} fill {} stroke {} {} {:?} {:?} {} caps={} small={:?} tcy={} roman={}", r.text, s.font_family, s.font_style, @@ -3578,6 +3581,9 @@ fn type_lines(doc: &Document) -> Vec { paint(&s.fill), paint(&s.stroke), r3(s.stroke_width), + s.stroke_cap, + s.stroke_join, + r3(s.stroke_miter_limit), s.all_caps, s.small_caps.map(r3), s.tate_chu_yoko, @@ -3718,6 +3724,22 @@ fn type_comes_back_as_type() { assert_eq!(back.text_threads.len(), 1, "the thread comes back"); } +/// A run without a stroke whose stroke's cap, join and miter limit aren't the defaults loses +/// nothing that draws: the save reports no attributes left out. +#[test] +fn an_unstroked_run_with_a_stroke_style_loses_nothing() { + use vectorcraft_doc::{CharStyle, LineCap, LineJoin, TextObject}; + for miter in [3.0, f64::NAN] { + let st = CharStyle { stroke_cap: LineCap::Round, stroke_join: LineJoin::Bevel, stroke_miter_limit: miter, ..style(14.0, Color::BLACK) }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Plain", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{miter}: {:?}", out.warnings); + } +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 1e02941c31..5ebd73de3a 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -21,15 +21,15 @@ use std::fmt::Write; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{ - AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, - PathEffect, TextKind, TextObject, VerticalAlign, + AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, + ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, }; use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and stroke weight, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -347,6 +347,9 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { fill: unlinked(&s.fill), stroke: unlinked(&s.stroke), stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, + stroke_cap: if stroked { s.stroke_cap } else { CharStyle::default().stroke_cap }, + stroke_join: if stroked { s.stroke_join } else { CharStyle::default().stroke_join }, + stroke_miter_limit: if stroked { miter_limit(s.stroke_miter_limit) } else { CharStyle::default().stroke_miter_limit }, all_caps: s.all_caps, small_caps: s.small_caps.filter(|v| *v == default_small_caps), tate_chu_yoko: s.tate_chu_yoko, @@ -357,7 +360,19 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; let run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); - let s = CharStyle { stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, ..s.clone() }; + // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. + let unstroked = CharStyle::default(); + let s = if stroked { + s.clone() + } else { + CharStyle { + stroke_width: unstroked.stroke_width, + stroke_cap: unstroked.stroke_cap, + stroke_join: unstroked.stroke_join, + stroke_miter_limit: unstroked.stroke_miter_limit, + ..s.clone() + } + }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) @@ -463,6 +478,32 @@ fn font_name(st: &CharStyle) -> FontRecord { } } +/// The text document's number for a stroke's cap (key 61), as PostScript numbers them: 0 butt, 1 +/// round, 2 projecting. +fn cap_code(cap: LineCap) -> i64 { + match cap { + LineCap::Butt => 0, + LineCap::Round => 1, + LineCap::Square => 2, + } +} + +/// The text document's number for a stroke's join (key 62), as PostScript numbers them: 0 miter, 1 +/// round, 2 bevel. +fn join_code(join: LineJoin) -> i64 { + match join { + LineJoin::Miter => 0, + LineJoin::Round => 1, + LineJoin::Bevel => 2, + } +} + +/// A stroke's miter limit (key 64) as the reader takes it back: at least 1 and at most 500, 10 when +/// it isn't a number at least 1. +fn miter_limit(v: f64) -> f64 { + if v.is_finite() && v >= 1.0 { v.min(500.0) } else { 10.0 } +} + /// `v` as the 16.16 fixed-point number a design vector holds (`wght` 700 is 45875200). fn fixed(v: f32) -> i64 { if v.is_finite() { (f64::from(v) * 65536.0).round() as i64 } else { 0 } @@ -621,7 +662,12 @@ impl TextDoc { } d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]); if stroke.is_some() { - d.push((63, V::Small(st.stroke_width / scale))); + d.extend([ + (61, V::Int(cap_code(st.stroke_cap))), + (62, V::Int(join_code(st.stroke_join))), + (63, V::Small(st.stroke_width / scale)), + (64, real(miter_limit(st.stroke_miter_limit))), + ]); } dict(d) } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a18b717056..8e38543a22 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` save: stroked type writes its stroke's cap, join and miter limit into the text document (keys 61, 62 and 64, as `.ai` import reads them since #6500), so they come back when the file opens again and no longer count among the attributes of type left out; a run without a stroke doesn't count them either, as they draw nothing. Tests `ai_editing::tests::type_comes_back_as_type`, `an_unstroked_run_with_a_stroke_style_loses_nothing` (follow-up to #6472) | | 2026-11-11 | minor | `.ai` and EPS import, PDF import, SVG export and `.ai` save: type with a Horizontal Scale other than 100% and tracking or manual kerning is spaced as a `.ai`'s own page spaces it. Layout now measures tracking and manual kerning in thousandths of the em as the scale draws it (see type-parity.md, same date); they were added at the full em, so such type drifted from the page letter by letter. A `.ai`'s page writes that type's character spacing as the tracking itself in a text space as wide as the scale, which PDF scales by it (ISO 32000-1 §9.4.4). In 224 users' files (used locally, never committed), 93 render differently. Of the 25 whose render moved by more than 1% of its pixels against the page, 23 came closer. The note on the type differing from the page shows a smaller share in 5 files (11.0% to 4.4% at most) and a larger one in 2 (by 0.2 to 0.3 points). 9 more envelopes of type open live (113 to 122 of 203, none fewer in any file), and no file switched between its layers and its PDF part. PDF import: the tracking of horizontally scaled type is the file's `Tc` in thousandths of its size (it was that times the scale), the glyphs where they were (test `tests::text_placement::character_spacing_in_horizontally_scaled_type_is_the_files_tc`). SVG export writes the letter spacing in thousandths of the font size it writes (the vertical scale), so type scaled uniformly keeps its spacing in a viewer (test `text_layout::spacing_in_uniformly_scaled_type_takes_the_scale`); tracked type scaled horizontally alone still differs a little there, as before. A `.ai` saved here writes the same values as before; VectorCraft now lays them out as the file's own PDF part draws them. Scores and estimates unchanged. | | 2026-11-11 | minor | `.ai` and EPS import: stroked type in an envelope with Distort Appearance is tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, for a stroke on its appearance or on a group round it as well as its characters'; it was mapped from its bounds with strokes, which reach as far as a miter join may at a corner. Tests `ai::envelope::tests::stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke`, `type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes`, `a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. A second try is only made while more checks are left than there are envelopes of type and warped text objects still to come. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box (a rule chosen by measuring real files). An envelope's grid (warp, mesh or top object) now reads its way round from all its rows and columns, not its first row alone: a mesh bent far round (its end columns leaning more than halfway over) reads the way it runs, not turned a quarter round, and a grid symmetric about its middle reads the same wherever it is on the page. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `a_warp_of_type_tried_again_leaves_the_next_envelope_its_check`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs`, `a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is` (part of #3179) | From c03fe29ad8044a247c0022c32e33004b6371cd9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:41:05 -0800 Subject: [PATCH 82/83] Plug-ins: the web build times the first-view budget and each run's limit The web build had no clock for plug-in runs, so its first view deferred every plug-in live effect until Effect > Refresh Deferred Effects, and a run's wall-clock limit was not enforced there. The deferrals clock and the run deadline now read `web_time::Instant`, which is the system's monotonic clock on the desktop and the page's `performance.now()` in the web build. The web's first view now shares the same 2,000 ms budget, and its runs stop at the 5 s, 60 s and 300 s limits as on the desktop. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- Cargo.lock | 1 + crates/plugins/Cargo.toml | 4 ++++ crates/plugins/src/deferred.rs | 25 ++++++++++++++----------- crates/plugins/src/export.rs | 3 +-- crates/plugins/src/host.rs | 28 ++++++++++++++-------------- crates/plugins/src/lib.rs | 2 +- crates/plugins/src/runtime.rs | 6 +++--- docs/mcp.md | 4 ++-- docs/plugins.md | 6 +++--- docs/target-app-parity.md | 2 +- 10 files changed, 44 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c3a087e845..74b6189119 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6687,6 +6687,7 @@ dependencies = [ "vectorcraft-geom", "wasmi", "wat", + "web-time", ] [[package]] diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 7c18f2c066..ef21a57ef4 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -22,6 +22,10 @@ craft-vectorcraft-format = { workspace = true } sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } wasmi = { workspace = true } +# The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the +# desktop, the page's `performance.now()` in the web build. It is MIT OR Apache-2.0 and already in +# the build through eframe. +web-time = "1" [dev-dependencies] wat = { workspace = true } diff --git a/crates/plugins/src/deferred.rs b/crates/plugins/src/deferred.rs index f817f32d90..1645dd55e0 100644 --- a/crates/plugins/src/deferred.rs +++ b/crates/plugins/src/deferred.rs @@ -86,20 +86,15 @@ pub struct Refreshed { pub failed: usize, } -/// Milliseconds on a monotonic clock, `None` where there is none (the web build). +/// Milliseconds on a monotonic clock, `None` from a clock that cannot be read. pub type Clock = Arc Option + Send + Sync>; -/// Milliseconds since the first reading in this process (native builds); `None` on the web build, -/// whose `std` has no monotonic clock. +/// Milliseconds since the first reading in this process, from `web_time::Instant`: the system's +/// monotonic clock on the desktop and the page's `performance.now()` in the web build. fn monotonic() -> Option { - #[cfg(not(target_arch = "wasm32"))] - { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - let start = START.get_or_init(std::time::Instant::now); - Some(u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)) - } - #[cfg(target_arch = "wasm32")] - None + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let start = START.get_or_init(web_time::Instant::now); + Some(u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)) } #[derive(Clone, Copy, Debug, PartialEq)] @@ -579,6 +574,14 @@ mod tests { }); } + /// The default clock, which the web build also reads, gives the first view its budget. + #[test] + fn the_default_clock_gives_the_first_view_a_budget() { + let d = Deferrals::new(); + assert!(matches!(d.allowance(), Allowance::Until { ms: OPENING_BUDGET_MS, .. })); + assert!(!d.passed(u64::MAX)); + } + /// A stage drawn with several inputs (the paths of a group) holds one record for each, and is /// listed and counted once. #[test] diff --git a/crates/plugins/src/export.rs b/crates/plugins/src/export.rs index b51fcfdb97..76b1316b7c 100644 --- a/crates/plugins/src/export.rs +++ b/crates/plugins/src/export.rs @@ -24,8 +24,7 @@ use crate::{Error, Kind, Limits, Plugin, Result, registry}; /// document: 200 times a filter's base budget. pub const FUEL: u64 = 10_000_000_000; -/// Wall-clock budget of one export, in milliseconds (native builds; the web build has no clock, -/// and the instruction budget alone bounds it there). +/// Wall-clock budget of one export, in milliseconds. pub const WALL_TIME_MS: u64 = 300_000; /// Most warnings an export reports. diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 474234880b..b98407cb7c 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -321,29 +321,20 @@ pub struct Report { /// The limit a run past its wall-clock deadline exceeded ([`Error::Limit`]). pub(crate) const TIME_BUDGET: &str = "time budget"; -/// When a run must stop (native: a wall-clock deadline). +/// When a run must stop: a deadline on the monotonic clock (`web_time::Instant`, the page's +/// `performance.now()` in the web build). #[derive(Clone, Copy)] pub(crate) struct Deadline { - #[cfg(not(target_arch = "wasm32"))] - at: std::time::Instant, + at: web_time::Instant, } impl Deadline { pub(crate) fn new(wall_time_ms: u64) -> Self { - #[cfg(target_arch = "wasm32")] - let _ = wall_time_ms; - Self { - #[cfg(not(target_arch = "wasm32"))] - at: std::time::Instant::now() + std::time::Duration::from_millis(wall_time_ms), - } + Self { at: web_time::Instant::now() + std::time::Duration::from_millis(wall_time_ms) } } pub(crate) fn passed(&self) -> bool { - #[cfg(not(target_arch = "wasm32"))] - if std::time::Instant::now() >= self.at { - return true; - } - false + web_time::Instant::now() >= self.at } pub(crate) fn check(&self) -> Result<()> { @@ -816,6 +807,15 @@ mod tests { Run::new("test", true, false, Deadline::new(60_000)) } + /// A deadline reads the monotonic clock that the web build also reads: one of 0 ms has + /// passed, and one a day away has not. + #[test] + fn a_deadline_passes_on_the_monotonic_clock() { + assert!(Deadline::new(0).passed()); + assert!(matches!(Deadline::new(0).check(), Err(Error::Limit(l)) if l == TIME_BUDGET)); + assert!(!Deadline::new(86_400_000).passed()); + } + /// Progress is clamped: negative counts are 0 and `done` never passes a known total. #[test] fn progress_is_clamped() { diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 63f879c2f9..8b57adbe63 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -9,7 +9,7 @@ //! permission): no WASI, file system, network, clock or randomness. A module that //! imports anything else is rejected; //! - an **instruction budget** (fuel) per call, metered in slices so a wall-clock deadline is -//! also enforced (native builds), so infinite loops end with an error. A filter may ask for a +//! also enforced, so infinite loops end with an error. A filter may ask for a //! larger one ([`Budget::Heavy`]), which the host lets the user allow before installing it; //! - a **linear-memory cap**, a **recursion-depth cap** and wasmi's strict module limits; //! - a **fresh instance per run**, so no state leaks between calls; what a plug-in keeps is only diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5abaa0bf48..863ec0a3a5 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -29,7 +29,7 @@ const FUEL_COSTS: CustomFuelCosts = CustomFuelCosts { bytes_copied_per_fuel: 64, /// the host learns that only once the run has ended. pub const HEAVY_FUEL: u64 = 1_000_000_000; -/// Wall-clock budget of a heavy filter's run, in milliseconds (native builds). +/// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; /// The limit a run reports when its input and parameters together are past half its memory. @@ -56,8 +56,8 @@ pub struct Limits { pub fuel_per_byte: u64, /// Deepest call nesting. pub max_recursion_depth: usize, - /// Wall-clock budget for one run, in milliseconds. Native builds only: the web build has no - /// monotonic clock in `std`, so the fuel budget alone bounds it there. + /// Wall-clock budget for one run, in milliseconds. The web build measures it with the page's + /// `performance.now()`. pub wall_time_ms: u64, /// The most a heavy filter ([`crate::Budget::Heavy`]) is given instead of `fuel_base` and /// `wall_time_ms`: what the host allows, which the module's manifest can ask for but never diff --git a/docs/mcp.md b/docs/mcp.md index 013574e591..0c560193d9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7319,8 +7319,8 @@ and the stages with a part of their input too small for the drawing the refresh timed out, failed or have no plug-in. `id` names one object in place of `ids`, and an entry that is not an object id of the document is an error. Each document has its own budget and its own deferred stages. Exports, Expand Appearance and commands run every stage under the per-call limit, so an export never leaves out a stage that was only -deferred for time, and the canvas then draws the result. The web build has no clock for the budget: there the first -view runs no plug-in effect, and Refresh Deferred Effects runs them. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): +deferred for time, and the canvas then draws the result. The web build measures the budget and the per-call +limit with the page's `performance.now()`. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): `document.export {format: "plugin.", params?, path?}` writes it, as does a `path` ending in one of its extensions that no built-in format has. An importer adds a read-only file format `plugin.` (listed by `document.formats` with `read: true`, and `openExtensions` holds the extensions File › Open opens with it, without those a built-in format reads or that File › Open installs, imports or loads as something else, such as `.wasm` or `.ase`): `document.open {path | name, dataBase64, importer?: diff --git a/docs/plugins.md b/docs/plugins.md index 55de6cdafc..3a934c9120 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -128,7 +128,7 @@ The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssem | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | | Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (desktop; checked every 20 M instructions) | `Limit("time budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | @@ -147,8 +147,8 @@ refuses or has no plug-in, draws its input art unchanged and is deferred. The st are deferred, and later drawings leave them as they are until their input or parameters change. Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget, and `effect.deferredStatus` lists them with the reason (`budget`, `timeout`, `missing`, `failed`, `safeMode`). Each document has its own budget. -Exports, Expand Appearance and commands run every stage under the 5 s limit. The web build has no clock for the -budget, so there the first view runs no live effect and Refresh Deferred Effects runs them. +Exports, Expand Appearance and commands run every stage under the 5 s limit. The web build has the same budget, +measured with the page's `performance.now()`. ### Heavy filters diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 31cb7837c7..3547a6ba53 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1650,7 +1650,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. -- **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache totals in memory (#6228):** the settings stay in memory while `settings.json` keeps its size and modified time, a set to the same value writes nothing, every other change is written to the file before the call returns, and `cacheBytes` comes from a total kept while the `cache` folder keeps its modified time. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From 4cde1aaa1fdd2d205ae15767efddcdff0427b22d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 03:44:25 -0800 Subject: [PATCH 83/83] Pen: Escape after the path is deselected ends something else The Pen and the Smart Pen reported a path being drawn to Escape for as long as they remembered the path, even after Deselect or Undo left it unselected. That Escape then ended nothing, and isolation mode or a rotated view needed a second press. Both tools now report the path only while they would go on drawing it, as the Curvature tool does. Follows #6405 --- crates/tools/src/addons/smart_pen.rs | 4 ++-- crates/tools/src/pen.rs | 4 ++-- crates/ui-egui/src/tests/rotateview.rs | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 4ee448830d..68c19cc676 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -548,8 +548,8 @@ impl Tool for SmartPenTool { } /// A path being drawn: Escape ends it. - fn ends_on_escape(&self, _cx: &ToolContext) -> bool { - self.path.is_some() + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index bc564fced3..b70a160d8a 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -243,8 +243,8 @@ impl Tool for PenTool { self.drag.is_some() || self.handle.is_some() || self.convert.is_some() } /// A path being drawn: Escape ends it. - fn ends_on_escape(&self, _cx: &ToolContext) -> bool { - self.path.is_some() + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index 2f98a3f3b1..dbdb0283fd 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -535,6 +535,23 @@ fn escape_that_ends_a_path_being_drawn_keeps_the_rotation() { } } +/// A path that is no longer selected is not being drawn: the next Escape resets the view. +#[test] +fn escape_after_deselecting_the_path_resets_the_view() { + for tool in ["pen", "smartPen", "curvature"] { + let mut w = Window::new(); + w.app.select_tool(tool); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: a path is being drawn"); + w.app.run("select.none", json!({})).unwrap(); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: the path is not selected"); + w.escape(0.2); + assert_eq!(w.rotation(), 0.0, "{tool}: one Escape resets the view"); + } +} + /// In isolation mode, an Escape that ends the Pen's path ends only the path: the next Escape leaves /// isolation mode, and the one after it resets the view. #[test]