From 263fe41e71c28469e25e904fe169209439f9668d Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:19:03 +0430 Subject: [PATCH 001/298] Fix #5267: Outline Stroke is in the canvas context menu --- crates/engine/src/cmd/pathops.rs | 10 ++++++++ crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/menus/context.rs | 4 +++ crates/ui-egui/src/tests/contextmenu.rs | 33 +++++++++++++++++++++++++ docs/gaps.md | 3 ++- docs/target-app-parity.md | 5 ++-- docs/ui-parity.md | 5 ++-- 7 files changed, 56 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index e1fecc6da3..e98e336feb 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -811,6 +811,16 @@ fn outlinable(st: &StrokeLayer) -> bool { st.visible && !st.paint.is_none() && st.width > 0.0 } +/// Does Outline Stroke have a stroke to turn into art somewhere under `n`: a visible stroke of +/// some paint and weight on a path or compound path (type is not outlined by it)? +pub fn has_outlinable_stroke(n: &Node) -> bool { + let mut found = false; + each_leaf(n, &mut |l| { + found |= !matches!(l.kind, NodeKind::Text(_)) && l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))); + }); + found +} + /// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a /// group around it. pub(crate) fn with_transparency(d: &mut Document, mut n: Node, opacity: f32, blend: BlendMode) -> Node { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2a9fb16289..88d8c836ae 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,7 +29,7 @@ pub use cmd::clipboard::Clipboard; pub use cmd::create::constrain_click; pub use cmd::distortcmds::perspective_click; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::auto_simplify_level; +pub use cmd::pathops::{auto_simplify_level, has_outlinable_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 3af95c6074..cad797710b 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -99,6 +99,10 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if paths { v.extend([c("Join", "path.join"), c("Average…", "path.average")]); } + // Outline Stroke turns strokes into filled art: offered when some object has a stroke to outline. + if roots.iter().any(|n| vectorcraft_engine::has_outlinable_stroke(n)) { + v.push(c("Outline Stroke", "object.path.outlineStroke")); + } if !st.selection.anchors.is_empty() { v.extend([c("Remove Anchor Points", "path.removeAnchors"), c("Cut Path at Selected Anchor Points", "path.cutAtAnchors")]); } diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index e4445ca343..9e56d86a00 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -381,3 +381,36 @@ fn every_context_label_is_a_menu_string() { assert!(shown.contains(label), "`{label}` is listed but the context menu never shows it"); } } + +/// #5267: a right-click on a stroked object offers Outline Stroke, which runs +/// `object.path.outlineStroke` (the Object › Path item) and leaves filled art; an object with no +/// stroke to outline has no such item. +#[test] +fn the_canvas_context_menu_offers_outline_stroke_for_a_stroked_selection() { + use vectorcraft_doc::AppearanceItem; + let mut app = app(); + let id = rect(&mut app, 50.0, 50.0); + // Stroked: a visible stroke of some weight. + app.run("stroke.set", json!({"weight": 6})).unwrap(); + let strokes = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + n.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)).count() + }; + assert!(strokes(&app) > 0, "the rectangle starts with a stroke"); + let ctx = egui::Context::default(); + app.run("select.none", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 100.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Outline Stroke"), "Outline Stroke in {texts:?}"); + click(&mut app, &ctx, at(&texts, "Outline Stroke"), PointerButton::Primary); + let st = app.session.active().unwrap(); + assert!(st.doc.node(id).is_none(), "the stroked rectangle was replaced by its outline"); + assert_eq!(strokes(&app), 0, "the outline is filled art with no stroke left"); + + // The outline has no stroke any more: nothing to outline, so no item. + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Arrange"), "the menu opened: {texts:?}"); + assert!(!has(&texts, "Outline Stroke"), "no stroke, no Outline Stroke in {texts:?}"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 8b707fd9f6..056cf26a81 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 (the canvas context menu offers Outline Stroke for a stroked selection, #5267; no entry closed, estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -732,6 +732,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The canvas context menu offers Outline Stroke for a stroked selection (#5267); no entry closed, estimates unchanged. | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4370a3a0c..4f9693dce4 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 (the canvas context menu offers Outline Stroke for a stroked selection, #5267; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -642,7 +642,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes 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. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. + - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection; Outline Stroke when the selection has a visible stroke to outline, #5267), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). @@ -1565,6 +1565,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The canvas context menu offers Outline Stroke for a stroked selection (#5267); scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | | 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26d3dd6790..db24cddf29 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 (the canvas context menu offers Outline Stroke for a stroked selection, #5267; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -339,7 +339,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: question marks for mixed modes, hit-testing by the area | -| Canvas context menu | done | Layers rows, panels and type have none (gap) | +| Canvas context menu | done | Layers rows, panels and type have none (gap). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after Join and Average (#5267) | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | | Retype, Comments, Version History panels | missing | the last two are cloud features (out of scope) | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior; on-canvas easing handles remain missing. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | @@ -418,6 +418,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The canvas context menu offers Outline Stroke when the selection has a stroke to outline (#5267); 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 e6fb5e66c7aeb6e55d898e651faae6db070a7474 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:50:49 +0430 Subject: [PATCH 002/298] Fix #5267: Outline Stroke eligibility follows the command's roots (review) --- crates/engine/src/cmd/edit.rs | 8 +++-- crates/engine/src/cmd/pathops.rs | 11 +++++-- crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/menus/context.rs | 4 +-- crates/ui-egui/src/tests/contextmenu.rs | 43 +++++++++++++++++++++++++ 5 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f252d09ff9..6ad25f82b9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -562,8 +562,12 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate:: /// Selected top-level objects in paint order, dropping any whose ancestor is also selected. pub(crate) fn selected_roots(s: &Session) -> Result> { - let st = s.doc()?; - Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc))) + Ok(selection_roots(s.doc()?)) +} + +/// [`selected_roots`] of one document's selection. +pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { + roots_of(&st.doc, st.selection.in_paint_order(&st.doc)) } /// [`selected_roots`] for the commands that move or reshape the art (Move, Transform, Rotate…): a diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index e98e336feb..b062bc33f8 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -13,7 +13,7 @@ use vectorcraft_geom::{FillRule, PathData}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; -use super::edit::selected_roots; +use super::edit::{selected_roots, selection_roots}; use super::{ CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param, switch_or, @@ -813,7 +813,7 @@ fn outlinable(st: &StrokeLayer) -> bool { /// Does Outline Stroke have a stroke to turn into art somewhere under `n`: a visible stroke of /// some paint and weight on a path or compound path (type is not outlined by it)? -pub fn has_outlinable_stroke(n: &Node) -> bool { +fn has_outlinable_stroke(n: &Node) -> bool { let mut found = false; each_leaf(n, &mut |l| { found |= !matches!(l.kind, NodeKind::Text(_)) && l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))); @@ -821,6 +821,13 @@ pub fn has_outlinable_stroke(n: &Node) -> bool { found } +/// Does `object.path.outlineStroke` have a stroke to outline in `st`'s selection? It acts on the +/// selection's roots (a compound path's member stands for its compound, which holds the +/// appearance), so eligibility looks at those same roots, not at the selected nodes themselves. +pub fn can_outline_stroke(st: &crate::DocState) -> bool { + selection_roots(st).into_iter().filter_map(|id| st.doc.node(id)).any(has_outlinable_stroke) +} + /// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a /// group around it. pub(crate) fn with_transparency(d: &mut Document, mut n: Node, opacity: f32, blend: BlendMode) -> Node { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 88d8c836ae..bd1a91b3cf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,7 +29,7 @@ pub use cmd::clipboard::Clipboard; pub use cmd::create::constrain_click; pub use cmd::distortcmds::perspective_click; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::{auto_simplify_level, has_outlinable_stroke}; +pub use cmd::pathops::{auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index cad797710b..655ea057ad 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -99,8 +99,8 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if paths { v.extend([c("Join", "path.join"), c("Average…", "path.average")]); } - // Outline Stroke turns strokes into filled art: offered when some object has a stroke to outline. - if roots.iter().any(|n| vectorcraft_engine::has_outlinable_stroke(n)) { + // Outline Stroke turns strokes into filled art: offered when the command has a stroke to outline in its roots. + if vectorcraft_engine::can_outline_stroke(st) { v.push(c("Outline Stroke", "object.path.outlineStroke")); } if !st.selection.anchors.is_empty() { diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 9e56d86a00..cefa6f4f34 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -414,3 +414,46 @@ fn the_canvas_context_menu_offers_outline_stroke_for_a_stroked_selection() { assert!(has(&texts, "Arrange"), "the menu opened: {texts:?}"); assert!(!has(&texts, "Outline Stroke"), "no stroke, no Outline Stroke in {texts:?}"); } + +/// A compound path of two rectangles, filled and stroked with `weight`, isolated, with a member +/// right-clicked → (the app, the context, the compound path, the context menu's text). The member +/// stays selected and has no appearance of its own: the compound holds the paint. +fn right_click_member_of_compound(weight: f64) -> (VectorcraftApp, egui::Context, NodeId, Vec<(String, Rect)>) { + let mut app = app(); + let ctx = egui::Context::default(); + let (a, b) = (rect(&mut app, 50.0, 50.0), rect(&mut app, 200.0, 50.0)); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + let compound = app.session.active().unwrap().selection.objects[0]; + // Filled, so that a click inside a member hits it whether or not the compound has a stroke. + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("stroke.set", json!({"weight": weight})).unwrap(); + menus::invoke(&mut app, "object.isolate", json!({})); + frame(&mut app, &ctx, vec![]); + let member = app.session.active().unwrap().doc.node(compound).and_then(|n| n.children().and_then(|c| c.first()).map(|m| m.id)).unwrap(); + app.run("select.set", json!({"ids": [member.0]})).unwrap(); + let p = screen(&app, 100.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects, [member], "the right-click leaves the member selected"); + assert!(st.doc.node(member).is_some_and(|m| m.appearance.items.is_empty()), "a member has no appearance of its own"); + (app, ctx, compound, texts) +} + +/// With a member of an isolated compound path selected (a right-click inside the isolated compound +/// leaves a member selected), the member's own appearance is empty: the compound holds the paint. +/// `object.path.outlineStroke` promotes the member to its compound, so the menu offers Outline +/// Stroke exactly when the compound has a stroke to outline. +#[test] +fn outline_stroke_is_offered_for_a_member_of_a_stroked_compound_path() { + // No stroke on the compound path: nothing to outline. + let (.., texts) = right_click_member_of_compound(0.0); + assert!(has(&texts, "Arrange"), "the menu opened: {texts:?}"); + assert!(!has(&texts, "Outline Stroke"), "no stroke, no Outline Stroke in {texts:?}"); + + // Stroked: the item is offered for the member, and the command outlines the compound. + let (mut app, ctx, compound, texts) = right_click_member_of_compound(6.0); + assert!(has(&texts, "Outline Stroke"), "Outline Stroke for a member of a stroked compound in {texts:?}"); + click(&mut app, &ctx, at(&texts, "Outline Stroke"), PointerButton::Primary); + assert!(app.session.active().unwrap().doc.node(compound).is_none(), "the stroked compound path was replaced by its outline"); +} From 87db7a4cdebb8c5e967979fe0fbc580794a6e1a5 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:51:02 +0430 Subject: [PATCH 003/298] 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 8fc64aad1b..d68045d16d 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; the canvas context menu offers Outline Stroke for a stroked selection, #5267; no entry closed, estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267); 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 2078cc239f..7e5f2a35b4 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; the canvas context menu offers Outline Stroke for a stroked selection, #5267; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267); 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 c237c5cd83..b1fdbd1b5c 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; the canvas context menu offers Outline Stroke for a stroked selection, #5267; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267); 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 3b1bd98781021c0342678b4a3926f5a24849d55a Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:40:07 +0430 Subject: [PATCH 004/298] docs: resolve target-app-parity.md conflict markers --- docs/target-app-parity.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9480748304..ec27a479e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -860,12 +860,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes 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. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). -<<<<<<< HEAD - - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection; Outline Stroke when the selection has a visible stroke to outline, #5267; and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. -======= - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. ->>>>>>> origin/main + - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection; Outline Stroke when the selection has a visible stroke to outline, #5267; and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). From b421daf6c57497804a025cc605ab946747ceaedb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 20:32:57 +0000 Subject: [PATCH 005/298] UI: add status-bar snapping quick access Show compact Smart Guides, Point and Grid controls with the existing snapping menu. Preserve message room and collapse the convenience controls when narrow. Closes #8687. --- crates/ui-egui/src/chrome/control_bar.rs | 53 ++--- crates/ui-egui/src/chrome/status_bar.rs | 47 ++++- crates/ui-egui/src/chrome/tests.rs | 236 ++++++++++++++++++++++- docs/gaps.md | 5 +- docs/roadmap.md | 7 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 6 +- 7 files changed, 328 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ce7f95808d..b3dfb7ba47 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -136,33 +136,36 @@ fn snapping_width(ui: &Ui) -> f32 { /// The Control bar's snapping quick access; every change uses its existing command, and Pixel /// Snapping Options… opens the dialog of `view.snapToPixel.options`. fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { - ui.menu_button(tl!("Snapping"), |ui| { - for (label, cmd, on) in [ - (tl!("Smart Guides"), "view.smartGuides", app.ui.view.smart_guides), - (tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point), - (tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid), - (tl!("Snap to Pixel"), "view.snapToPixel", app.ui.view.snap_to_pixel), - (tl!("Snap to Glyph"), "view.snapToGlyph", app.ui.view.snap_to_glyph), - ] { - if widgets::check(ui, label, on, true) { - crate::menus::invoke(app, cmd, json!({})); - } + ui.menu_button(tl!("Snapping"), |ui| snapping_menu_contents(app, ui)); +} + +/// The same snapping commands and preferences in the Control and status bars. +pub(super) fn snapping_menu_contents(app: &mut VectorcraftApp, ui: &mut Ui) { + for (label, cmd, on) in [ + (tl!("Smart Guides"), "view.smartGuides", app.ui.view.smart_guides), + (tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point), + (tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid), + (tl!("Snap to Pixel"), "view.snapToPixel", app.ui.view.snap_to_pixel), + (tl!("Snap to Glyph"), "view.snapToGlyph", app.ui.view.snap_to_glyph), + ] { + if widgets::check(ui, label, on, true) { + crate::menus::invoke(app, cmd, json!({})); } - if ui.button(tl!("Pixel Snapping Options…")).clicked() { - ui.close(); - crate::menus::invoke(app, "view.snapToPixel.options", json!({})); + } + if ui.button(tl!("Pixel Snapping Options…")).clicked() { + ui.close(); + crate::menus::invoke(app, "view.snapToPixel.options", json!({})); + } + ui.separator(); + for (key, label, on) in [ + ("alignmentGuides", tl!("Alignment Guides"), app.session.prefs.alignment_guides), + ("snapTangent", tl!("Snap to Tangent"), app.session.prefs.snap_tangent), + ("snapPerpendicular", tl!("Snap to Perpendicular"), app.session.prefs.snap_perpendicular), + ] { + if widgets::check(ui, label, on, true) { + crate::menus::invoke(app, "prefs.set", json!({"key": key, "value": !on})); } - ui.separator(); - for (key, label, on) in [ - ("alignmentGuides", tl!("Alignment Guides"), app.session.prefs.alignment_guides), - ("snapTangent", tl!("Snap to Tangent"), app.session.prefs.snap_tangent), - ("snapPerpendicular", tl!("Snap to Perpendicular"), app.session.prefs.snap_perpendicular), - ] { - if widgets::check(ui, label, on, true) { - crate::menus::invoke(app, "prefs.set", json!({"key": key, "value": !on})); - } - } - }); + } } /// The Control bar's isolation button. In isolation mode it is Exit Isolation Mode, except while a diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 57b1b2a457..376378a26f 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -104,12 +104,57 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - status_readouts(app, ui, &t); + status_readouts_and_snapping(app, ui, &t); }); }); widgets::set_menu_floor(ui.ctx(), panel.response.rect.top()); } +/// Reserve the right-side convenience controls before the optional readouts shrink. +fn status_readouts_and_snapping(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens) { + let gap = ui.spacing().item_spacing.x; + let menu_width = status_snapping_menu_width(ui); + let full_width = 3.0 * 18.0 + 3.0 * gap + menu_width; + let available = ui.available_width(); + let (width, direct) = if available >= MESSAGE_MIN + gap + full_width { + (full_width, true) + } else if available >= MESSAGE_MIN + gap + menu_width { + (menu_width, false) + } else { + (0.0, false) + }; + let readouts_width = (available - width - if width > 0.0 { gap } else { 0.0 }).max(0.0); + let (area, _) = ui.allocate_exact_size(vec2(readouts_width, ui.available_height()), Sense::hover()); + // Keep the readouts' child identity stable across all three collapse states. + let mut readouts = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::left_to_right(egui::Align::Center))); + status_readouts(app, &mut readouts, t); + if width == 0.0 { + return; + } + if direct { + status_snapping_buttons(app, ui); + } + ui.menu_button(tl!("Snapping"), |ui| super::control_bar::snapping_menu_contents(app, ui)); +} + +/// Measure the same localized label and padding the native menu button draws. +fn status_snapping_menu_width(ui: &Ui) -> f32 { + let label = egui::WidgetText::from(tl!("Snapping")).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Button); + label.size().x + 2.0 * ui.spacing().button_padding.x +} + +fn status_snapping_buttons(app: &mut VectorcraftApp, ui: &mut Ui) { + for (icon, label, command, on) in [ + ("sparkles", tl!("Smart Guides"), "view.smartGuides", app.ui.view.smart_guides), + ("dc-reference-point", tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point), + ("grid-3x3", tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid), + ] { + if widgets::icon_button(ui, icon, label, on, 18.0).clicked() { + crate::menus::invoke(app, command, json!({})); + } + } +} + /// The least width the status message keeps when the window is narrow. const MESSAGE_MIN: f32 = 180.0; diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 5a4d92ab6d..01a17e9555 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -798,7 +798,26 @@ fn narrow_status_bars_preserve_the_message_and_hide_optional_readouts() { let (mut app, ctx) = status_readout_app(); app.hover_doc = Some(vectorcraft_geom::Point::new(7.0, 5.0)); let mut origin = None; - for (width, coords, perf) in [(1400.0, true, true), (1000.0, true, false), (800.0, false, false)] { + // The optional snapping controls reserve room too. Measure the same three readout stages + // instead of fixing their thresholds to the former status-bar contents. + let mut widths = [None; 3]; + for width in (600..=1600).step_by(10).rev().map(|w| w as f32) { + let texts = status_readout_frame(&mut app, &ctx, width); + let coords = texts.iter().any(|t| t.text.starts_with("X:")); + let perf = texts.iter().any(|t| t.text.starts_with("render")); + let stage = match (coords, perf) { + (true, true) => 0, + (true, false) => 1, + (false, false) => 2, + _ => panic!("diagnostics cannot outlast coordinates: {width}: {texts:?}"), + }; + widths[stage].get_or_insert(width); + if widths.iter().all(Option::is_some) { + break; + } + } + let [wide, middle, narrow] = widths.map(|w| w.expect("all three optional-readout stages remain available")); + for (width, coords, perf) in [(wide, true, true), (middle, true, false), (narrow, false, false)] { let texts = status_readout_frame(&mut app, &ctx, width); let message = status_text(&texts, "Saved recovery data"); assert!(!message.elided, "{width}: message was truncated: {message:?}"); @@ -5014,3 +5033,218 @@ fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { let (_, [x0, _, x1, _]) = state(&app); assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]); } + +/// Real status-only frames reuse the existing chrome harness, including AccessKit and painted clips. +fn review_8687_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32) -> (Vec, Vec) { + bar_frame(app, ctx, width, None, vec![], super::status_bar); + bar_frame(app, ctx, width, None, vec![], super::status_bar) +} + +fn review_8687_node(nodes: &[egui::accesskit::Node], name: &str, role: egui::accesskit::Role) -> egui::accesskit::Node { + let matching: Vec<_> = nodes.iter().filter(|n| n.label() == Some(name) && n.role() == role).collect(); + assert_eq!(matching.len(), 1, "one visible {role:?} named {name}: {matching:?}"); + matching[0].clone() +} + +fn review_8687_click(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32, node: &egui::accesskit::Node) { + let b = node.bounds().expect("an actual visible control"); + assert!(b.x0 >= 0.0 && b.x1 <= width as f64 && b.y0 >= 0.0 && b.y1 <= 300.0); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + bar_frame(app, ctx, width, None, vec![egui::Event::PointerMoved(at), button(true)], super::status_bar); + bar_frame(app, ctx, width, None, vec![button(false)], super::status_bar); +} + +fn review_8687_dismiss(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32) { + for pressed in [true, false] { + let event = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + bar_frame(app, ctx, width, None, vec![event], super::status_bar); + } +} + +fn review_8687_direct_commands(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32) { + for (name, command) in [("Smart Guides", "view.smartGuides"), ("Snap to Point", "view.snapToPoint"), ("Snap to Grid", "view.snapToGrid")] { + let nodes = review_8687_frame(app, ctx, width).1; + let button = review_8687_node(&nodes, name, egui::accesskit::Role::Button); + assert_eq!(button.is_selected(), None, "off is an unselected Button, not a checkbox"); + assert_eq!(button.toggled(), None); + let before = app.run_count; + review_8687_click(app, ctx, width, &button); + assert_eq!(app.run_count, before + 1, "direct {name} uses the existing command entry"); + assert_eq!(crate::menus::checked(app, command, &json!({})), Some(true)); + let button = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::Button); + assert_eq!(button.is_selected(), Some(true)); + crate::menus::invoke(app, command, json!({})); + let button = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::Button); + assert_eq!(button.is_selected(), None, "an existing reverse command refreshes the live button"); + assert_eq!(crate::menus::checked(app, command, &json!({})), Some(false)); + } +} + +fn review_8687_dropdown_commands(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32) { + for (name, command) in [ + ("Smart Guides", "view.smartGuides"), + ("Snap to Point", "view.snapToPoint"), + ("Snap to Grid", "view.snapToGrid"), + ("Snap to Pixel", "view.snapToPixel"), + ("Snap to Glyph", "view.snapToGlyph"), + ] { + let menu = review_8687_node(&review_8687_frame(app, ctx, width).1, "Snapping", egui::accesskit::Role::Button); + review_8687_click(app, ctx, width, &menu); + let row = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::CheckBox); + assert_eq!(row.toggled(), Some(egui::accesskit::Toggled::False)); + let before = app.run_count; + review_8687_click(app, ctx, width, &row); + assert_eq!(app.run_count, before + 1, "menu {name} uses the existing command entry"); + assert_eq!(crate::menus::checked(app, command, &json!({})), Some(true)); + review_8687_dismiss(app, ctx, width); + crate::menus::invoke(app, command, json!({})); + let menu = review_8687_node(&review_8687_frame(app, ctx, width).1, "Snapping", egui::accesskit::Role::Button); + review_8687_click(app, ctx, width, &menu); + let row = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::CheckBox); + assert_eq!(row.toggled(), Some(egui::accesskit::Toggled::False), "menu rereads external command state"); + review_8687_dismiss(app, ctx, width); + } +} + +/// Direct buttons and the shared dropdown operate existing commands and reflect reverse changes. +#[test] +fn review_8687_status_snapping_uses_existing_commands_and_accessible_state() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.ui.view.snap_to_grid = false; + app.ui.view.snap_to_pixel = false; + app.ui.view.snap_to_glyph = false; + app.run("prefs.set", json!({"key": "alignmentGuides", "value": true})).unwrap(); + let document = json!(app.session.doc().unwrap().doc.as_ref()); + let selection = app.session.doc().unwrap().selection.clone(); + let history = (app.session.doc().unwrap().history.undo.len(), app.session.doc().unwrap().history.redo.len()); + let tool = app.session.tool_id().to_string(); + let camera = app.view().map(|v| (v.zoom, v.rotation)); + let width = 1600.0; + review_8687_direct_commands(&mut app, &ctx, width); + review_8687_dropdown_commands(&mut app, &ctx, width); + let menu = review_8687_node(&review_8687_frame(&mut app, &ctx, width).1, "Snapping", egui::accesskit::Role::Button); + review_8687_click(&mut app, &ctx, width, &menu); + let nodes = review_8687_frame(&mut app, &ctx, width).1; + for (name, on) in [ + ("Alignment Guides", app.session.prefs.alignment_guides), + ("Snap to Tangent", app.session.prefs.snap_tangent), + ("Snap to Perpendicular", app.session.prefs.snap_perpendicular), + ] { + let row = review_8687_node(&nodes, name, egui::accesskit::Role::CheckBox); + assert_eq!(row.toggled(), Some(if on { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False })); + } + let before = app.run_count; + review_8687_click(&mut app, &ctx, width, &review_8687_node(&nodes, "Alignment Guides", egui::accesskit::Role::CheckBox)); + assert_eq!(app.run_count, before + 1); + assert!(!app.session.prefs.alignment_guides); + review_8687_dismiss(&mut app, &ctx, width); + let menu = review_8687_node(&review_8687_frame(&mut app, &ctx, width).1, "Snapping", egui::accesskit::Role::Button); + review_8687_click(&mut app, &ctx, width, &menu); + let options = review_8687_node(&review_8687_frame(&mut app, &ctx, width).1, "Pixel Snapping Options…", egui::accesskit::Role::Button); + let pixel = app.session.prefs.pixel_snap; + review_8687_click(&mut app, &ctx, width, &options); + let dialog = app.ui.dialog.as_ref().expect("the existing Pixel Snapping Options dialog"); + assert_eq!(dialog.kind, crate::dialogs::pixel_snap_options::KIND); + assert_eq!(serde_json::Value::Object(dialog.fields.clone()), json!({"drawing": pixel.drawing, "moving": pixel.moving, "scaling": pixel.scaling})); + app.ui.dialog = None; + assert_eq!(app.session.prefs.pixel_snap, pixel, "closing options without OK changes no option"); + assert_eq!(json!(app.session.doc().unwrap().doc.as_ref()), document); + assert_eq!(app.session.doc().unwrap().selection, selection); + assert_eq!((app.session.doc().unwrap().history.undo.len(), app.session.doc().unwrap().history.redo.len()), history); + assert_eq!(app.session.tool_id(), tool); + assert_eq!(app.view().map(|v| (v.zoom, v.rotation)), camera); +} + +/// Width changes give up direct buttons, then the dropdown, while retaining core status content. +#[test] +fn review_8687_status_snapping_fits_full_menu_and_omitted_real_frames() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + app.hover_doc = Some(vectorcraft_geom::Point::new(7.0, 5.0)); + let mut stages = Vec::new(); + let mut origin = None; + let mut info_origin = None; + let zoom = crate::state::zoom_label(app.view().map(|v| v.zoom).unwrap_or(1.0), app.session.prefs.display_print_size); + for width in (400..=1600).step_by(10).rev().map(|w| w as f32) { + let (texts, nodes) = review_8687_frame(&mut app, &ctx, width); + let direct: Vec<_> = ["Smart Guides", "Snap to Point", "Snap to Grid"] + .into_iter() + .filter_map(|name| nodes.iter().find(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::Button)) + .collect(); + let menu = nodes.iter().find(|n| n.label() == Some("Snapping") && n.role() == egui::accesskit::Role::Button); + assert!(direct.is_empty() || direct.len() == 3, "the direct group remains whole at{width}"); + let stage = if !direct.is_empty() { + 2 + } else if menu.is_some() { + 1 + } else { + 0 + }; + assert!(stage != 2 || menu.is_some(), "full includes Snapping"); + if let Some(previous) = stages.last() { + assert!(stage <= *previous, "controls cannot return as the bar narrows"); + } + if stages.last() != Some(&stage) { + stages.push(stage); + } + let message = status_text(&texts, "Saved recovery data"); + let info = status_text(&texts, "Selection"); + assert!(message.clip.left() >= info.bounds.right(), "message stays after the info field at{width}"); + if let Some(at) = origin { + assert_eq!(message.at, at, "message origin stays fixed across stages"); + } else { + origin = Some(message.at); + } + if let Some(at) = info_origin { + assert_eq!(info.at, at, "snapping must not displace the selected info field"); + } else { + info_origin = Some(info.at); + } + review_8687_layout(&texts, &nodes, width, stage, &zoom); + if stage == 0 { + break; + } + } + assert_eq!(stages, [2, 1, 0], "actual frames reach full, dropdown-only, then omitted"); +} + +fn review_8687_layout(texts: &[StatusText], nodes: &[egui::accesskit::Node], width: f32, stage: u8, zoom: &str) { + let message = status_text(texts, "Saved recovery data"); + let info = status_text(texts, "Selection"); + let direct = ["Smart Guides", "Snap to Point", "Snap to Grid"] + .into_iter() + .filter_map(|name| nodes.iter().find(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::Button)); + let menu = nodes.iter().find(|n| n.label() == Some("Snapping") && n.role() == egui::accesskit::Role::Button); + for name in ["First Artboard", "Previous Artboard", "Next Artboard", "Last Artboard"] { + review_8687_node(nodes, name, egui::accesskit::Role::Button); + } + assert!(texts.iter().any(|t| t.text == zoom), "Zoom remains: {texts:?}"); + assert!(texts.iter().any(|t| t.text == "0°"), "Rotation remains: {texts:?}"); + let mut rects = Vec::new(); + for node in direct.chain(menu) { + let b = node.bounds().expect("a visible status control"); + let rect = egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)); + assert!(rect.left() >= info.bounds.right() && rect.right() <= width, "controls stay after navigation/info and in the window"); + assert!(!rect.intersects(message.clip), "controls leave the message its own rectangle"); + assert!(rects.iter().all(|old: &egui::Rect| !old.intersects(rect)), "controls do not overlap"); + rects.push(rect); + } + if stage > 0 { + // MESSAGE_MIN covers the message area, including the existing 18px idle-spinner slot. + // The painted text clip starts after that slot, so it alone is narrower than the area. + assert!( + message.clip.width() + 18.0 >= 180.0 - 0.01, + "admitted controls retain MESSAGE_MIN including the spinner reserve: {width}: {message:?}" + ); + } + for field in texts.iter().filter(|t| t.text.starts_with("X:") || t.text.starts_with("Y:") || t.text.starts_with("render")) { + assert!(field.clip.left() >= info.bounds.right()); + assert!(!field.clip.intersects(message.clip)); + assert!(rects.iter().all(|r| !r.intersects(field.clip))); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index c7192aebff..b6fcd7ca47 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Status bar snapping: compact Smart Guides, Snap to Point and Snap to Grid controls with the existing Snapping menu (#8687); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; 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) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -10,6 +10,8 @@ ## Feature submission evidence +**Status bar snapping controls (#8687):** The bottom-right status bar offers compact Smart Guides, Snap to Point and Snap to Grid buttons showing their current settings, plus the existing Snapping menu. All changes use the existing View commands and preferences; the existing menus remain available. Narrow windows retain the menu alone or omit the new group, preserving navigation, selected information and the existing minimum space for status messages; optional readouts may collapse earlier. Focused status-bar frame cases in `crates/ui-egui/src/chrome/tests.rs` accompany the source change; runtime validation is pending. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -962,6 +964,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Status bar: compact Smart Guides, Snap to Point and Snap to Grid controls plus the existing Snapping menu (#8687), with current settings shown and responsive collapse preserving navigation, selected information and status messages. Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 777563282a..9a0320e116 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-19 · **Change:** minor (M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Status bar snapping: compact Smart Guides, Snap to Point and Snap to Grid controls with the existing Snapping menu (#8687); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously 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) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -26,6 +26,8 @@ ## Feature submission evidence +**Status bar snapping controls (#8687):** The bottom-right status bar offers compact Smart Guides, Snap to Point and Snap to Grid buttons showing their current settings, plus the existing Snapping menu. All changes use the existing View commands and preferences; the existing menus remain available. Narrow windows retain the menu alone or omit the new group, preserving navigation, selected information and the existing minimum space for status messages; optional readouts may collapse earlier. Focused status-bar frame cases in `crates/ui-egui/src/chrome/tests.rs` accompany the source change; runtime validation is pending. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -191,7 +193,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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 (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), 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); Live Paint Bucket fills faces crossed in one drag (#6373) | 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 | -| 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; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); 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) and give the document language as the catalog's `/Lang` (#3644); 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); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| 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; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); 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) and give the document language as the catalog's `/Lang` (#3644); 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); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234); bottom status bar snapping controls and the existing Snapping menu (#8687), with responsive collapse preserving current navigation/info and message space; validation pending | 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 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -233,6 +235,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Status bar: compact Smart Guides, Snap to Point and Snap to Grid controls plus the existing Snapping menu (#8687), with current settings shown and responsive collapse preserving navigation, selected information and status messages. Scores and estimates unchanged. | | 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d7bf4daf7f..a4e398facf 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-19 · **Change:** minor (G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Status bar snapping: compact Smart Guides, Snap to Point and Snap to Grid controls with the existing Snapping menu (#8687); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -30,6 +30,8 @@ ## Feature submission evidence +**Status bar snapping controls (#8687):** The bottom-right status bar offers compact Smart Guides, Snap to Point and Snap to Grid buttons showing their current settings, plus the existing Snapping menu. All changes use the existing View commands and preferences; the existing menus remain available. Narrow windows retain the menu alone or omit the new group, preserving navigation, selected information and the existing minimum space for status messages; optional readouts may collapse earlier. Focused status-bar frame cases in `crates/ui-egui/src/chrome/tests.rs` accompany the source change; runtime validation is pending. Scores and estimates are unchanged. + `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. EPS embedded fonts, 2026-11-09 (#6023–#6067): the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). @@ -310,7 +312,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged; bottom status bar snapping controls reuse existing commands/options (#8687), with responsive collapse and focused frame coverage in `crates/ui-egui/src/chrome/tests.rs`; runtime validation pending; scores and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -3121,6 +3123,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Status bar: compact Smart Guides, Snap to Point and Snap to Grid controls plus the existing Snapping menu (#8687), with current settings shown and responsive collapse preserving navigation, selected information and status messages. Scores and estimates unchanged. | | 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b4c9bd6a59..471b4a2c3e 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-19 · **Change:** minor (Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Status bar snapping: compact Smart Guides, Snap to Point and Snap to Grid controls with the existing Snapping menu (#8687); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -20,6 +20,8 @@ ## Feature submission evidence +**Status bar snapping controls (#8687):** The bottom-right status bar offers compact Smart Guides, Snap to Point and Snap to Grid buttons showing their current settings, plus the existing Snapping menu. All changes use the existing View commands and preferences; the existing menus remain available. Narrow windows retain the menu alone or omit the new group, preserving navigation, selected information and the existing minimum space for status messages; optional readouts may collapse earlier. Focused status-bar frame cases in `crates/ui-egui/src/chrome/tests.rs` accompany the source change; runtime validation is pending. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-09 revision:** draft implementation and regression coverage for #5804; no parity rescore. @@ -290,6 +292,7 @@ tools, never checked side by side) isn't captured row by row. | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to them too; that is VectorCraft's choice. Character panel menu › Show Snap to Glyph Options: a Snap to Glyph checkbox (View › Snap to Glyph), then a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232); showing them scrolls the panel to them (#5273) | | Tangent and perpendicular snapping for line endpoints (new in 30.0) | done | #2530: tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Line Segment, Pen and Curvature tools, and for an existing line whose end anchor is dragged with Direct Selection (the only anchor selected, an open path's end on a straight segment; Shift keeps its angle step instead; Group Selection moves the path whole and does not snap so); mid-line anchors, curved segments' ends and curves as perpendicular targets are excluded, as the pages say. Saved Preferences › Smart Guides › Geometric Guides controls, on by default. [Perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) pages; test `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` | | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set, including Snap to Glyph and Alignment Guides (#6164); no View › Snapping submenu. Floating-panel parity remains unverified. | +| Bottom status bar snapping controls (#8687) | implemented | Compact Smart Guides, Snap to Point and Snap to Grid buttons show their current settings beside the existing Snapping menu. Existing View/Control-bar menus and commands are unchanged; narrow windows keep the dropdown alone or omit the group to preserve navigation/info and status messages. `crates/ui-egui/src/chrome/tests.rs`; runtime validation pending. | | 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 (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` | @@ -622,6 +625,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Status bar: compact Smart Guides, Snap to Point and Snap to Grid controls plus the existing Snapping menu (#8687), with current settings shown and responsive collapse preserving navigation, selected information and status messages. Scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-19 | minor | Canvas context menu: a right-click on a path, a group of paths or a compound path offers Simplify… between Average… and Smooth…, in the Path menu's order, opening the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings, as Object › Path › Simplify… does (#8344). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | From 86578b49fd64048f4bf7299e908bae3458f9f04e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 20:44:20 +0000 Subject: [PATCH 006/298] Tests: reverse status width ranges before stepping Keep the same descending sample widths without requiring ExactSizeIterator for an inclusive i32 range. Preserve every assertion and test. --- crates/ui-egui/src/chrome/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 01a17e9555..9d82972612 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -801,7 +801,7 @@ fn narrow_status_bars_preserve_the_message_and_hide_optional_readouts() { // The optional snapping controls reserve room too. Measure the same three readout stages // instead of fixing their thresholds to the former status-bar contents. let mut widths = [None; 3]; - for width in (600..=1600).step_by(10).rev().map(|w| w as f32) { + for width in (600..=1600).rev().step_by(10).map(|w| w as f32) { let texts = status_readout_frame(&mut app, &ctx, width); let coords = texts.iter().any(|t| t.text.starts_with("X:")); let perf = texts.iter().any(|t| t.text.starts_with("render")); @@ -5170,7 +5170,7 @@ fn review_8687_status_snapping_fits_full_menu_and_omitted_real_frames() { let mut origin = None; let mut info_origin = None; let zoom = crate::state::zoom_label(app.view().map(|v| v.zoom).unwrap_or(1.0), app.session.prefs.display_print_size); - for width in (400..=1600).step_by(10).rev().map(|w| w as f32) { + for width in (400..=1600).rev().step_by(10).map(|w| w as f32) { let (texts, nodes) = review_8687_frame(&mut app, &ctx, width); let direct: Vec<_> = ["Smart Guides", "Snap to Point", "Snap to Grid"] .into_iter() From 63278b5bacd1d9075e337e3db37a1f6ee36d8598 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 23:32:41 -0800 Subject: [PATCH 007/298] M3: Copy information-panel readouts on click (#8432) --- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + 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/gu.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 | 3 + 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 | 3 + 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/panels/doc_info.rs | 13 +- crates/ui-egui/src/panels/info.rs | 39 +-- crates/ui-egui/src/panels/links.rs | 28 +- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/labels.rs | 77 +++++ crates/ui-egui/tests/panel_readout_copy.rs | 365 +++++++++++++++++++++ docs/gaps.md | 6 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 10 +- docs/ui-parity.md | 9 +- 38 files changed, 592 insertions(+), 46 deletions(-) create mode 100644 crates/ui-egui/tests/panel_readout_copy.rs diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..2093575c54 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -8039,3 +8039,6 @@ breakText Glyphs Глифи # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Редактиране на оригинала с: file-filter Applications Приложения + +# #8432 information readout copy confirmation. + Copied to clipboard Копирано в клипборда diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..8925975e9c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -8094,3 +8094,6 @@ shape Open Otvoren # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Uredi original pomoću: file-filter Applications Aplikacije + +# #8432 information readout copy confirmation. + Copied to clipboard Kopirano u međuspremnik diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a6fdf89b21 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -9082,3 +9082,6 @@ breakText Glyphs Glifs # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Edita l’original amb: file-filter Applications Aplicacions + +# #8432 information readout copy confirmation. + Copied to clipboard Copiat al porta-retalls diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..0ad698983e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -10871,3 +10871,6 @@ breakText Glyphs Glyfy # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Upravit originál v: file-filter Applications Aplikace + +# #8432 information readout copy confirmation. + Copied to clipboard Zkopírováno do schránky diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..80e7c820f5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10967,3 +10967,6 @@ breakText Glyphs Glyffer # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Redigér original med: file-filter Applications Programmer + +# #8432 information readout copy confirmation. + Copied to clipboard Kopieret til udklipsholder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..bfef7cb649 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -10513,3 +10513,6 @@ breakText Glyphs Glyphen # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Original bearbeiten mit: file-filter Applications Anwendungen + +# #8432 information readout copy confirmation. + Copied to clipboard In die Zwischenablage kopiert diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..64e040535d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -9055,3 +9055,6 @@ breakText Glyphs Γλύφοι # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Επεξεργασία πρωτοτύπου με: file-filter Applications Εφαρμογές + +# #8432 information readout copy confirmation. + Copied to clipboard Αντιγράφηκε στο πρόχειρο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..f6c3dbf461 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -10799,3 +10799,6 @@ breakText Glyphs Glifos # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Editar original con: file-filter Applications Aplicaciones + +# #8432 information readout copy confirmation. + Copied to clipboard Copiado al portapapeles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..a697cbb338 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -9138,3 +9138,6 @@ breakText Glyphs Merkit # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Muokkaa alkuperäistä sovelluksella: file-filter Applications Sovellukset + +# #8432 information readout copy confirmation. + Copied to clipboard Kopioitu leikepöydälle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..35b3b4c36b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -10857,3 +10857,6 @@ breakText Glyphs Glyphes # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Modifier l’original avec : file-filter Applications Applications + +# #8432 information readout copy confirmation. + Copied to clipboard Copié dans le presse-papiers diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..1fe448b025 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5773,3 +5773,6 @@ swatch [Registration] [રજિસ્ટ્રેશન] Pulse Stroke ધબકતો ઘસારો Round Flow ગોળ પ્રવાહ Chisel Flow ત્રાંસો પ્રવાહ + +# #8432 information readout copy confirmation. + Copied to clipboard ક્લિપબોર્ડ પર કૉપિ કર્યું diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..57d6316ba2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10477,3 +10477,6 @@ theme Appearance अपीयरेंस # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: मूल फ़ाइल इसमें एडिट करें: file-filter Applications ऐप्स + +# #8432 information readout copy confirmation. + Copied to clipboard क्लिपबोर्ड पर कॉपी किया गया diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..0c980daaf2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -10860,3 +10860,6 @@ breakText Glyphs Glifák # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Eredeti szerkesztése ezzel: file-filter Applications Alkalmazások + +# #8432 information readout copy confirmation. + Copied to clipboard A vágólapra másolva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..2938e01f09 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -9091,3 +9091,6 @@ file-filter Applications Aplikasi @msg image {_1} cannot be distorted this way: its corners would not make a convex shape gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya tidak akan membentuk bangun cembung @msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya akan melewati cakrawala distorsi @msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya terlalu berdekatan untuk pemetaan perspektif + +# #8432 information readout copy confirmation. + Copied to clipboard Disalin ke papan klip diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..ee8940e816 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -10547,3 +10547,6 @@ breakText Glyphs Glifi # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Modifica originale con: file-filter Applications Applicazioni + +# #8432 information readout copy confirmation. + Copied to clipboard Copiato negli appunti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..0e7ceee360 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10610,3 +10610,6 @@ breakText Glyphs 字形 # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: 元のファイルを編集するアプリ: file-filter Applications アプリケーション + +# #8432 information readout copy confirmation. + Copied to clipboard クリップボードにコピーしました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..bc8672c8d1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -11190,3 +11190,6 @@ font-script Japanese იაპონური # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: ორიგინალის რედაქტირება პროგრამით: file-filter Applications აპლიკაციები + +# #8432 information readout copy confirmation. + Copied to clipboard დაკოპირდა ბუფერში diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..839135a888 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -10510,3 +10510,6 @@ breakText Glyphs 글리프 # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: 원본 편집 앱: file-filter Applications 응용 프로그램 + +# #8432 information readout copy confirmation. + Copied to clipboard 클립보드에 복사됨 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..bece69038a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10910,3 +10910,6 @@ breakText Glyphs Glyphs # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Origineel bewerken met: file-filter Applications Programma’s + +# #8432 information readout copy confirmation. + Copied to clipboard Gekopieerd naar klembord diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..d528ff7447 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -10736,3 +10736,6 @@ breakText Glyphs Glify # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Edytuj oryginał w: file-filter Applications Aplikacje + +# #8432 information readout copy confirmation. + Copied to clipboard Skopiowano do schowka diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..446394cbad 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10943,3 +10943,6 @@ swatch Yellow Green Verde-amarelado # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Editar original com: file-filter Applications Aplicativos + +# #8432 information readout copy confirmation. + Copied to clipboard Copiado para a área de transferência diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..3385197b51 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10960,3 +10960,6 @@ shape Open Открытый # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Редактировать оригинал в: file-filter Applications Приложения + +# #8432 information readout copy confirmation. + Copied to clipboard Скопировано в буфер обмена diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..b6c2c7c54b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10997,3 +10997,6 @@ digits Hindi Hindi # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Redigera original med: file-filter Applications Program + +# #8432 information readout copy confirmation. + Copied to clipboard Kopierat till urklipp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..93bab8aebd 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10829,3 +10829,6 @@ breakText Glyphs Glifler # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Orijinali şununla düzenle: file-filter Applications Uygulamalar + +# #8432 information readout copy confirmation. + Copied to clipboard Panoya kopyalandı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..18603393f3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -10523,3 +10523,6 @@ breakText Glyphs Гліфи # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Редагувати оригінал у: file-filter Applications Програми + +# #8432 information readout copy confirmation. + Copied to clipboard Скопійовано до буфера обміну diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..8758d3fef5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8755,3 +8755,6 @@ breakText Glyphs Glyph # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Chỉnh sửa bản gốc bằng: file-filter Applications Ứng dụng + +# #8432 information readout copy confirmation. + Copied to clipboard Đã sao chép vào bảng nhớ tạm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..0ac95d77b1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -10747,3 +10747,6 @@ breakText Glyphs 字形 # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: 编辑原稿所用应用: file-filter Applications 应用程序 + +# #8432 information readout copy confirmation. + Copied to clipboard 已复制到剪贴板 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..0306dfb20e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -10563,3 +10563,6 @@ breakText Glyphs 字符 # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: 編輯原稿所用應用程式: file-filter Applications 應用程式 + +# #8432 information readout copy confirmation. + Copied to clipboard 已複製到剪貼簿 diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index ed6bdcdaab..9fd2e0488c 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -21,13 +21,13 @@ struct Cache { /// A `label: value` row. `label` is shown as given: translate an interface label first, a name /// stays as it is. -pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { +pub(crate) fn row(ui: &mut Ui, session: &mut vectorcraft_engine::Session, label: &str, value: String) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(egui::RichText::new(label).size(12.0).color(t.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Long values (paths) are cut to the panel's width; hovering shows them whole. - ui.add(egui::Label::new(egui::RichText::new(value).size(12.0).color(t.text)).truncate()); + widgets::copyable_readout(ui, session, egui::RichText::new(&value).size(12.0).color(t.text), &value, true); }); }); } @@ -80,10 +80,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for (k, r) in rows.iter().enumerate() { let (label, value) = (r[0].as_str().unwrap_or_default(), r[1].as_str().unwrap_or_default()); if value.is_empty() { - widgets::dim_name(ui, super::label_or_name(label, !named.contains(&k))); + if named.contains(&k) && !label.is_empty() { + let t = Tokens::get(ui.ctx()); + widgets::copyable_readout(ui, &mut app.session, egui::RichText::new(label).color(t.text).size(12.5), label, false); + } else { + widgets::dim_name(ui, super::label_or_name(label, !named.contains(&k))); + } } else { let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); - row(ui, super::label_or_name(label, !named.contains(&k)), shown); + row(ui, &mut app.session, super::label_or_name(label, !named.contains(&k)), shown); } } } diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 753a4cc20b..9bbaa071b1 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -6,6 +6,7 @@ use egui::{Sense, Ui, vec2}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{NodeKind, Unit}; +use vectorcraft_engine::Session; use vectorcraft_geom::Point; use vectorcraft_tools::Readout; @@ -43,7 +44,7 @@ fn paint_name(p: &Paint) -> Option { /// One paint's row: its tile and values, and with `options` its name ([`paint_name`]). A paint the /// selected objects do not share (`mixed`) leaves the row empty. -fn paint_block(ui: &mut Ui, p: &Paint, mixed: bool, options: bool) { +fn paint_block(ui: &mut Ui, session: &mut Session, p: &Paint, mixed: bool, options: bool) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); @@ -54,17 +55,18 @@ fn paint_block(ui: &mut Ui, p: &Paint, mixed: bool, options: bool) { match p { Paint::Solid { color, .. } => { for (k, v) in color_values(color) { - ui.label(egui::RichText::new(format!("{k}: {v}")).monospace().color(t.text)); + let value = format!("{k}: {v}"); + widgets::copyable_readout(ui, session, egui::RichText::new(&value).monospace().color(t.text), &value, false); } } other => { let name = paint_name(other).filter(|_| options).unwrap_or_else(|| other.label()); - ui.label(egui::RichText::new(name).color(t.text_dim)); + widgets::copyable_readout(ui, session, egui::RichText::new(&name).color(t.text_dim), &name, false); } } }); if let (false, true, Paint::Solid { .. }, Some(name)) = (mixed, options, p, paint_name(p)) { - ui.label(egui::RichText::new(name).color(t.text_dim)); + widgets::copyable_readout(ui, session, egui::RichText::new(&name).color(t.text_dim), &name, false); } } @@ -166,39 +168,38 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { readout: readout.as_ref(), options, }); - let mono = |ui: &mut Ui, s: String| { - ui.label(egui::RichText::new(s).monospace().color(t.text)); + let mono = |ui: &mut Ui, session: &mut Session, s: String| { + widgets::copyable_readout(ui, session, egui::RichText::new(&s).monospace().color(t.text), &s, false); }; ui.columns(2, |cols| { for s in rows.left { - mono(&mut cols[0], s); + mono(&mut cols[0], &mut app.session, s); } for s in rows.right { - mono(&mut cols[1], s); + mono(&mut cols[1], &mut app.session, s); } }); if app.session.tool_id() == "zoom" { let zoom = app.view().map_or(1.0, |v| v.zoom); - mono(ui, format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); + let value = format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.session.prefs.display_print_size)); + mono(ui, &mut app.session, value); } if let Some(Readout::Brush { name: Some(name) }) = readout { - mono(ui, name); + mono(ui, &mut app.session, name); } widgets::divider(ui); let (f, s) = current_paints(app); let (fill_mixed, stroke_mixed) = mixed_paints(app, ui.ctx()); - paint_block(ui, &f, fill_mixed, options); - paint_block(ui, &s, stroke_mixed, options); + paint_block(ui, &mut app.session, &f, fill_mixed, options); + paint_block(ui, &mut app.session, &s, stroke_mixed, options); if let Some((font, size, tracking)) = shared_type(app) { widgets::divider(ui); - mono(ui, font); - mono( - ui, - crate::i18n::fmt( - tl!("Size: {size} Tracking: {tracking}"), - &[("size", &app.session.type_unit().format(size)), ("tracking", &format!("{tracking:.0}"))], - ), + mono(ui, &mut app.session, font); + let value = crate::i18n::fmt( + tl!("Size: {size} Tracking: {tracking}"), + &[("size", &app.session.type_unit().format(size)), ("tracking", &format!("{tracking:.0}"))], ); + mono(ui, &mut app.session, value); } } diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 4c491efb6b..38de2297a9 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -721,7 +721,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if o.info { let units = app.session.general_unit(); - link_info(ui, cache.info.as_ref().map(|(_, i)| i), units); + link_info(ui, &mut app.session, cache.info.as_ref().map(|(_, i)| i), units); } let sel = selected_rows(&cache.list, &selected); let modified = ids(&sel, |r| status_is(r, "modified") || r["preview"] == true && !status_is(r, "missing")); @@ -877,7 +877,7 @@ pub(crate) fn date_label(ms: u64) -> String { } /// The Link Info section: the details of `info` (`links.info`), or a hint. -fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { +fn link_info(ui: &mut Ui, session: &mut vectorcraft_engine::Session, info: Option<&Value>, units: vectorcraft_doc::Unit) { widgets::divider(ui); let Some(i) = info else { widgets::dim_label(ui, tl!("Select an image to see its Link Info.")); @@ -892,16 +892,16 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { } }; let row = super::doc_info::row; - row(ui, tl!("Name"), i["fileName"].as_str().or(i["name"].as_str()).unwrap_or_default().into()); - row(ui, tl!("Format"), i["format"].as_str().unwrap_or_default().into()); - row(ui, tl!("Color Space"), i["colorMode"].as_str().unwrap_or_default().into()); + row(ui, session, tl!("Name"), i["fileName"].as_str().or(i["name"].as_str()).unwrap_or_default().into()); + row(ui, session, tl!("Format"), i["format"].as_str().unwrap_or_default().into()); + row(ui, session, tl!("Color Space"), i["colorMode"].as_str().unwrap_or_default().into()); if let Some(l) = i["location"].as_str() { - row(ui, tl!("Location"), l.into()); + row(ui, session, tl!("Location"), l.into()); } // A placed document has no resolution: its rows are left out. for (label, k) in [(tl!("PPI"), "ppi"), (tl!("Effective PPI"), "effectivePpi")] { if i.get(k).is_some() { - row(ui, label, pair(k)); + row(ui, session, label, pair(k)); } } // Pixels, or a placed document's artboard size. @@ -910,22 +910,22 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { (None, Some(w), Some(h)) => format!("{} × {}", units.format(w), units.format(h)), _ => String::new(), }; - row(ui, tl!("Dimensions"), dims); + row(ui, session, tl!("Dimensions"), dims); let scale: Vec = i["scale"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); if let [x, y] = scale[..] { - row(ui, tl!("Scale"), format!("H: {x:.1}% V: {y:.1}%")); + row(ui, session, tl!("Scale"), format!("H: {x:.1}% V: {y:.1}%")); } - row(ui, tl!("Rotation"), format!("{:.1}°", i["rotation"].as_f64().unwrap_or(0.0))); + row(ui, session, tl!("Rotation"), format!("{:.1}°", i["rotation"].as_f64().unwrap_or(0.0))); if let Some(b) = i["fileSize"].as_u64() { - row(ui, tl!("Size"), size_label(b)); + row(ui, session, tl!("Size"), size_label(b)); } for (k, label) in [("created", tl!("Created")), ("modified", tl!("Modified"))] { if let Some(ms) = i[k].as_u64() { - row(ui, label, date_label(ms)); + row(ui, session, label, date_label(ms)); } } if let Some(p) = i["page"].as_u64() { - row(ui, tl!("Page"), p.to_string()); + row(ui, session, tl!("Page"), p.to_string()); } let status = match i["status"].as_str().unwrap_or_default() { "ok" => tl!("Linked"), @@ -933,7 +933,7 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { "modified" => tl!("Modified"), _ => tl!("Embedded"), }; - row(ui, tl!("Status"), status.into()); + row(ui, session, tl!("Status"), status.into()); } /// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b67df13c7f..4e543cb854 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -60,8 +60,8 @@ pub use dropdowns::{ }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; +pub(crate) use labels::{copyable_readout, dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; -pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index d7c0d9813d..865bbdc6ed 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -159,6 +159,83 @@ pub fn dim_name(ui: &mut Ui, text: &str) -> Response { ui.label(egui::RichText::new(text).color(t.text).size(12.5)) } +/// A single click waits for egui's double-click interval: copying immediately would also +/// copy the first click of a word-selection double-click. The record belongs to this label in +/// this viewport, and expires if the label is not rendered in the next pass or its value changes. +#[derive(Clone, Default)] +struct PendingReadoutCopy { + value: String, + deadline: f64, + pass: u64, +} + +/// A readonly panel value with native label selection and an accessible Copy click action. +/// Only a completed primary single-click copies the entire value, including elided text. +pub(crate) fn copyable_readout( + ui: &mut Ui, + session: &mut vectorcraft_engine::Session, + text: egui::RichText, + value: &str, + truncate: bool, +) -> Response { + let mut label = egui::Label::new(text).sense(Sense::click()); + if truncate { + label = label.truncate(); + } + let response = ui.add(label); + let ctx = ui.ctx(); + let id = response.id.with(("pending-readout-copy", ctx.viewport_id())); + let pass = ctx.cumulative_pass_nr(); + let mut pending = ctx.data_mut(|d| d.remove_temp::(id)); + let pressed = ctx.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); + let interrupted = ctx.input(|i| { + i.events.iter().any(|event| match event { + egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) | egui::Event::Ime(_) => { + true + } + egui::Event::AccessKitActionRequest(request) => request.action == egui::accesskit::Action::SetTextSelection, + _ => false, + }) + }); + let cancelled = pressed || response.dragged() || response.double_clicked() || response.triple_clicked() || interrupted; + let eligible = ui.is_enabled() && ui.is_rect_visible(response.rect) && !value.is_empty(); + let had_pending = pending.as_ref().is_some_and(|p| p.value == value && p.pass.saturating_add(1) >= pass); + pending = pending.filter(|p| eligible && p.value == value && p.pass.saturating_add(1) >= pass && !cancelled); + let accessible_click = eligible && ctx.input(|i| i.num_accesskit_action_requests(response.id, egui::accesskit::Action::Click) > 0); + if eligible { + ctx.accesskit_node_builder(response.id, |node| node.set_description(tl!("Copy"))); + } + let now = ctx.input(|i| i.time); + if eligible + && !interrupted + && !ctx.input(|i| i.modifiers.shift) + && !response.double_clicked() + && !response.triple_clicked() + && !(had_pending && pressed) + && response.clicked_by(egui::PointerButton::Primary) + { + pending = + Some(PendingReadoutCopy { value: value.to_string(), deadline: now + ctx.options(|o| o.input_options.max_double_click_delay), pass }); + } + let ready = pending.as_ref().is_some_and(|p| now >= p.deadline); + if accessible_click || ready { + copy_readout(ctx, session, value); + } else if let Some(mut pending) = pending { + pending.pass = pass; + if let Ok(delay) = std::time::Duration::try_from_secs_f64((pending.deadline - now).max(0.0)) { + ctx.request_repaint_after(delay); + ctx.data_mut(|d| d.insert_temp(id, pending)); + } + } + response +} + +fn copy_readout(ctx: &egui::Context, session: &mut vectorcraft_engine::Session, value: &str) { + use vectorcraft_engine::cmd::toast::{Level, Toast}; + ctx.copy_text(value.to_string()); + session.toast(Toast { seconds: 1.5, ..Toast::new(tl!("Copied to clipboard"), Level::Success) }); +} + /// A form row: `label` in a column `label_width` wide, then what `add` draws. pub fn label_row(ui: &mut Ui, label: &str, label_width: f32, add: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs new file mode 100644 index 0000000000..78fcecc1fd --- /dev/null +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -0,0 +1,365 @@ +//! Copy actual information-panel readouts without replacing them with artwork SVG. +//! These frames prove host clipboard intent; they do not access the OS clipboard. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::cell::Cell; +use std::io::Cursor; +use std::rc::Rc; +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Shape, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::cmd::clipboard::Flavour; +use vectorcraft_ui_egui::{Services, SystemClipboard, VectorcraftApp, background}; + +const COPIED: &str = "Copied to clipboard"; +const LENGTH: &str = "234 pt"; + +struct Board(Rc>); + +impl SystemClipboard for Board { + fn write(&mut self, _: &[Flavour]) -> Result<(), String> { + self.0.set(self.0.get() + 1); + Ok(()) + } + + fn holds_ours(&mut self) -> bool { + false + } + + fn read(&mut self, _: &[&'static str]) -> Option { + None + } + + fn has(&mut self, _: &[&'static str]) -> bool { + false + } +} + +struct App { + app: VectorcraftApp, + ctx: egui::Context, + time: f64, +} + +impl App { + fn new() -> Self { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 37, "height": 40})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut a = Self { app, ctx, time: 0.0 }; + a.settle(); + a + } + + fn frame_after(&mut self, seconds: f64, events: Vec) -> egui::FullOutput { + self.time += seconds; + let mut raw = egui::RawInput { + events, + time: Some(self.time), + focused: true, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), + ..Default::default() + }; + self.app.raw_input_hook(&self.ctx, &mut raw); + let mut out = self.ctx.run_ui(raw, |ui| { + self.app.logic(ui.ctx()); + self.app.ui(ui); + }); + out.textures_delta.clear(); + out + } + + fn frame(&mut self, events: Vec) -> egui::FullOutput { + self.frame_after(0.02, events) + } + + fn settle(&mut self) -> egui::FullOutput { + let mut out = self.frame(vec![]); + for _ in 0..3 { + out = self.frame(vec![]); + } + out + } + + fn delay(&self) -> f64 { + self.ctx.options(|o| o.input_options.max_double_click_delay) + } + + fn deadline(&mut self) -> egui::FullOutput { + self.frame_after(self.delay() + 0.05, vec![]) + } + + fn snapshot(&self) -> Value { + let st = self.app.session.active().unwrap(); + json!({"doc": st.doc, "selection": st.selection, "undo": st.history.undo.len(), "redo": st.history.redo.len()}) + } + + fn tap(&mut self, at: Pos2) -> egui::FullOutput { + self.frame(vec![Event::PointerMoved(at), button(at, true)]); + self.frame(vec![button(at, false)]) + } + + fn panel(&mut self, panel: &str) -> egui::FullOutput { + self.app.run("window.panel", json!({"panel": panel})).unwrap(); + self.settle() + } + + fn close_panel(&mut self, panel: &str) { + self.app.run("window.panel.close", json!({"panel": panel})).unwrap(); + self.settle(); + } + + fn document_category(&mut self, category: &str) -> egui::FullOutput { + let out = self.panel("docInfo"); + let title = painted(&out, "Document Info").0; + let update = out.platform_output.accesskit_update.as_ref().expect("actual panel accessibility"); + let at = update + .nodes + .iter() + .filter(|(_, n)| n.label() == Some("Panel menu")) + .filter_map(|(_, n)| n.bounds()) + .map(|b| Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .filter(|r| (r.center().y - title.center().y).abs() < 16.0 && r.center().x > title.center().x) + .min_by(|a, b| a.center().distance(title.center()).total_cmp(&b.center().distance(title.center()))) + .expect("the Document Info title's own Panel menu") + .center(); + let menu = self.tap(at); + let item = painted(&menu, category).0.center(); + self.tap(item); + self.settle() + } +} + +fn button(at: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +fn copies(out: &egui::FullOutput) -> Vec { + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(s) = c { Some(s.clone()) } else { None }).collect() +} + +fn text_shape<'a>(shape: &'a Shape, text: &str) -> Option<&'a egui::epaint::TextShape> { + match shape { + Shape::Text(t) if t.galley.text() == text => Some(t), + Shape::Vec(v) => v.iter().rev().find_map(|s| text_shape(s, text)), + _ => None, + } +} + +fn painted(out: &egui::FullOutput, text: &str) -> (Rect, bool) { + out.shapes + .iter() + .rev() + .find_map(|s| { + let t = text_shape(&s.shape, text)?; + let r = t.galley.rect.translate(t.pos.to_vec2()); + s.clip_rect.intersects(r).then_some((r.intersect(s.clip_rect), t.galley.elided)) + }) + .unwrap_or_else(|| panic!("fixture: no visible actual readout {text:?}")) +} + +fn visible_text_count(out: &egui::FullOutput, text: &str) -> usize { + fn count(shape: &Shape, clip: Rect, text: &str) -> usize { + match shape { + Shape::Text(t) if t.galley.text() == text => usize::from(t.galley.rect.translate(t.pos.to_vec2()).intersect(clip).is_positive()), + Shape::Vec(v) => v.iter().map(|s| count(s, clip, text)).sum(), + _ => 0, + } + } + out.shapes.iter().map(|s| count(&s.shape, s.clip_rect, text)).sum() +} + +fn copy_at(a: &mut App, at: Pos2, value: &str) -> egui::FullOutput { + let before = a.snapshot(); + let release = a.tap(at); + assert!(copies(&release).is_empty(), "the first release cannot yet exclude a double-click"); + let commit = a.deadline(); + let next = a.frame(vec![]); + let mut all = copies(&commit); + all.extend(copies(&next)); + assert_eq!(all, [value], "exactly one full value, never the art's SVG"); + assert_eq!(visible_text_count(&next, COPIED), 1, "one actual nonmodal confirmation is painted"); + assert_eq!(a.snapshot(), before, "readout copy leaves document, selection and history intact"); + assert!(copies(&a.frame(vec![])).is_empty(), "no copy on the next frame"); + next +} + +fn drag_text(a: &mut App, rect: Rect) { + let from = rect.left_center() + vec2(1.0, 0.0); + let to = rect.right_center() - vec2(1.0, 0.0); + assert!(copies(&a.frame(vec![Event::PointerMoved(from), button(from, true)])).is_empty()); + for k in 1..=4 { + assert!(copies(&a.frame(vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)])).is_empty()); + } + assert!(copies(&a.frame(vec![button(to, false)])).is_empty()); + assert!(copies(&a.deadline()).is_empty(), "drag selection never auto-copies"); +} + +#[test] +fn panel_readout_existing_label_keyboard_and_art_copy_remain_independent() { + let mut a = App::new(); + let out = a.document_category("Objects"); + let before = a.snapshot(); + drag_text(&mut a, painted(&out, LENGTH).0); + for event in [Event::Copy, Event::Cut] { + let out = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND), event]); + assert_eq!(copies(&out), [LENGTH], "the existing label selection owns Copy and Cut"); + assert!(copies(&a.frame(vec![Event::ModifiersChanged(Modifiers::NONE)])).is_empty()); + assert!(a.app.session.clipboard.is_empty(), "the art was not copied or cut"); + assert_eq!(a.snapshot(), before); + } + a.close_panel("docInfo"); + let first = a.frame(vec![Event::Copy]); + let next = a.frame(vec![]); + let mut copied = copies(&first); + copied.extend(copies(&next)); + assert_eq!(copied.len(), 1, "ordinary art Copy still runs when no label consumes it"); + assert!(copied[0].contains(" (Rc>, mpsc::Sender<()>) { + let writes = Rc::new(Cell::new(0)); + a.app.services.system_clipboard = Some(Box::new(Board(writes.clone()))); + a.app.services.write_shared = Some(Arc::new(|_: &str, _: &[u8]| Err("no fixture file writes".into()))); + let (hold, held) = mpsc::channel(); + background::run( + &mut a.app, + true, + String::new(), + None, + move |_| { + let _ = held.recv_timeout(Duration::from_secs(10)); + Ok(Value::Null) + }, + |_, r| r, + ) + .unwrap(); + a.app.run("edit.copy", json!({})).unwrap(); + assert!(!a.app.session.clipboard.is_empty(), "ordinary art Copy really queued its formats"); + assert_eq!(writes.get(), 0, "the existing worker holds those formats"); + (writes, hold) +} + +#[test] +fn panel_readout_document_value_copies_once_with_feedback_and_cancels_pending_art() { + let mut a = App::new(); + let out = a.document_category("Objects"); + let (writes, hold) = hold_art_formats(&mut a); + let before = a.snapshot(); + copy_at(&mut a, painted(&out, LENGTH).0.center(), LENGTH); + drop(hold); + background::wait_all(&mut a.app); + assert_eq!(writes.get(), 0, "unwritten art formats cannot replace the new readout text"); + assert_eq!(a.snapshot(), before); + let next = a.frame(vec![]); + assert_eq!(visible_text_count(&next, COPIED), 1, "no duplicate confirmation was queued"); + assert!(copies(&next).is_empty()); +} + +fn dismiss_feedback(a: &mut App, out: &egui::FullOutput) { + a.tap(painted(out, COPIED).0.center()); + assert_eq!(visible_text_count(&a.frame(vec![]), COPIED), 0, "the previous confirmation cannot satisfy the next readout's oracle"); +} + +fn copy_graphic_style_name(a: &mut App) { + let name = "Original information-panel style"; + a.app.run("graphicStyle.new", json!({"name": name})).unwrap(); + let out = a.document_category("Graphic Styles"); + let copied = copy_at(a, painted(&out, name).0.center(), name); + dismiss_feedback(a, &copied); + a.close_panel("docInfo"); +} + +fn place_original_png(a: &mut App, name: &str) { + let pixels = image::RgbaImage::from_pixel(8, 8, image::Rgba([17, 54, 128, 255])); + let mut bytes = Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(pixels).write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + a.app.run("file.place", json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes.get_ref()), "link": false})).unwrap(); +} + +fn copy_long_link_value(a: &mut App) { + let name = format!("{}.png", "Original linked-information fixture ".repeat(6)); + place_original_png(a, &name); + let out = a.panel("links"); + let label = painted(&out, "Name").0; + let (value, elided) = out + .shapes + .iter() + .find_map(|s| { + let t = text_shape(&s.shape, &name)?; + let r = t.galley.rect.translate(t.pos.to_vec2()).intersect(s.clip_rect); + (r.is_positive() && (r.center().y - label.center().y).abs() < 8.0).then_some((r, t.galley.elided)) + }) + .expect("the actual selected image's Link Info Name value"); + assert!(elided, "this fixture really truncates the painted readout"); + copy_at(a, value.center(), &name); +} + +#[test] +fn panel_readout_info_names_and_truncated_link_metadata_copy_full_displayed_text() { + let mut a = App::new(); + let out = a.panel("info"); + let width = "W: 37 pt"; + let copied = copy_at(&mut a, painted(&out, width).0.center(), width); + dismiss_feedback(&mut a, &copied); + a.close_panel("info"); + copy_graphic_style_name(&mut a); + copy_long_link_value(&mut a); +} + +fn assert_no_delayed_copy(a: &mut App) { + assert!(copies(&a.deadline()).is_empty()); + assert!(copies(&a.frame(vec![])).is_empty()); +} + +fn cancelled_gesture(kind: &str) { + let mut a = App::new(); + let out = a.document_category("Objects"); + let at = painted(&out, LENGTH).0.center(); + let before = a.snapshot(); + match kind { + "outside" => { + a.frame(vec![Event::PointerMoved(at), button(at, true)]); + let up = a.frame(vec![button(at + vec2(-80.0, 0.0), false)]); + assert!(copies(&up).is_empty(), "release outside does not accept the value"); + } + "double" => { + assert!(copies(&a.tap(at)).is_empty()); + let second = a.frame_after(a.delay() * 0.25, vec![button(at, true)]); + assert!(copies(&second).is_empty()); + assert!(copies(&a.frame(vec![button(at, false)])).is_empty()); + } + "hidden" => { + assert!(copies(&a.tap(at)).is_empty()); + a.close_panel("docInfo"); + assert_no_delayed_copy(&mut a); + a.panel("docInfo"); + } + "changed" => { + assert!(copies(&a.tap(at)).is_empty()); + a.app.run("shape.rectangle", json!({"x": 70, "y": 70, "width": 1, "height": 1})).unwrap(); + let changed = a.frame(vec![]); + painted(&changed, "238 pt"); + } + _ => panic!("unknown fixture"), + } + assert_no_delayed_copy(&mut a); + if kind != "changed" { + assert_eq!(a.snapshot(), before, "cancelled gestures do not edit the document or selection"); + } +} + +#[test] +fn panel_readout_double_click_release_outside_and_stale_values_do_not_auto_copy() { + for kind in ["outside", "double", "hidden", "changed"] { + cancelled_gesture(kind); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index df988ebe81..bb9cb14f8b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Information readouts copy their complete values on click with confirmation (#8432); scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; 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) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -361,6 +361,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools +- **Narrowed (#8432, information readouts):** Document Info values and names, Info readouts and Links metadata copy their complete displayed text on a simple click, including the full value when a path is truncated, and show a short confirmation (#8432). Info includes the readout label and units. Dragging or double-clicking still selects text; the existing selected-label keyboard Copy/Cut routing from #8512 remains in place. The already merged keyboard-copy repair and the remaining menu-specific limitations are separate; estimates unchanged. + + - **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. - **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. @@ -965,6 +968,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Information readouts: click-to-copy for Document Info values and names, Info readouts and shared Links metadata, with short confirmation (#8432, remaining feature request). Existing selected-label keyboard Copy/Cut routing from #8512 is retained; scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index a518e3a35a..4e9a4bb0d3 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-20 · **Change:** minor (M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Information readouts copy their complete values on click with confirmation (#8432); scores and estimates unchanged; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously 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) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -178,7 +178,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | Information readouts copy complete values on click with short confirmation (#8432; estimates unchanged); ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #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); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 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 copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); 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; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; 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; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | @@ -235,6 +235,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Information readouts: click-to-copy for Document Info values and names, Info readouts and shared Links metadata, with short confirmation (#8432, remaining feature request). Existing selected-label keyboard Copy/Cut routing from #8512 is retained; scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..4d497d3bc4 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-20 · **Change:** minor (Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Information readouts copy their complete values on click with confirmation (#8432); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -313,7 +313,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged Click-to-copy for information readouts, with confirmation (#8432; no rescore). | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -573,8 +573,8 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | -| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | -| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | +| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 Click-to-copy for information readouts, with confirmation (#8432; no rescore). | +| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 Click-to-copy for information readouts, with confirmation (#8432; no rescore). | | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | @@ -1321,6 +1321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - With text selected in a panel's label, such as a Document Info value, Cmd/Ctrl+C and Cmd/Ctrl+X copy that text and do not copy or cut the art, and so do F3 and F2 where they are Copy and Cut, any other keys assigned to Copy or Cut, and the menu bar's Copy and Cut on macOS. When the selected label is not drawn (the panels are hidden), Copy and Cut act on the art instead (#8432; VectorCraft's own behavior; `selectall::copy_and_cut_copy_the_text_selected_in_a_panel_label`, `selectall::copy_sent_on_from_another_window_copies_the_text_only_when_it_is_this_windows`, `selectall::panel_text_copied_before_the_art_formats_are_written_stays_on_the_clipboard`, `shortcuts::tests::a_window_notes_only_its_labels_copies_until_the_next_main_window_pass`, `shortcuts::tests::a_window_notes_a_copy_of_text_dragged_across_its_label`). Not yet: the in-window Edit menu's Copy and Cut (the click on the menu clears the label's selection first), and, while the selected text is in a floating panel's own window, the menu bar's Copy and Cut, and F3 and F2 (they do not copy the text). + - **Information readout click-to-copy (#8432):** Document Info values and names, Info readouts and Links metadata copy their complete displayed text on a simple click, including the full value when a path is truncated, and show a short confirmation (#8432). Info includes the readout label and units. Dragging or double-clicking still selects text; the existing selected-label keyboard Copy/Cut routing from #8512 remains in place. This is an additional convenience, not a change to the existing menu-copy limitations. Scores and estimates unchanged. - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, locked and hidden frames included, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames`, `textedit::remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames`). - When only some frames of a threaded story are selected, Remove Line Breaks and Remove Paragraph Breaks go through that story's frames once for all of them, not once per selected frame; each selected frame still loses its own breaks, in the order selected, as one undo step (`addons::cleanup::text::tests::remove_breaks_goes_through_a_partly_named_story_once`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`, `panels::tabs::tests::indent_markers_after_select_all_keep_each_story_paragraphs_indents`, `dialogs::justification::tests::justification_dialog_follows_the_story_thread_at_ok`). @@ -3144,6 +3145,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Information readouts: click-to-copy for Document Info values and names, Info readouts and shared Links metadata, with short confirmation (#8432, remaining feature request). Existing selected-label keyboard Copy/Cut routing from #8512 is retained; scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..affa3d904c 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-20 · **Change:** minor (Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Information readouts copy their complete values on click with confirmation (#8432); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -622,10 +622,17 @@ Dragging from a face fills the visible faces crossed in that Live Paint group, e narrow face lies between pointer events. Undo restores the whole drag, and Escape cancels it before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). +## Information readout click-to-copy + +Document Info values and names, Info readouts and Links metadata copy their complete displayed text on a simple click, including the full value when a path is truncated, and show a short confirmation (#8432). Info includes the readout label and units. Dragging or double-clicking still selects text; the existing selected-label keyboard Copy/Cut routing from #8512 remains in place. + +This covers these information readouts; editable fields, arbitrary panel labels and the existing menu-specific Copy/Cut limitations keep their current behavior. Scores and estimates unchanged. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Information readouts: click-to-copy for Document Info values and names, Info readouts and shared Links metadata, with short confirmation (#8432, remaining feature request). Existing selected-label keyboard Copy/Cut routing from #8512 is retained; scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | | 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | From b41e9aad5890b3a001c566ab44533d16c175ac59 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 23:45:14 -0800 Subject: [PATCH 008/298] M3: Wait for information panel menu sizing in click-copy tests --- crates/ui-egui/tests/panel_readout_copy.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index 78fcecc1fd..fb9fe7e0bc 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -129,7 +129,10 @@ impl App { .min_by(|a, b| a.center().distance(title.center()).total_cmp(&b.center().distance(title.center()))) .expect("the Document Info title's own Panel menu") .center(); - let menu = self.tap(at); + self.tap(at); + // A newly opened egui popup first measures an invisible sizing pass. Read its painted + // category only after normal subsequent layout frames, as the user sees it. + let menu = self.settle(); let item = painted(&menu, category).0.center(); self.tap(item); self.settle() From 705bb1d643686b2d2e3d0fe4dd948e70b69dd527 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 00:01:11 -0800 Subject: [PATCH 009/298] M3: Locate the actual decorated category menu items in readout tests --- crates/ui-egui/tests/panel_readout_copy.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index fb9fe7e0bc..aaf4e5e100 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -133,7 +133,14 @@ impl App { // A newly opened egui popup first measures an invisible sizing pass. Read its painted // category only after normal subsequent layout frames, as the user sees it. let menu = self.settle(); - let item = painted(&menu, category).0.center(); + // menu_item_name paints the check column in the same galley as the label. + // Match that real menu text without trimming any copied readout or user data. + let item = [" ", "✓ "] + .into_iter() + .map(|prefix| format!("{prefix}{category}")) + .find(|text| visible_text_count(&menu, text) > 0) + .map(|text| painted(&menu, &text).0.center()) + .unwrap_or_else(|| panic!("fixture: no painted category menu item {category:?}")); self.tap(item); self.settle() } From 28fa8cf7f49e1f67b9d3b91e0bb2fc4e0ee25edb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 00:21:28 -0800 Subject: [PATCH 010/298] M3: Model pointer movement in readout cancellation checks --- crates/ui-egui/tests/panel_readout_copy.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index aaf4e5e100..72389a5172 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -325,9 +325,10 @@ fn panel_readout_info_names_and_truncated_link_metadata_copy_full_displayed_text copy_long_link_value(&mut a); } -fn assert_no_delayed_copy(a: &mut App) { - assert!(copies(&a.deadline()).is_empty()); - assert!(copies(&a.frame(vec![])).is_empty()); +fn assert_no_delayed_copy(a: &mut App, kind: &str) { + let copied = copies(&a.deadline()); + assert!(copied.is_empty(), "{kind}: unexpected delayed copy {copied:?}"); + assert!(copies(&a.frame(vec![])).is_empty(), "{kind}: no later duplicate copy"); } fn cancelled_gesture(kind: &str) { @@ -338,7 +339,10 @@ fn cancelled_gesture(kind: &str) { match kind { "outside" => { a.frame(vec![Event::PointerMoved(at), button(at, true)]); - let up = a.frame(vec![button(at + vec2(-80.0, 0.0), false)]); + let outside = at + vec2(-80.0, 0.0); + // A real release outside includes the pointer motion that egui uses to distinguish + // dragging from a click; a button's release position alone does not record movement. + let up = a.frame(vec![Event::PointerMoved(outside), button(outside, false)]); assert!(copies(&up).is_empty(), "release outside does not accept the value"); } "double" => { @@ -350,7 +354,7 @@ fn cancelled_gesture(kind: &str) { "hidden" => { assert!(copies(&a.tap(at)).is_empty()); a.close_panel("docInfo"); - assert_no_delayed_copy(&mut a); + assert_no_delayed_copy(&mut a, kind); a.panel("docInfo"); } "changed" => { @@ -361,7 +365,7 @@ fn cancelled_gesture(kind: &str) { } _ => panic!("unknown fixture"), } - assert_no_delayed_copy(&mut a); + assert_no_delayed_copy(&mut a, kind); if kind != "changed" { assert_eq!(a.snapshot(), before, "cancelled gestures do not edit the document or selection"); } From 0e203bd8191a05d6b25613b6216bdf44a00ae354 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 02:14:29 -0800 Subject: [PATCH 011/298] M3: Cancel delayed readout copies when other input takes over --- crates/ui-egui/src/widgets/labels.rs | 15 ++-- crates/ui-egui/tests/panel_readout_copy.rs | 90 ++++++++++++++++++++++ 2 files changed, 100 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 865bbdc6ed..f8300792ca 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -187,13 +187,18 @@ pub(crate) fn copyable_readout( let id = response.id.with(("pending-readout-copy", ctx.viewport_id())); let pass = ctx.cumulative_pass_nr(); let mut pending = ctx.data_mut(|d| d.remove_temp::(id)); - let pressed = ctx.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); + // A new pointer or assistive action must not be overwritten by an older delayed copy. + // This label's own accessible Click is still handled immediately below. + let pressed = ctx.input(|i| i.pointer.any_pressed()); let interrupted = ctx.input(|i| { i.events.iter().any(|event| match event { - egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) | egui::Event::Ime(_) => { - true - } - egui::Event::AccessKitActionRequest(request) => request.action == egui::accesskit::Action::SetTextSelection, + egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Paste(_) + | egui::Event::Ime(_) + | egui::Event::AccessKitActionRequest(_) => true, _ => false, }) }); diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index 72389a5172..fc29529f93 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -376,4 +376,94 @@ fn panel_readout_double_click_release_outside_and_stale_values_do_not_auto_copy( for kind in ["outside", "double", "hidden", "changed"] { cancelled_gesture(kind); } + review_8826_motion_keeps_pending_copy(); + for button in [PointerButton::Secondary, PointerButton::Middle] { + review_8826_pointer_takeover(button); + } + review_8826_accesskit_takeover(true); + review_8826_accesskit_takeover(false); +} + +fn review_8826_motion_keeps_pending_copy() { + let mut a = App::new(); + let out = a.panel("info"); + let rect = painted(&out, "W: 37 pt").0; + let before = a.snapshot(); + assert!(copies(&a.tap(rect.center())).is_empty()); + let at = rect.center() + vec2(1.0, 0.0); + assert!(rect.contains(at), "ordinary motion stays over the same real readout"); + let moved = a.frame(vec![Event::PointerMoved(at)]); + painted(&moved, "W: 37 pt"); + assert!(copies(&moved).is_empty()); + assert_eq!(copies(&a.deadline()), ["W: 37 pt"], "motion alone does not cancel an ordinary primary copy"); + let next = a.frame(vec![]); + assert!(copies(&next).is_empty()); + assert_eq!(visible_text_count(&next, COPIED), 1); + assert_eq!(a.snapshot(), before); +} + +fn review_8826_pointer_takeover(button: PointerButton) { + let mut a = App::new(); + let out = a.panel("info"); + let at = painted(&out, "W: 37 pt").0.center(); + let before = a.snapshot(); + let release = a.tap(at); + assert!(copies(&release).is_empty()); + painted(&release, "W: 37 pt"); + let press = a.frame_after(a.delay() * 0.25, vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: Modifiers::NONE }]); + assert!(copies(&press).is_empty(), "{button:?} press must not copy"); + painted(&press, "W: 37 pt"); + let release = a.frame(vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: Modifiers::NONE }]); + assert!(copies(&release).is_empty(), "{button:?} release must not schedule a copy"); + painted(&release, "W: 37 pt"); + assert_no_delayed_copy(&mut a, &format!("{button:?} takeover")); + let still_shown = a.frame(vec![]); + painted(&still_shown, "W: 37 pt"); + assert_eq!(visible_text_count(&still_shown, COPIED), 0, "cancelled pending copy has no confirmation"); + assert_eq!(a.snapshot(), before, "{button:?} takeover leaves document, selection and history intact"); +} + +fn review_8826_readout_node(out: &egui::FullOutput, value: &str) -> egui::accesskit::NodeId { + let rect = painted(out, value).0; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("actual readout accessibility tree").nodes; + let matches: Vec<_> = nodes + .iter() + .filter(|(_, n)| n.label() == Some(value) || n.value() == Some(value)) + .filter(|(_, n)| n.supports_action(egui::accesskit::Action::Click)) + .filter(|(_, n)| { + n.bounds() + .is_some_and(|b| Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)).intersects(rect)) + }) + .collect(); + assert_eq!(matches.len(), 1, "one live clickable node for the painted {value:?}"); + let (id, node) = matches[0]; + assert_eq!(node.description(), Some("Copy"), "the actual readout advertises its copy action"); + *id +} + +fn review_8826_accesskit_takeover(same_target: bool) { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let mut a = App::new(); + let out = a.panel("info"); + let width = review_8826_readout_node(&out, "W: 37 pt"); + let height = review_8826_readout_node(&out, "H: 40 pt"); + assert_ne!(width, height, "the live W and H rows have distinct semantic targets"); + let before = a.snapshot(); + let release = a.tap(painted(&out, "W: 37 pt").0.center()); + assert!(copies(&release).is_empty()); + painted(&release, "W: 37 pt"); + painted(&release, "H: 40 pt"); + let (target_node, expected) = if same_target { (width, "W: 37 pt") } else { (height, "H: 40 pt") }; + let activated = a.frame_after( + a.delay() * 0.25, + vec![Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node, target_tree: TreeId::ROOT, data: None })], + ); + assert_eq!(copies(&activated), [expected], "the actual AccessKit target copies once immediately"); + painted(&activated, "W: 37 pt"); + painted(&activated, "H: 40 pt"); + assert_no_delayed_copy(&mut a, if same_target { "same-target accessible click" } else { "different-readout accessible click" }); + let still_shown = a.frame(vec![]); + painted(&still_shown, "W: 37 pt"); + painted(&still_shown, "H: 40 pt"); + assert_eq!(a.snapshot(), before, "accessible copy leaves document, selection and history intact"); } From 84627feff167a6dae4b33af35316b66adec7ace0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 02:33:58 -0800 Subject: [PATCH 012/298] M3: Use matches for readout input interruption checks --- crates/ui-egui/src/widgets/labels.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index f8300792ca..bb09646009 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -191,15 +191,17 @@ pub(crate) fn copyable_readout( // This label's own accessible Click is still handled immediately below. let pressed = ctx.input(|i| i.pointer.any_pressed()); let interrupted = ctx.input(|i| { - i.events.iter().any(|event| match event { - egui::Event::Key { .. } - | egui::Event::Text(_) - | egui::Event::Copy - | egui::Event::Cut - | egui::Event::Paste(_) - | egui::Event::Ime(_) - | egui::Event::AccessKitActionRequest(_) => true, - _ => false, + i.events.iter().any(|event| { + matches!( + event, + egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Paste(_) + | egui::Event::Ime(_) + | egui::Event::AccessKitActionRequest(_) + ) }) }); let cancelled = pressed || response.dragged() || response.double_clicked() || response.triple_clicked() || interrupted; From 1232209b3b5a0cdcfb27fcc582100b98db96c217 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 06:53:32 -0800 Subject: [PATCH 013/298] #8687: identify artboard navigator controls by their actual labels --- crates/ui-egui/src/chrome/tests.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 9c014c385a..1b10beae7c 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1449,12 +1449,20 @@ fn a_middle_click_on_a_tab_closes_it_as_the_close_box_does() { /// One headless frame of the status bar; returns the artboard navigator's buttons, left to /// right: first, previous, next, last. fn navigator(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + ctx.enable_accesskit(); let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 300.0)); let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::status_bar(app, ui)); out.textures_delta.clear(); - let size = egui::vec2(18.0, 18.0); - let mut r: Vec = - ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == size).map(|w| w.rect).collect()); + let names = [tl!("First Artboard"), tl!("Previous Artboard"), tl!("Next Artboard"), tl!("Last Artboard")]; + let mut r: Vec = out + .platform_output + .accesskit_update + .into_iter() + .flat_map(|update| update.nodes) + .filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label().is_some_and(|name| names.contains(&name))) + .filter_map(|(_, node)| node.bounds()) + .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .collect(); r.sort_by(|a, b| a.left().total_cmp(&b.left())); r } From ff1fd9108c816f76244a5c23002572019564bc94 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 08:13:24 -0800 Subject: [PATCH 014/298] #8687: assert the actual AccessKit pressed state in snapping tests --- crates/ui-egui/src/chrome/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 1b10beae7c..27fc575679 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -5087,10 +5087,12 @@ fn review_8687_direct_commands(app: &mut crate::VectorcraftApp, ctx: &egui::Cont assert_eq!(app.run_count, before + 1, "direct {name} uses the existing command entry"); assert_eq!(crate::menus::checked(app, command, &json!({})), Some(true)); let button = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::Button); - assert_eq!(button.is_selected(), Some(true)); + assert_eq!(button.is_selected(), None); + assert_eq!(button.toggled(), Some(egui::accesskit::Toggled::True)); crate::menus::invoke(app, command, json!({})); let button = review_8687_node(&review_8687_frame(app, ctx, width).1, name, egui::accesskit::Role::Button); assert_eq!(button.is_selected(), None, "an existing reverse command refreshes the live button"); + assert_eq!(button.toggled(), None); assert_eq!(crate::menus::checked(app, command, &json!({})), Some(false)); } } From dfaf4bedb8666204d10b4c04203753269ec07137 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:03:06 -0800 Subject: [PATCH 015/298] Private #8779 focused failure diagnostics; preserve all assertions --- crates/ui-egui/src/chrome/tests.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 27fc575679..2b4e943910 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -5062,7 +5062,16 @@ fn review_8687_node(nodes: &[egui::accesskit::Node], name: &str, role: egui::acc fn review_8687_click(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32, node: &egui::accesskit::Node) { let b = node.bounds().expect("an actual visible control"); - assert!(b.x0 >= 0.0 && b.x1 <= width as f64 && b.y0 >= 0.0 && b.y1 <= 300.0); + assert!( + b.x0 >= 0.0 && b.x1 <= width as f64 && b.y0 >= 0.0 && b.y1 <= 300.0, + "target {:?} {:?}: bounds ({}, {}, {}, {}) outside viewport ({width}, 300)", + node.role(), + node.label(), + b.x0, + b.y0, + b.x1, + b.y1 + ); let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; bar_frame(app, ctx, width, None, vec![egui::Event::PointerMoved(at), button(true)], super::status_bar); From daacafe5c2b9b26d349ed9bc6679c048c496867d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:33:11 -0800 Subject: [PATCH 016/298] #8687: fit the closed Snapping menu inside the status row --- crates/ui-egui/src/chrome/status_bar.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 8fc5523398..b3393186c3 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -134,7 +134,11 @@ fn status_readouts_and_snapping(app: &mut VectorcraftApp, ui: &mut Ui, t: &Token if direct { status_snapping_buttons(app, ui); } - ui.menu_button(tl!("Snapping"), |ui| super::control_bar::snapping_menu_contents(app, ui)); + let height = ui.spacing().interact_size.y.min(ui.available_height()); + ui.scope(|ui| { + ui.spacing_mut().interact_size.y = height; + ui.menu_button(tl!("Snapping"), |ui| super::control_bar::snapping_menu_contents(app, ui)); + }); } /// Measure the same localized label and padding the native menu button draws. From d241e34c15e7c2be6f37b9df787222229a4e97a9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 10:04:31 -0800 Subject: [PATCH 017/298] #8687: bound Snapping to the panel row before other controls expand it --- crates/ui-egui/src/chrome/status_bar.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index b3393186c3..da85c3ac20 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -8,6 +8,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .exact_size(24.0) .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 0)).stroke(Stroke::new(1.0, t.border))) .show(ui, |ui| { + // Keep the menu inside the panel even when earlier controls expand the row. + let row_rect = ui.available_rect_before_wrap(); ui.horizontal_centered(|ui| { let zoom = app.view().map(|v| v.zoom).unwrap_or(1.0); let print = app.session.prefs.display_print_size; @@ -104,14 +106,14 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - status_readouts_and_snapping(app, ui, &t); + status_readouts_and_snapping(app, ui, &t, row_rect); }); }); widgets::set_menu_floor(ui.ctx(), panel.response.rect.top()); } /// Reserve the right-side convenience controls before the optional readouts shrink. -fn status_readouts_and_snapping(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens) { +fn status_readouts_and_snapping(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, row_rect: egui::Rect) { let gap = ui.spacing().item_spacing.x; let menu_width = status_snapping_menu_width(ui); let full_width = 3.0 * 18.0 + 3.0 * gap + menu_width; @@ -134,8 +136,11 @@ fn status_readouts_and_snapping(app: &mut VectorcraftApp, ui: &mut Ui, t: &Token if direct { status_snapping_buttons(app, ui); } - let height = ui.spacing().interact_size.y.min(ui.available_height()); - ui.scope(|ui| { + let height = ui.spacing().interact_size.y.min(row_rect.height()); + let mut menu_rect = ui.available_rect_before_wrap(); + menu_rect.min.y = row_rect.min.y; + menu_rect.max.y = row_rect.max.y; + ui.scope_builder(egui::UiBuilder::new().max_rect(menu_rect), |ui| { ui.spacing_mut().interact_size.y = height; ui.menu_button(tl!("Snapping"), |ui| super::control_bar::snapping_menu_contents(app, ui)); }); From 12edbb10738153d80f7195f81a90e89025a1ce34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:09:30 -0800 Subject: [PATCH 018/298] Swatches: a pattern swatch dropped on empty canvas places a copy of its tile art A pattern swatch dragged from the Swatches panel and released where there is no art now runs the new `pattern.placeArt {name, x?, y?}`: one group holding a rectangle of the tile with no fill and no stroke at its back and the tile art in its place in the tile, centered on the drop point, selected, in one undo step. Dropped on art, the swatch fills it as before. `object.pattern.replaceArt` now reads a rectangle with no fill and no stroke at the back of the art (or at the back of one selected group) as the tile and leaves it out of the tile art, so the placed copy, edited and Alt-dragged back onto the swatch, keeps its place in the tile. Without such a rectangle the tile keeps its size and moves as far as the art's bounds moved from the old tile art's, instead of staying where it was. The help page describes this edit cycle and the unpainted bounding rectangle: https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=208 https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=204 Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 5 +- crates/engine/src/cmd/patterncmds.rs | 95 +++++++++-- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/pattern.rs | 154 +++++++++++++++++- crates/ui-egui/src/canvas/context.rs | 14 +- crates/ui-egui/src/canvas/tests.rs | 44 +++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/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/widgets/drag.rs | 6 +- docs/mcp.md | 27 ++- docs/target-app-parity.md | 3 +- 38 files changed, 352 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..ba4277da58 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ mod dynamic; mod symbolism; mod symbols; -pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; +pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint}; use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..afdf7d9f60 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -766,10 +766,11 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and +/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its /// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. -fn frame_marker(n: &Node) -> Option { +pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| match i { diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index e4b6d810a6..1b5d00de58 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; +use super::brushsym::frame_marker; use super::edit::{outermost, selected_roots}; use super::pathops::Beside; use super::{ @@ -43,10 +44,19 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), + cmd!( + "pattern.placeArt", + "Place Pattern Art", + [], + None, + "{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}", + can_replace_pattern_art, + pattern_place_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -429,41 +439,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { const C: &str = "object.pattern.replaceArt"; let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); let roots = roots(s, p, C)?; let d = &s.doc()?.doc; - let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; - if roots.is_empty() { + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect()); + if src.is_empty() { return Err(bad(C, "select the art for the pattern tile")); } - let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); if paints_pattern(d, &src, &name) { return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); } + let mut next = def.clone(); + next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) { + (Some(tile), ..) => tile, + (None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()), + (None, ..) => def.tile, + }; + next.art = src.clone(); + if next.size_tile_to_art { + next.fit_tile_to_art(); + } + let tile = next.tile; // Copies made from the same next id are equal when the art matches the tile art. let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); - if fresh(&old) == fresh(&src) { + if tile == def.tile && fresh(&def.art) == fresh(&src) { return Ok(json!({ "name": name })); } s.edit("Replace Pattern Art", |d, _| { let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); if let Some(def) = d.pattern_mut(&name) { def.art = art; - if def.size_tile_to_art { - def.fit_tile_to_art(); - } + def.tile = tile; } Ok(()) })?; Ok(json!({ "name": name })) } +/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted +/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as +/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members +/// are the art. Without such a rectangle the art is `src` and there is no tile. +fn tile_and_art(src: Vec>) -> (Vec>, Option) { + let mut art = src; + if let [g] = art.as_slice() + && let NodeKind::Group { children, clip: false } = &g.kind + && children.first().is_some_and(|c| frame_marker(c).is_some()) + && **g == Node::group(g.id, children.clone()) + { + art = children.clone(); + } + match art.first().and_then(|c| frame_marker(c)) { + Some(tile) => (art.split_off(1), Some(tile)), + None => (art, None), + } +} + +/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted +/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first +/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not +/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]). +fn pattern_place_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "pattern.placeArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if def.art.is_empty() { + return Err(bad(C, "no artwork")); + } + let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0); + let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted); + let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect()); + if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Pattern Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + /// What a piece of art uses by name, for [`paints_pattern`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Uses<'a> { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..5898abc113 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -480,6 +480,7 @@ pub(super) const ALLOWED: &[&str] = &[ "pattern.delete", "pattern.list", "pattern.options", + "pattern.placeArt", "pattern.transform", "perspective.attach", "perspective.draw", diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 01f8e76fbc..d45376ae82 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -222,8 +222,9 @@ fn blue_rect(s: &mut Session) -> NodeId { } /// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo -/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the -/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +/// step: the pattern keeps its name, swatch, place and options, the tile keeps its size and moves as +/// far as the art's bounds moved, art painted with it keeps the paint, and the selected art stays on +/// the canvas, selected. Undo and Redo swap the two tiles. #[test] fn replace_art_gives_a_pattern_new_tile_art() { let mut s = session(); @@ -243,7 +244,9 @@ fn replace_art_gives_a_pattern_new_tile_art() { assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); assert_eq!(def.art[0].appearance, node(&s, blue).appearance); assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); - assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + // The red square's bounds start at (0, 0) and the blue rectangle's at (100, 100). + assert_eq!(def.tile, old.tile + vectorcraft_geom::Vec2::new(100.0, 100.0), "the tile moves with the art"); + assert_eq!((def.tile_type, &def.name), (old.tile_type, &old.name), "the options stay"); assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); @@ -282,6 +285,151 @@ fn replace_art_that_matches_the_tile_art_records_nothing() { assert_eq!(doc(&s), &before); } +/// The geometric bounds of object `id`. +fn bounds_of(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +/// Place Pattern Art places a copy of the tile art in a group with an unpainted rectangle of the +/// tile at its back, centered where it is asked for (by default the first artboard's center), in +/// the current layer, selected, as one undo step; the pattern does not change. +#[test] +fn place_art_places_the_tile_art_with_its_tile() { + let mut s = session(); + let red = make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(-5.0, -5.0, 15.0, 15.0)); + let steps = s.doc().unwrap().history.undo.len(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Place Pattern Art"))); + assert_eq!(st.selection.objects.to_vec(), vec![id], "the copy is selected"); + assert_eq!(st.doc.parent_of(id), Some(st.doc.layers[0].id), "in the current layer"); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &def, "the pattern stays as it was"); + let group = node(&s, id); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("a group: {:?}", group.kind) }; + let [marker, art] = children.as_slice() else { panic!("the tile and the art: {children:?}") }; + // The tile, centered on (200, 150), is unpainted; the art keeps its place in the tile. + assert_eq!(marker.geometric_bounds(), Some(Rect::new(190.0, 140.0, 210.0, 160.0))); + assert!(marker.appearance.fill_paint().is_none() && marker.appearance.stroke().is_none_or(|k| k.paint.is_none())); + assert_eq!(art.geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + assert_eq!(art.appearance, def.art[0].appearance); + assert!(art.id != red && art.id != def.art[0].id, "a copy with an id of its own"); + // Without a position: the first artboard's center (the document is 400 × 400). + let centered = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap()); + assert_eq!(bounds_of(&s, centered).center(), Point::new(200.0, 200.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(centered).is_none(), "Undo removes the copies"); +} + +/// The placed copy, edited and given back with Replace Pattern Art, becomes the tile art, and its +/// rectangle becomes the tile: the art keeps its place in the tile, so the pattern draws the same +/// arrangement with the new art. Given back unchanged, nothing is recorded. +#[test] +fn placed_art_given_back_keeps_its_place_in_the_tile() { + let mut s = session(); + make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 210.0, 160.0), "the rectangle is the tile"); + assert_eq!(def.art.len(), 1, "the rectangle is not part of the art: {:?}", def.art); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + let old = before.pattern("Dots").unwrap(); + let place = |tile: Rect, art: &[Arc]| vectorcraft_doc::live::nodes_bounds(art).unwrap().origin() - tile.origin(); + assert_eq!(place(def.tile, &def.art), place(old.tile, &old.art), "the art keeps its place in the tile"); + // Given back again without a change: nothing to record. + let (again, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &again); + // Edited (the art recolored and the rectangle widened, ungrouped): the new art and tile. + let NodeKind::Group { children, .. } = &node(&s, id).kind else { panic!("a group") }; + let (marker, art) = (children[0].id, children[1].id); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + sel(&mut s, &[id]); + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(marker).is_some() && doc(&s).node(art).is_some(), "ungrouped"); + s.execute("object.transform", &json!({"ids": [marker.0], "matrix": [2, 0, 0, 1, -190, 0]})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [marker.0, art.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 230.0, 160.0), "the widened rectangle is the tile"); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].appearance, node(&s, art).appearance, "the recolored art"); +} + +/// Only an unpainted rectangle at the back of the art is the tile: a painted one, or an unpainted +/// one in front of other art, is tile art like any other, and a rectangle alone leaves no art. +#[test] +fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { + let mut s = session(); + make_dots(&mut s); + let back = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let front = rect(&mut s, 110.0, 110.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [front.0], "color": "#00ff00"})).unwrap(); + // Painted: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "color": "#ffffff"})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted, but in front of the other art: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [back.0], "none": true})).unwrap(); + sel(&mut s, &[back]); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted and at the back: the tile. + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!((def.art.len(), def.tile), (1, Rect::new(100.0, 100.0, 140.0, 140.0))); + // A rectangle alone is a tile with no art. + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); +} + +/// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that +/// is not a number, a pattern with no art, while a pattern is edited and on a locked layer. +#[test] +fn place_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + doc_mut(&mut s).patterns.push(vectorcraft_doc::pattern::PatternDef::new("Empty", vec![])); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let unchanged = |s: &Session, case: &str| { + assert_eq!(doc(s), &before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + for (case, p, why) in [ + ("no name", json!({}), "missing name"), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`"), + ("x not a number", json!({"name": "Dots", "x": "100"}), "`x` must be a number"), + ("y not a number", json!({"name": "Dots", "y": true}), "`y` must be a number"), + ("no art", json!({"name": "Empty"}), "no artwork"), + ] { + let err = s.execute("pattern.placeArt", &p).unwrap_err(); + assert!(err.to_string().contains(why), "{case}: {err}"); + unchanged(&s, case); + } + let layer = doc(&s).layers[0].id; + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": true})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert_eq!(err.to_string(), "the target layer is locked or hidden"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "locked: unchanged"); + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": false})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "while editing: unchanged"); +} + /// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, /// while a pattern is edited, and for art painted with the pattern itself, directly, through /// another pattern, through a symbol, through the paints a graph stores, through a graph design a diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 9cdec919b5..898c044c35 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -57,8 +57,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` /// for a brush library's). A Brushes panel scatter, art or pattern -/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`). A chip -/// follows the pointer meanwhile. +/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`), and so +/// does a Swatches panel pattern swatch, with its tile (`pattern.placeArt`). A chip follows the +/// pointer meanwhile. pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) { crate::panels::swatches::drag_preview(app, ui.ctx()); let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return }; @@ -119,6 +120,15 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile + // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + let at = xf.to_doc(pos); + if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { + app.status(e); + } + return; + } let Some(hit) = hit else { return }; let Some(st) = app.session.active() else { return }; let (cmd, params) = match &*d { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..908f7a7844 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9842,6 +9842,50 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { } } +#[test] +fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { + use vectorcraft_color::{Color, Paint}; + use widgets::{PanelDrag, SwatchRows}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let tile = app.session.execute("shape.rectangle", &json!({"x": 300, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("object.pattern.make", &json!({"ids": [tile], "name": "Checks", "edit": false})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let swatch = |name: &str, paint: Paint| { + let rows = SwatchRows { grabbed: name.into(), names: vec![name.into()], groups: false }; + PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None } + }; + let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let undo = undo_len(&app); + // A color swatch, and a pattern from elsewhere than the Swatches panel, place nothing. + drop(&mut app, swatch("Red", Paint::solid(Color::from_hex("#ed1c24").unwrap())), Point::new(250.0, 220.0)); + drop(&mut app, PanelDrag::paint(vectorcraft_doc::pattern::pattern_paint("Checks")), Point::new(250.0, 220.0)); + assert_eq!(undo_len(&app), undo); + // The pattern swatch: a copy of its tile art and tile, centered where it lands, selected. + drop(&mut app, pattern.clone(), Point::new(250.0, 220.0)); + let st = app.session.active().unwrap(); + assert_eq!(undo_len(&app), undo + 1, "{}", app.ui.status); + assert_eq!(st.history.undo.last().unwrap().label, "Place Pattern Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // On art, the swatch fills it as before. + drop(&mut app, pattern, Point::new(100.0, 100.0)); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); + assert!(matches!(&n, Paint::Pattern { pattern, .. } if pattern == "Checks"), "{n:?}"); +} + #[test] fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..f3f2642b89 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7518,6 +7518,7 @@ breakText Glyphs Глифи Place Brush Art Поставяне на графика на четка Replace Brush Art Замяна на графика на четка Replace Pattern Art Замяна на графика на мостра + Place Pattern Art Поставяне на графика на мостра Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика? Apply to Strokes Прилагане към щрихите Leave Strokes Оставяне на щрихите diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..dfeda0bf71 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7567,6 +7567,7 @@ shape Open Otvoren Place Brush Art Postavi crtež četkice Replace Brush Art Zamijeni crtež četkice Replace Pattern Art Zamijeni crtež uzorka + Place Pattern Art Postavi crtež uzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom? Apply to Strokes Primijeni na poteze Leave Strokes Ostavi poteze diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..4fae84451b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifs Place Brush Art Col·loca l’art del pinzell Replace Brush Art Substitueix l’art del pinzell Replace Pattern Art Substitueix l’art del motiu + Place Pattern Art Col·loca l’art del motiu Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou? Apply to Strokes Aplica als traços Leave Strokes Deixa els traços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..6a003e834f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8380,6 +8380,7 @@ breakText Glyphs Glyfy Place Brush Art Umístit kresbu štětce Replace Brush Art Nahradit kresbu štětce Replace Pattern Art Nahradit kresbu vzorku + Place Pattern Art Umístit kresbu vzorku Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou? Apply to Strokes Použít na tahy Leave Strokes Ponechat tahy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..4d4e1d1791 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10436,6 +10436,7 @@ breakText Glyphs Glyffer Place Brush Art Placér penselgrafik Replace Brush Art Erstat penselgrafik Replace Pattern Art Erstat mønstergrafik + Place Pattern Art Placér mønstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik? Apply to Strokes Anvend på streger Leave Strokes Bevar streger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..9ee0901afe 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8005,6 +8005,7 @@ breakText Glyphs Glyphen Place Brush Art Pinselgrafik platzieren Replace Brush Art Pinselgrafik ersetzen Replace Pattern Art Mustergrafik ersetzen + Place Pattern Art Mustergrafik platzieren Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen? Apply to Strokes Auf Konturen anwenden Leave Strokes Konturen beibehalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..195ea82836 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Γλύφοι Place Brush Art Τοποθέτηση σχεδίου πινέλου Replace Brush Art Αντικατάσταση σχεδίου πινέλου Replace Pattern Art Αντικατάσταση σχεδίου μοτίβου + Place Pattern Art Τοποθέτηση σχεδίου μοτίβου Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο; Apply to Strokes Εφαρμογή στα περιγράμματα Leave Strokes Διατήρηση περιγραμμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..e0d1f9cad3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8357,6 +8357,7 @@ breakText Glyphs Glifos Place Brush Art Colocar ilustración del pincel Replace Brush Art Reemplazar ilustración del pincel Replace Pattern Art Reemplazar ilustración del motivo + Place Pattern Art Colocar ilustración del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración? Apply to Strokes Aplicar a los trazos Leave Strokes Dejar los trazos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..c82597b70b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8447,6 +8447,7 @@ breakText Glyphs Merkit Place Brush Art Sijoita siveltimen kuvitus Replace Brush Art Korvaa siveltimen kuvitus Replace Pattern Art Korvaa kuvion kuvitus + Place Pattern Art Sijoita kuvion kuvitus Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus? Apply to Strokes Käytä viivoihin Leave Strokes Jätä viivat ennalleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..b4a1357166 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8376,6 +8376,7 @@ breakText Glyphs Glyphes Place Brush Art Placer l’illustration de la forme Replace Brush Art Remplacer l’illustration de la forme Replace Pattern Art Remplacer l’illustration du motif + Place Pattern Art Placer l’illustration du motif Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ? Apply to Strokes Appliquer aux contours Leave Strokes Conserver les contours diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..2696806612 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5150,6 +5150,7 @@ antiAlias Sharp શાર્પ Place Brush Art બ્રશ આર્ટ પ્લેસ કરો Replace Brush Art બ્રશ આર્ટ બદલો Replace Pattern Art પેટર્ન આર્ટ બદલો + Place Pattern Art પેટર્ન આર્ટ પ્લેસ કરો Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? સ્ટ્રોક્સ આ બ્રશ વાપરે છે. તે સ્ટ્રોક્સ પર નવી આર્ટ લાગુ કરવી છે કે તેમને જેમ છે તેમ રાખીને નવી આર્ટવાળી બ્રશની નકલ ઉમેરવી છે? Apply to Strokes સ્ટ્રોક્સ પર લાગુ કરો Leave Strokes સ્ટ્રોક્સ જેમ છે તેમ રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1c00d27a9a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4531,6 +4531,7 @@ arrowhead Feather पंख Place Brush Art ब्रश आर्टवर्क रखें Replace Brush Art ब्रश आर्टवर्क बदलें Replace Pattern Art पैटर्न आर्टवर्क बदलें + Place Pattern Art पैटर्न आर्टवर्क रखें Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें? Apply to Strokes स्ट्रोक्स पर लागू करें Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..ef865a6414 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8366,6 +8366,7 @@ breakText Glyphs Glifák Place Brush Art Ecsetgrafika elhelyezése Replace Brush Art Ecsetgrafika cseréje Replace Pattern Art Mintázatgrafika cseréje + Place Pattern Art Mintázatgrafika elhelyezése Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával? Apply to Strokes Alkalmazás a körvonalakra Leave Strokes Körvonalak megtartása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..8372f7f977 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8221,6 +8221,7 @@ breakText Glyphs Glif Place Brush Art Tempatkan karya seni kuas Replace Brush Art Ganti karya seni kuas Replace Pattern Art Ganti karya seni pola + Place Pattern Art Tempatkan karya seni pola Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru? Apply to Strokes Terapkan ke Stroke Leave Strokes Biarkan Stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c2cf171f71 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8043,6 +8043,7 @@ breakText Glyphs Glifi Place Brush Art Inserisci grafica del pennello Replace Brush Art Sostituisci grafica del pennello Replace Pattern Art Sostituisci grafica del motivo + Place Pattern Art Inserisci grafica del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica? Apply to Strokes Applica alle tracce Leave Strokes Lascia le tracce diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..75bf59ef58 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9932,6 +9932,7 @@ breakText Glyphs 字形 Place Brush Art ブラシのアートを配置 Replace Brush Art ブラシのアートを置き換え Replace Pattern Art パターンのアートを置き換え + Place Pattern Art パターンのアートを配置 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか? Apply to Strokes 線に適用 Leave Strokes 線を保持 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ae0f3fea37 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10554,6 +10554,7 @@ breakText Glyphs გლიფები Place Brush Art ფუნჯის ნახატის განთავსება Replace Brush Art ფუნჯის ნახატის ჩანაცვლება Replace Pattern Art პატერნის ნახატის ჩანაცვლება + Place Pattern Art პატერნის ნახატის განთავსება Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით? Apply to Strokes კონტურებზე გამოყენება Leave Strokes კონტურების დატოვება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..0c8afe603c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8015,6 +8015,7 @@ breakText Glyphs 글리프 Place Brush Art 브러시 아트 배치 Replace Brush Art 브러시 아트 바꾸기 Replace Pattern Art 패턴 아트 바꾸기 + Place Pattern Art 패턴 아트 배치 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까? Apply to Strokes 선에 적용 Leave Strokes 선 유지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..cf3aa33af9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10274,6 +10274,7 @@ breakText Glyphs Glyphs Place Brush Art Penseelillustratie plaatsen Replace Brush Art Penseelillustratie vervangen Replace Pattern Art Patroonillustratie vervangen + Place Pattern Art Patroonillustratie plaatsen Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen? Apply to Strokes Op contouren toepassen Leave Strokes Contouren behouden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..ae16f5e361 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8239,6 +8239,7 @@ breakText Glyphs Glify Place Brush Art Umieść kompozycję pędzla Replace Brush Art Zastąp kompozycję pędzla Replace Pattern Art Zastąp kompozycję wzorka + Place Pattern Art Umieść kompozycję wzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją? Apply to Strokes Zastosuj do obrysów Leave Strokes Pozostaw obrysy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..59275fc6c3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifos Place Brush Art Colocar Arte do Pincel Replace Brush Art Substituir Arte do Pincel Replace Pattern Art Substituir Arte do Padrão + Place Pattern Art Colocar Arte do Padrão Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte? Apply to Strokes Aplicar aos Traçados Leave Strokes Manter Traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..010a3c8e26 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Глифы Place Brush Art Поместить рисунок кисти Replace Brush Art Заменить рисунок кисти Replace Pattern Art Заменить рисунок узора + Place Pattern Art Поместить рисунок узора Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком? Apply to Strokes Применить к обводкам Leave Strokes Оставить обводки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..8f5b68b23c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8415,6 +8415,7 @@ breakText Glyphs Glyfer Place Brush Art Placera penselgrafik Replace Brush Art Ersätt penselgrafik Replace Pattern Art Ersätt mönstergrafik + Place Pattern Art Placera mönstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken? Apply to Strokes Använd på konturer Leave Strokes Behåll konturer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..27abc76472 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10270,6 +10270,7 @@ breakText Glyphs Glifler Place Brush Art Fırça Çizimini Yerleştir Replace Brush Art Fırça Çizimini Değiştir Replace Pattern Art Desen Çizimini Değiştir + Place Pattern Art Desen Çizimini Yerleştir Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin? Apply to Strokes Konturlara Uygula Leave Strokes Konturları Bırak diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..41ecd25cf7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8025,6 +8025,7 @@ breakText Glyphs Гліфи Place Brush Art Розмістити малюнок пензля Replace Brush Art Замінити малюнок пензля Replace Pattern Art Замінити малюнок візерунка + Place Pattern Art Розмістити малюнок візерунка Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком? Apply to Strokes Застосувати до обведень Leave Strokes Залишити обведення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..61bfc96683 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8071,6 +8071,7 @@ breakText Glyphs Glyph Place Brush Art Đặt đối tượng của cọ Replace Brush Art Thay đối tượng của cọ Replace Pattern Art Thay đối tượng của họa tiết + Place Pattern Art Đặt đối tượng của họa tiết Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới? Apply to Strokes Áp dụng cho nét Leave Strokes Giữ nguyên nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..cf31b8b7e3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8249,6 +8249,7 @@ breakText Glyphs 字形 Place Brush Art 置入画笔图稿 Replace Brush Art 替换画笔图稿 Replace Pattern Art 替换图案图稿 + Place Pattern Art 置入图案图稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本? Apply to Strokes 应用于描边 Leave Strokes 保留描边 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..dd143d13b9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8073,6 +8073,7 @@ breakText Glyphs 字符 Place Brush Art 置入筆刷圖稿 Replace Brush Art 取代筆刷圖稿 Replace Pattern Art 取代圖樣圖稿 + Place Pattern Art 置入圖樣圖稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本? Apply to Strokes 套用至筆畫 Leave Strokes 保留筆畫 diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index da6698b6be..4f7edafc41 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -10,8 +10,10 @@ pub enum PanelDrag { /// A paint: Swatches panel tiles, a Fill/Stroke proxy, a Recent Colors chip, a Color Guide /// color or the Gradient panel's thumbnail. Art it is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; /// null for a colour group, which paints nothing) through the active proxy's - /// `paint.setFill`/`paint.setStroke`; the Gradient panel's ramp takes its colour as a stop; the - /// Swatches panel moves `rows`, or makes a swatch of a paint dragged from elsewhere. `library`: + /// `paint.setFill`/`paint.setStroke`; a Swatches panel pattern swatch dropped where there is no + /// art places a copy of its tile art there (`pattern.placeArt`); the Gradient panel's ramp takes + /// its colour as a stop; the Swatches panel moves `rows`, or makes a swatch of a paint dragged + /// from elsewhere. `library`: /// the Libraries panel colour it is (library id, colour name), which that panel moves to where /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..155232b365 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6174,9 +6174,13 @@ details are VectorCraft's own rules; the help page says only that the option mov `object.pattern.replaceArt {name, ids?}` (Replace Pattern Art) makes copies of the selected art, or of `ids`, the tile art of pattern `name`, as one undo step, and returns `{name}`. The pattern keeps its name, its swatch and the swatch's -place, its tile and its options; with `sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and -`vSpacing`. Fills and strokes name the pattern, so every object painted with it draws the new tile. The art stays on the -canvas, selected as it was. Art that matches the tile art already records no undo step. The command is off while a +place, and its options. When the backmost object of the art is a rectangle with no fill and no stroke (or the backmost +member of one selected group, as `pattern.placeArt` places it), that rectangle becomes the tile and is left out of the +tile art, and the group's members become the art. Otherwise the tile keeps its size and moves by as much as the top-left +corner of the art's bounds moved from the old tile art's, so art drawn anywhere on the canvas stays in its tile. With +`sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and `vSpacing`. Fills and strokes name the pattern, +so every object painted with it draws the new tile. The art stays on the canvas, selected as it was. Art and a tile that +match the pattern's already record no undo step. A rectangle alone leaves no art and is refused. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, changing nothing, for a missing `name`, a pattern that does not exist, no art, and art painted with the pattern itself, directly or through the symbols, other patterns, graph designs and brushes it uses, or the series and label paints a graph stores. In the Swatches panel, art dragged off the canvas and released with Alt (Option on macOS) held over a @@ -6184,7 +6188,22 @@ pattern swatch runs it with that swatch's pattern; the swatch is outlined while else in the list, or without Alt, the art becomes a new pattern swatch as before. The help page describes replacing a pattern by dragging its edited tile onto the old swatch with Alt or Option held, with the pattern updated in the file (, -archived copy). Keeping the tile, the options and the source art are VectorCraft's own rules. +archived copy). Keeping the tile's size, moving it with the art, the options and the source art are VectorCraft's own +rules. The help page describes a tile bounded by a rectangle that is the backmost object, with no fill and no stroke +(, archived copy). + +`pattern.placeArt {name, x?, y?}` (Place Pattern Art) places a copy of pattern `name`'s tile art, centered on (`x`, `y`) +(default: the center of the first artboard), in the layer new art goes into, selects it, and returns `{id}`, in one undo +step. The copy is one group: a rectangle of the pattern's tile with no fill and no stroke at its back, then the tile art +in its place in the tile, so `object.pattern.replaceArt` reads the edited copy back with the same tile. The pattern does +not change. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, +changing nothing, for a missing `name`, a pattern that does not exist, an `x` or `y` that is not a number, a pattern +with no art ("no artwork") and a locked or hidden target layer. In the app, a pattern swatch dragged from the Swatches +panel onto an empty part of the canvas runs it at the drop point; dropped on art, the swatch fills it as before. The +help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and Alt-dragging +it back onto the swatch +(, archived copy). The group, +its rectangle, the centering and the default position are VectorCraft's own rules. ```json {"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..eadaf243ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -925,7 +925,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **Cancel, Delete and rename leave no paint of a missing pattern:** the help page lists Save a Copy, Done and Cancel for leaving pattern editing (https://helpx.adobe.com/illustrator/using/create-edit-patterns.html). Canceling a pattern made for the edit removes it with every swatch of it, a color group's included. Canceling a new pattern, `pattern.delete` and a `pattern.options` rename reach every paint of the pattern: art outside the editing layer, opacity mask art, type runs, symbol definitions, graph designs, the series and label paints a graph keeps for its next redraw, other patterns' tiles (a copy Save a Copy made included), graphic and character styles, brush art, and the fill, stroke and appearance new art takes. Canceling a new pattern and Delete make those paints no paint, a VectorCraft rule; a rename renames them. Canceling the edit of an existing pattern puts its definition back as it was when editing started; after a rename in Pattern Options, it also gives the pattern its old name back with its swatches and paints, unless another pattern, swatch or color group has taken that name. Undo and Redo restore new art's paints with the document. Tests in `tests/pattern.rs` cover each command. - **Move Tile with Art:** Pattern Options has the Move Tile with Art checkbox under Size Tile to Art, and with it on, moving the tile art in pattern editing mode moves the tile with it (). VectorCraft's own rules for what the page leaves open: the tile moves only when a move takes all of the tile art, by the same offset; rotations, scales, copies and anchor moves leave it in place; the option is off for a new pattern. `pattern.options {moveTileWithArt}` sets it and `pattern.list` reports it. Tests in `tests/pattern.rs` and `panels::pattern_options::tests` cover it. -- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch, tile and options (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch and options, the tile keeps its size and moves with the art (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **A pattern swatch dragged onto empty canvas places its tile art:** the help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and dragging it back onto the swatch with Alt (, archived copy), and a tile bounded by a backmost rectangle with no fill and no stroke (). A pattern swatch released over an empty part of the canvas places a copy of the pattern's tile art at the drop point, selected, in one undo step (`pattern.placeArt`); dropped on art, it still fills that art. `object.pattern.replaceArt` reads an unpainted rectangle at the back of the art as the tile. VectorCraft's own rules: the copy is one group with an unpainted rectangle of the tile at its back, centered on the drop point, and the pattern itself does not change. Tests in `tests/pattern.rs` and `canvas::tests` cover it. - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). From e94a8aed63ce72c12780f140265119e9269b1ec1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:57 -0800 Subject: [PATCH 019/298] Swatches: a drop inside a filled shape fills it with Path Only on With Object Selection by Path Only on, a pattern swatch or a brush with art dropped inside a filled object, away from its outline, found no art under the pointer and placed a copy of the tile art or brush art there. The empty-canvas check now counts fills (and type by its area), as the mesh-point check does, so the drop fills the object instead. The unpainted tile rectangle that object.pattern.replaceArt and brush.replaceArt read also has to run around its four corners in order: a closed path through them in a crossing order is art, not the tile. --- crates/engine/src/cmd/brushsym/brushes.rs | 7 +++++-- crates/engine/src/tests/pattern.rs | 13 +++++++++++++ crates/ui-egui/src/canvas/context.rs | 15 ++++++++++++++- crates/ui-egui/src/canvas/tests.rs | 21 +++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index afdf7d9f60..efcb425091 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -769,7 +769,8 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { /// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and /// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its -/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. +/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing +/// and that has no other appearance. pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() @@ -782,7 +783,9 @@ pub(crate) fn frame_marker(n: &Node) -> Option { let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; let at_corners = sp.anchors.len() == 4 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)) + // Each side, the closing one included, joins two corners that share an edge. + && sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y); (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) } diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index d45376ae82..36403a736a 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -391,6 +391,19 @@ fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { // A rectangle alone is a tile with no art. let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); + // An unpainted path through the four corners of its bounds in a crossing order is not a + // rectangle: art. + let corners = [(200, 200), (240, 240), (240, 200), (200, 240)]; + let anchors: Vec<_> = corners.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let bowtie = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + sel(&mut s, &[bowtie]); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [bowtie.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 2, "the crossing path is art: {:?}", def.art); + assert_ne!(def.tile, Rect::new(200.0, 200.0, 240.0, 240.0), "the crossing path is not the tile"); } /// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 898c044c35..584332b8af 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -113,6 +113,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. if let (None, widgets::PanelDrag::Brush { name, def }) = (&hit, &*d) && matches!(def["type"].as_str(), Some("scatter" | "art" | "pattern")) + && no_art_at(app, xf.to_doc(pos), xf.zoom) { let at = xf.to_doc(pos); if let Err(e) = app.run("brush.placeArt", json!({"name": name, "x": at.x, "y": at.y})) { @@ -122,7 +123,9 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. - if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) + && no_art_at(app, xf.to_doc(pos), xf.zoom) + { let at = xf.to_doc(pos); if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { app.status(e); @@ -177,6 +180,16 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } } +/// Whether no art is under document point `p` at `zoom`, with fills counted even with Object +/// Selection by Path Only and type objects by their area even with Type Object Selection by Path +/// Only: a brush's or a pattern swatch's art is placed only there. +fn no_art_at(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> bool { + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..opt }) + }) + .is_none() +} + /// The selected, editable gradient mesh and its points that a solid color dropped at document /// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh /// (fills count even with Object Selection by Path Only, and clipping applies), and the points are diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 908f7a7844..8b59e2734d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9840,6 +9840,19 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Side Tile")); } } + // With Object Selection by Path Only, inside a filled rectangle and away from its outline is + // still on art: nothing is placed. (The placed copies are undone first.) + for _ in 0..3 { + app.session.execute("edit.undo", &json!({})).unwrap(); + } + app.session.execute("shape.rectangle", &json!({"x": 250, "y": 200, "width": 100, "height": 80})).unwrap(); + app.session.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + drop(&mut app, "Arrow", Point::new(300.0, 240.0)); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); } #[test] @@ -9880,6 +9893,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // With Object Selection by Path Only, inside the filled rectangle and away from its outline is + // still on art: nothing is placed. + app.session.execute("paint.setFill", &json!({"ids": [id], "color": "#ffffff"})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = undo_len(&app); + drop(&mut app, pattern.clone(), Point::new(100.0, 100.0)); + assert_eq!(undo_len(&app), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); // On art, the swatch fills it as before. drop(&mut app, pattern, Point::new(100.0, 100.0)); let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); From 71e2f35b3b65b9f6d4827eeb1fef0e2571d62d1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:41:54 -0800 Subject: [PATCH 020/298] Web: the Paintbrush records an airbrush pen's stylus wheel The web build reads Pointer Events' tangentialPressure (-1..1, https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure) for each pen sample, including the positions a fast stroke's events coalesce, and gives the Paintbrush the wheel as 0..1, as the macOS reader does. Pointer Events give 0 for a pen without a wheel, so 0 counts as no wheel until the pen has reported another value since it came near; another pen, the other end, a canceled press and leaving the hover range start afresh. Mouse and finger input reads no wheel. The canvas now pairs the feed's per-move poses with the moves of a frame that carries touch events (the web pen), keeping the touch's force as the pressure, so each move keeps its own wheel. --- apps/vectorcraft-web/src/pencil.rs | 191 ++++++++++++++++++++++++++--- crates/ui-egui/src/canvas/drag.rs | 7 +- crates/ui-egui/src/canvas/tests.rs | 59 +++++++++ docs/target-app-parity.md | 4 +- 4 files changed, 241 insertions(+), 20 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 88b85e9d50..620d38ef1f 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -50,11 +50,31 @@ pub struct Pointers { eraser: bool, /// The pen's pressure and end for the canvas (`Services::stylus`). stylus: StylusFeed, + /// The pen whose finger wheel is read ([`Pointers::wheel`]). + wheel: Option, +} + +/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential +/// pressure other than 0 since it came near. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Wheel { + id: i32, + eraser: bool, + reads: bool, } impl Default for Pointers { fn default() -> Self { - Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() } + Self { + events: vec![], + pen: None, + fingers: vec![], + primary: None, + button: None, + eraser: false, + stylus: StylusFeed::on_ui_thread(), + wheel: None, + } } } @@ -67,6 +87,8 @@ struct Input<'a> { id: i32, button: i16, pressure: f32, + /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. + tangential: f32, modifiers: egui::Modifiers, } @@ -93,9 +115,29 @@ impl Pointers { self.stylus.clone() } - /// A pen moved or pressed with `pressure`, with the end it last pressed with. - fn pen_sample(&self, pressure: f32) { - self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() })); + /// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed + /// with. With `moved`, the sample comes with one `PointerMoved` and the feed keeps it for that + /// move ([`StylusFeed::set_move`]), so the canvas pairs each move with its own wheel. + fn pen_sample(&self, pressure: f32, wheel: Option, moved: bool) { + let sample = PenSample { pressure, eraser: self.eraser, pose: PenPose { wheel, ..PenPose::default() } }; + if moved { + self.stylus.set_move(sample); + } else { + self.stylus.set_sample(Some(sample)); + } + } + + /// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with + /// Pointer Events' `tangentialPressure` (−1..1, + /// ): [`PenPose`]'s + /// wheel of 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 + /// for a pen without a wheel, so 0 reads as none until that pen, with that end, has reported a + /// value other than 0 since it came near. A value that is not a number is none. + fn wheel(&mut self, id: i32, tangential: f32) -> Option { + let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads); + let reads = known || (tangential.is_finite() && tangential != 0.0); + self.wheel = Some(Wheel { id, eraser: self.eraser, reads }); + (reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0) } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -135,7 +177,10 @@ impl Pointers { } /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). - fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { + /// + /// `coalesced` holds the positions the pen reported since the last event, each with its + /// pressure and tangential pressure, the last one at `pos`. + fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool { let id = e.id; if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is @@ -164,19 +209,24 @@ impl Pointers { if let Some(end) = end { self.eraser = end; } - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { - self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second - // on an iPad), each with its pressure, so fast strokes keep their curve. - for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { - self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1)); - self.events.push(Event::PointerMoved(c.0)); + // on an iPad), each with its pressure and wheel, so fast strokes keep + // their curve. + for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) { + let wheel = self.wheel(id, tangential); + self.pen_sample(pressure, wheel, true); + self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure)); + self.events.push(Event::PointerMoved(at)); } + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force); self.events.push(Event::PointerMoved(pos)); } @@ -190,12 +240,19 @@ impl Pointers { } // Pointer Events report no end while a pen hovers: it keeps the end it // last pressed with. - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { - let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; - self.pen_sample(0.0); + let (phase, wheel) = if kind == "pointerup" { + // Lifted, the pen hovers on and keeps what it read of its wheel. + (TouchPhase::End, self.wheel(id, e.tangential)) + } else { + self.wheel = None; + (TouchPhase::Cancel, None) + }; + self.pen_sample(0.0, wheel, false); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -205,6 +262,11 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } + // Left the hover range or canceled: the pen reads its wheel afresh. + let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + if gone && self.wheel.is_some_and(|w| w.id == id) { + self.wheel = None; + } return self.pen.is_some(); } } @@ -277,7 +339,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, let z = runner.egui_ctx().zoom_factor(); let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z); let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z); - let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove" + let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove" && e.pointer_type() == "pen" // Safari before 17 hasn't it, and calling a missing method would abort the app. && js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false) @@ -285,7 +347,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, e.get_coalesced_events() .iter() .filter_map(|c| c.dyn_into::().ok()) - .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0))) + .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure())) .collect() } else { vec![] @@ -296,6 +358,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, id: e.pointer_id(), button: e.button(), pressure: e.pressure(), + tangential: e.tangential_pressure(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -344,7 +407,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } } fn reset() { @@ -501,6 +564,100 @@ mod tests { reset(); } + fn pen_at(button: i16, tangential: f32) -> Input<'static> { + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + } + + fn wheels(feed: &StylusFeed) -> Vec> { + feed.take_moves().into_iter().map(|(_, q)| q.wheel).collect() + } + + /// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the + /// feed as 0..1 with each move, once the pen has reported a value other than 0. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] { + assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true)); + } + assert_eq!( + wheels(&feed), + [None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)], + "none until reported; then 0 is half way, past the ends is clamped and not a number is none" + ); + assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.5), "the lift keeps the wheel"); + reset(); + } + + /// The positions a fast stroke's event coalesced keep their own wheel, in order, and the + /// event's own position comes last with its own. + #[test] + fn coalesced_moves_keep_their_wheel() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0)); + assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true)); + let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)]; + assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true)); + let moved: Vec = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect(); + let kept = feed.take_moves(); + assert_eq!(moved, [Pos2::ZERO, a, b, c]); + assert_eq!(kept.iter().map(|(_, q)| q.wheel).collect::>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]); + assert_eq!(kept.iter().map(|&(f, _)| f).collect::>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too"); + reset(); + } + + /// A pen that leaves the hover range, a canceled press, another pen and the other end each + /// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel. + #[test] + fn the_wheel_is_read_afresh_for_each_pen_and_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let learn = |p: &mut Pointers, button: i16| { + assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + }; + let hover = |p: &mut Pointers, id: i32| { + let mut e = pen_at(-1, 0.0); + e.id = id; + e.pressure = 0.0; + assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true)); + }; + learn(&mut p, 0); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "a lift into hover keeps it"); + p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a canceled press"); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "after a canceled press"); + learn(&mut p, 0); + hover(&mut p, 8); + assert_eq!(wheels(&feed).last(), Some(&None), "another pen"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "the other end"); + assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] { + let mut other = pen_at(0, 0.5); + (other.pointer_type, other.id) = (pointer_type, 10); + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!(feed.pose(), None, "{pointer_type} {kind}"); + assert!(feed.take_moves().is_empty(), "{pointer_type} {kind}"); + } + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..a96873d5aa 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,7 +193,7 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any. The last move is the pointer's position; the +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, /// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that @@ -222,6 +222,11 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< _ => {} } } + // A web pen's feed kept a pose (its wheel) for each of its moves: paired from the end, + // as below, with the touch's force kept as the pressure. + for (m, &(_, q)) in moves.iter_mut().rev().zip(samples.iter().rev()) { + m.2 = Some(q); + } } else if !samples.is_empty() { // The feed's last sample is the last move's: pair them from the end. A lift's 0 is // no pressure (the press keeps its last touch). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..8a642f7667 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11983,6 +11983,65 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { } } +/// The web build's pen comes as touch events with its pressure as their force, and its feed keeps +/// a wheel for each move: [`frame_moves`] keeps the touch's force and pairs each move with its own +/// pose from the end, and the last move's pose comes second. +#[test] +fn frame_moves_pair_a_web_pens_touches_with_the_feeds_poses() { + let ctx = egui::Context::default(); + let (a, b, c) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(30.0, 40.0)); + let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat(); + let feed = StylusFeed::default(); + let wheel = |w: f32| PenPose { wheel: Some(w), ..PenPose::default() }; + for (p, w) in [(0.9, 0.0), (0.2, 0.25), (0.8, 0.5), (0.6, 0.75)] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose: wheel(w), ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), None)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.2), Some(wheel(0.25))), (b, Some(0.8), Some(wheel(0.5)))], "an older move's sample is left over"); + assert_eq!(last, Some(wheel(0.75))); +} + +/// A web pen's stroke reaches the Paintbrush with each move's pressure, from its touch, and each +/// move's finger wheel, from the feed. +#[test] +fn a_web_pens_wheel_reaches_the_paintbrush_with_each_move() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let feed = StylusFeed::default(); + app.services.stylus = Some(feed.clone()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.select_tool("paintbrush"); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); + let moved = |pressure: f32, wheel: f32| { + feed.set_move(crate::stylus::PenSample { pressure, pose: PenPose { wheel: Some(wheel), ..PenPose::default() }, ..Default::default() }) + }; + moved(0.5, 0.0); + frame(&mut app, &ctx, pen(egui::TouchPhase::Start, at(300.0), 0.5)); + let mut events = vec![]; + for (x, pressure, wheel) in [(340.0, 0.3, 0.25), (380.0, 0.7, 0.5), (420.0, 0.9, 0.75), (460.0, 0.4, 1.0)] { + moved(pressure, wheel); + events.extend(pen(egui::TouchPhase::Move, at(x), pressure)); + } + frame(&mut app, &ctx, events); + frame(&mut app, &ctx, pen(egui::TouchPhase::End, at(460.0), 0.4)); + let (cmd, p) = app.session.journal.last().unwrap().clone(); + assert_eq!(cmd, "path.freehand"); + let points = p["points"].as_array().unwrap(); + let column = |i: usize| -> Vec { points.iter().filter_map(|s| s.get(i).and_then(serde_json::Value::as_f64)).collect() }; + let (pressures, wheels) = (column(2), column(6)); + for (pressure, wheel) in [(0.3, 0.25), (0.7, 0.5), (0.9, 0.75)] { + let paired = points.iter().any(|s| { + let near = |i: usize, v: f64| s.get(i).and_then(serde_json::Value::as_f64).is_some_and(|got| (got - v).abs() < 0.01); + near(2, pressure) && near(6, wheel) + }); + assert!(paired, "{pressure} with {wheel}: {pressures:?} {wheels:?}"); + } +} + /// The last move of a frame reaches the Paintbrush with the tilt the host's feed kept for that /// move, not with a later pen sample that came without a move. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..dba4dd200d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2057,7 +2057,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2065,7 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (), for each move of a pen including the positions a fast stroke's events coalesce; Windows pointer messages have no field for it. Pointer Events give 0 for a pen without a wheel, so in the web build, as on macOS, 0 counts as no wheel until the pen has reported another value since it came near; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. That rule is VectorCraft's own. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `canvas::tests::a_web_pens_wheel_reaches_the_paintbrush_with_each_move` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 32fa158676215acf084360fd0b8e43e52b4c8fbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:20:02 -0800 Subject: [PATCH 021/298] Stylus: docs name the web build as a source of the airbrush wheel The stylus module doc and StylusFeed::set_move now say the web build reads the wheel from Pointer Events' tangentialPressure and keeps a pose for each move. The frame_moves doc comment is rewrapped. --- crates/ui-egui/src/canvas/drag.rs | 15 ++++++++------- crates/ui-egui/src/stylus.rs | 9 +++++---- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index a96873d5aa..71e09a39ff 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,13 +193,14 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the -/// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no -/// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, -/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that -/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's -/// position is the pointer's. The last move before it is left out only when it is at that -/// position; its tilt and rotation come second either way. +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). +/// The last move is the pointer's position; the tilt and rotation the feed kept for it come +/// second, if any. A mouse's moves count too, with no pressure: a fast mouse stroke otherwise keeps +/// one position a frame, a sample every few pixels, too few for a low Fidelity to follow the hand +/// (#3328). With `release`, the moves stop at that button's button-up in this frame, if it came: +/// the moves after it are hover, and the button-up's position is the pointer's. The last move +/// before it is left out only when it is at that position; its tilt and rotation come second +/// either way. pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0b27d24127..1111b5983e 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -12,8 +12,9 @@ //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. //! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the -//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on -//! Windows, whose pointer messages have no field for it, or in the web build. +//! host reads it: from XInput2 on X11, from AppKit on macOS and from Pointer Events' +//! `tangentialPressure` in the web build. The app does not read it on Windows, whose pointer +//! messages have no field for it. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before @@ -157,8 +158,8 @@ impl StylusFeed { } /// Like [`Self::set_sample`], for a pen sample that comes with one pointer move of the window, - /// read before the window handles the move (macOS): its pressure, tilt and rotation are also - /// kept for that move ([`Self::take_moves`]). + /// read before the window handles the move (macOS and the web build): its pressure, tilt, + /// rotation and wheel are also kept for that move ([`Self::take_moves`]). pub fn set_move(&self, sample: PenSample) { self.set_sample(Some(sample)); let mut pen = self.lock(); From 8833fde4a962923df8ebc4a6c15bc8bcb05fbaee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:04:53 -0800 Subject: [PATCH 022/298] Web: the stylus wheel stays learned when the pen hovers across the canvas edge A hovering pen that moved off the canvas onto another element cleared what it had read of its airbrush wheel, so back on the canvas a centered wheel (0) read as no wheel. The pen now reads its wheel afresh only when a pointerleave names no element it moved onto (relatedTarget), which is how leaving the hover range is reported, on the canvas or off it. --- apps/vectorcraft-web/src/pencil.rs | 38 ++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 620d38ef1f..f19939bde8 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -89,6 +89,9 @@ struct Input<'a> { pressure: f32, /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. tangential: f32, + /// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving + /// one element for another is still in its hover range. + entered: bool, modifiers: egui::Modifiers, } @@ -262,8 +265,10 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } - // Left the hover range or canceled: the pen reads its wheel afresh. - let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + // Left the hover range (a leave onto no element, on the canvas or off it) + // or canceled: the pen reads its wheel afresh. Moving onto another element + // keeps what it read. + let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel"; if gone && self.wheel.is_some_and(|w| w.id == id) { self.wheel = None; } @@ -359,6 +364,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, button: e.button(), pressure: e.pressure(), tangential: e.tangential_pressure(), + entered: e.related_target().is_some(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -407,7 +413,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() } } fn reset() { @@ -565,7 +571,7 @@ mod tests { } fn pen_at(button: i16, tangential: f32) -> Input<'static> { - Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() } } fn wheels(feed: &StylusFeed) -> Vec> { @@ -658,6 +664,30 @@ mod tests { reset(); } + /// A hovering pen that moves off the canvas onto another element and back keeps what it read + /// of its wheel; one that leaves the hover range off the canvas reads it afresh. + #[test] + fn the_wheel_survives_crossing_the_canvas_edge() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + let mut hover = pen_at(-1, 0.0); + hover.pressure = 0.0; + let mut onto = pen_at(-1, 0.0); + (onto.pressure, onto.entered) = (0.0, true); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false)); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "moved onto another element and back"); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + p.feed("pointerleave", &hover, Pos2::ZERO, &[], false); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range off the canvas"); + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] From 441994e52deb81237df50d2d8f0530a3f8ae01d5 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:33:28 +0430 Subject: [PATCH 023/298] UI: exclude protected dimensions from Outline Stroke eligibility Use the same linked-dimension roots as the command lift operation without cloning the document. Exercise the real context menu for separate and grouped selections: fill-only sources have no action, stroked sources outline while dimension artwork survives. --- crates/engine/src/cmd/pathops.rs | 28 +++++++++++------- crates/ui-egui/src/tests/contextmenu.rs | 39 +++++++++++++++++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b4312ef669..abb3acebb8 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1143,21 +1143,29 @@ pub(crate) fn outlinable(st: &StrokeLayer) -> bool { st.visible && !st.paint.is_none() && st.width > 0.0 } -/// Does Outline Stroke have a stroke to turn into art somewhere under `n`: a visible stroke of -/// some paint and weight on a path or compound path (type is not outlined by it)? -fn has_outlinable_stroke(n: &Node) -> bool { - let mut found = false; - each_leaf(n, &mut |l| { - found |= !matches!(l.kind, NodeKind::Text(_)) && l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))); - }); - found +/// Does Outline Stroke have a stroke to turn into art under `n`, outside the dimension subtrees +/// the command will keep? Guides, clipping paths and type are not outlined. +fn has_outlinable_stroke(n: &Node, kept: &[NodeId]) -> bool { + if kept.contains(&n.id) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))) + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_outlinable_stroke(c, kept)), + _ => false, + } } /// Does `object.path.outlineStroke` have a stroke to outline in `st`'s selection? It acts on the /// selection's roots (a compound path's member stands for its compound, which holds the -/// appearance), so eligibility looks at those same roots, not at the selected nodes themselves. +/// appearance), excluding the linked dimensions that the command lifts while outlining their art. pub fn can_outline_stroke(st: &crate::DocState) -> bool { - selection_roots(st).into_iter().filter_map(|id| st.doc.node(id)).any(has_outlinable_stroke) + let roots = selection_roots(st); + let kept = super::dimension::with_their_art(&st.doc, &roots); + roots.into_iter().filter_map(|id| st.doc.node(id)).any(|n| has_outlinable_stroke(n, &kept)) } /// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index d615108fb5..54b7300cb2 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -821,6 +821,45 @@ fn outline_stroke_is_offered_for_a_member_of_a_stroked_compound_path() { assert!(app.session.active().unwrap().doc.node(compound).is_none(), "the stroked compound path was replaced by its outline"); } +#[test] +fn outline_stroke_ignores_a_linked_dimensions_lines_when_its_source_is_selected() { + for grouped in [false, true] { + let mut app = app(); + let source = rect(&mut app, 50.0, 50.0); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let dimension = NodeId( + app.run("dimension.create", json!({"source": {"kind": "segment", "edge": {"node": source.0, "subpath": 0, "segment": 0}}})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + app.run("select.set", json!({"ids": [source.0, dimension.0]})).unwrap(); + if grouped { + app.run("object.group", json!({})).unwrap(); + } + let selected = app.session.active().unwrap().selection.objects.clone(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 100.0, 125.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, selected, "grouped: {grouped}"); + assert!(has(&texts, "Arrange"), "the menu opened: {texts:?}"); + assert!(!has(&texts, "Outline Stroke"), "only the protected dimension has strokes: {texts:?}"); + click(&mut app, &ctx, pos2(10.0, 590.0), PointerButton::Primary); + + app.run("paint.setStroke", json!({"ids": [source.0], "color": "#000000"})).unwrap(); + app.run("stroke.set", json!({"ids": [source.0], "weight": 6})).unwrap(); + let dimension_art = app.session.active().unwrap().doc.node(dimension).unwrap().children().unwrap().to_vec(); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Outline Stroke"), "the source has a stroke to outline: {texts:?}"); + click(&mut app, &ctx, at(&texts, "Outline Stroke"), PointerButton::Primary); + let st = app.session.active().unwrap(); + assert!(st.doc.node(source).is_none(), "the source was replaced by filled outlines"); + assert_eq!(st.doc.node(dimension).unwrap().children().unwrap(), dimension_art.as_slice(), "the dimension keeps its own art"); + } +} + /// Point type holding `t` at (20, 60), with Auto Spell Check on. fn spelled(app: &mut VectorcraftApp, t: &str) -> NodeId { let id = NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": t, "size": 24})).unwrap()["id"].as_u64().unwrap()); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8aa6ee8073..a7c8ebb9b0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > -> Outline Stroke is available in the canvas context menu when the selection has an outlinable stroke (#5267). Scores and estimates unchanged. +> Outline Stroke is available in the canvas context menu when the selection has an outlinable stroke (#5267). A linked dimension selected with its source keeps its lines; those protected lines do not make a fill-only source eligible, including inside a group. Scores and estimates unchanged. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > From 90752660adc593f619518d6882b357a0ee6fe63c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:18:50 -0800 Subject: [PATCH 024/298] Scripts: documents give scripts their variables, data sets and variable libraries A script's Document has variables, dataSets, activeDataset, variablesLocked, importVariables(file) and exportVariables(file), with the Variables, Variable, Datasets and Dataset classes and the VariableKind enumeration. Every page item has visibilityVariable, and type, placed and raster images and graphs have contentVariable. Each change runs a variable.* or dataset.* command and joins the run's undo step; a value that changes nothing runs no command. - variable.setBinding binds one object's visibility or content slot to one variable, or to none, in one undo step. - dataset.update takes a name, to update a data set that is not the active one without switching to it. - A File crosses to the host as its path under a hidden key, and a plain object that carries the key is refused. importVariables and exportVariables check the path against what the script's own File objects may read or write; the open documents' files do not count. Docs: docs/mcp.md, docs/target-app-parity.md, docs/gaps.md (G6). --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/variablecmds.rs | 89 +- crates/engine/src/file_access.rs | 3 +- crates/engine/src/script/dom.rs | 21 +- crates/engine/src/script/dom/variables.rs | 802 ++++++++++++++++++ crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_variables.rs | 433 ++++++++++ crates/js/src/file_classes.rs | 13 + crates/js/src/host.rs | 12 +- crates/js/src/host_classes.rs | 13 + crates/js/src/lib.rs | 2 +- docs/gaps.md | 3 +- docs/mcp.md | 36 +- docs/target-app-parity.md | 1 + 16 files changed, 1416 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/variables.rs create mode 100644 crates/engine/src/tests/script_variables.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..538b9e0dbf 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -952,6 +952,8 @@ pub use variablecmds::utf16_order_without_mark; /// file: its size limit, its text, its cells and the data `graph.setData` takes from them. pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +/// The kind of variable that drives an object's content (`variable.setBinding`). +pub(crate) use variablecmds::content_kind; /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..33aaab396e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -727,6 +727,7 @@ pub(super) const ALLOWED: &[&str] = &[ "variable.makeTextDynamic", "variable.makeVisibilityDynamic", "variable.rename", + "variable.setBinding", "variable.sort", "variable.unbind", ]; diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..fdd4231dc3 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -451,6 +451,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result { Ok(json!({"unbound": n})) } +/// The kind of variable that drives the content of `n`: text for type, image for an image object +/// and graph for a graph root. `None` for other objects, which have only a visibility slot. +pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option { + match &n.kind { + NodeKind::Text(_) => Some(VariableKind::Text), + NodeKind::Image(_) => Some(VariableKind::Image), + _ if n.extras().graph.is_some() => Some(VariableKind::Graph), + _ => None, + } +} + +/// The variables of `kind` bound to `id`, in the order they are defined. +fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec { + let Some(bound) = vars.bindings.get(&id) else { return Vec::new() }; + vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect() +} + +/// The slot `variable.setBinding` names: an object's visibility, or its content. +fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> { + let node = doc.node(id).ok_or(EngineError::NoNode(id))?; + match str_param(p, "slot") { + Some("visibility") => Ok(("visibility", VariableKind::Visibility)), + Some("content") => { + content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0))) + } + _ => Err(bad(cmd, "`slot` must be `visibility` or `content`")), + } +} + +/// Bind one object's visibility or content to one variable, or to none, in one undo step: the +/// object's other variables of that slot's kind are unbound. The content of type takes a text +/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded +/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing +/// changes when one fails. A call that leaves the bindings as they were adds no undo step. +fn set_binding(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.setBinding"; + let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?; + let variable = match p.get("variable") { + None | Some(Value::Null) => None, + Some(v) => Some(named(v.as_str(), "variable", C)?), + }; + let doc = &s.doc()?.doc; + let (slot, kind) = slot_kind(doc, id, p, C)?; + if let Some(name) = &variable { + let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; + if have != kind { + return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); + } + check_bindable(doc, &[id], kind, C)?; + if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); + } + } + let unbound: Vec = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect(); + let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" }; + edit_variables(s, label, |vars| { + for n in &unbound { + vars.unbind(id, n); + } + if let Some(n) = &variable { + vars.bind(id, n); + } + Ok(()) + })?; + Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound})) +} + /// The `variable` a command names, which must be defined; `None` when it names none. fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result> { let name = optional_name(p, "variable", cmd)?; @@ -690,13 +757,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// other than a visibility variable, locked or inside a locked layer or group, or, for any /// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. With every bound object locked, no value is -/// written; an update that writes no value adds no undo step. +/// update, so say so rather than picking one. `name` updates that row instead, and leaves the +/// active row as it is. With every bound object locked, no value is written; an update that +/// writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); + let given = match p.get("name") { + None => None, + Some(v) => Some(named(v.as_str(), "name", C)?), + }; let st = s.doc()?; - let Some(name) = st.doc.variables.active_dataset.clone() else { + let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else { return Err(bad(C, "no active data set")); }; if !anything_bound(&st.doc) { @@ -975,6 +1047,15 @@ pub fn specs() -> Vec { has_doc, unbind ), + cmd!( + "variable.setBinding", + "Bind Variable", + [], + None, + "{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}", + has_doc, + set_binding + ), cmd!( "variable.lock", "Lock Variables", @@ -1027,7 +1108,7 @@ pub fn specs() -> Vec { "Update Data Set", ["Window", "Variables"], None, - "{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", + "{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", has_doc, dataset_update ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..f61179f43d 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -300,7 +300,8 @@ impl ScriptGate { ScriptGate { also: Some(also), ..self.clone() } } - fn check(&self, path: &str, access: Access) -> Result<(), String> { + /// May `path` be read (or written) through this gate? + pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..a7303cf4e6 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,15 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod variables; + +pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; + +/// After each command a script runs ([`variables::after_command`]). +pub(super) fn after_command(h: &Host, id: &str) { + variables::after_command(h, id); +} + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -85,13 +94,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the `Variable` and `Dataset` objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + vars: variables::Handles, } impl State { @@ -1660,6 +1670,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + variables::define_enums(realm)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -1714,6 +1725,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(variables::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1763,7 +1775,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "tags", "uRL", "uuid", - "visibilityVariable", "wrapInside", "wrapOffset", "wrapped", @@ -1776,8 +1787,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "PageItem", m)), ); + page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(variables::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs new file mode 100644 index 0000000000..270a7cfc08 --- /dev/null +++ b/crates/engine/src/script/dom/variables.rs @@ -0,0 +1,802 @@ +//! Variables and data sets in the script object model: `Document.variables`, `dataSets`, +//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`, +//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the +//! help pages , +//! , +//! , +//! , +//! , +//! and +//! describe them. Every change runs +//! one of the `variable.*` and `dataset.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change +//! made through the object keeps the object working; once the name leaves the document any other +//! way (a delete, a rename by another command, an undo, a kind change by another command, or an +//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or +//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most +//! [`MAX_HANDLES`] of each. +//! - Collections list variables and data sets in the order the document holds them, counted from +//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`. +//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first +//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data +//! set named `Data Set 1` and so on, which becomes the active one. +//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`, +//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file +//! declared without one VectorCraft knows, and cannot be given. +//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order. +//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows +//! its values in the art, as `display()` does. +//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the +//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the +//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all. +//! An embedded image (`RasterItem`) cannot take an image variable. +//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the +//! script may read, or write, as its `File` objects may: the files of the open documents do not +//! count. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, +}; +use crate::doc::{Node, Variable, VariableKind}; +use crate::file_access::Access; + +/// The error for a `Variable` whose variable left the document, or that came from an earlier run. +pub const STALE_VARIABLE: &str = "Stale variable"; +/// The error for a `Dataset` whose data set left the document, or that came from an earlier run. +pub const STALE_DATASET: &str = "Stale data set"; +/// The most `Variable` objects, and the most `Dataset` objects, one run gives out. +pub const MAX_HANDLES: usize = 10_000; + +/// The kinds, each with the name of its `VariableKind` member. +const KINDS: [(VariableKind, &str); 5] = [ + (VariableKind::Text, "TEXTUAL"), + (VariableKind::Visibility, "VISIBILITY"), + (VariableKind::Image, "IMAGE"), + (VariableKind::Graph, "GRAPH"), + (VariableKind::Unknown, "Unknown"), +]; + +/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a +/// variable (`None` for a data set) and whether it still names it. +struct Entry { + uid: u64, + name: String, + kind: Option, + alive: bool, +} + +/// The objects of one class a run gave out: each one's handle is its index here. +#[derive(Default)] +struct Table { + entries: Vec, + /// The entry that names each document's name, while it does. + live: HashMap<(u64, String), usize>, +} + +impl Table { + /// The entry for `name` of the document `uid`, made when there is none. + fn slot(&mut self, uid: u64, name: &str, kind: Option, what: &str) -> std::result::Result { + if let Some(&at) = self.live.get(&(uid, name.to_string())) + && self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind) + { + return Ok(at); + } + if self.entries.len() >= MAX_HANDLES { + return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run"))); + } + self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true }); + let at = self.entries.len() - 1; + self.live.insert((uid, name.to_string()), at); + Ok(at) + } + + /// The entry `at` no longer names anything. + fn kill(&mut self, at: usize) { + if let Some(e) = self.entries.get_mut(at) { + e.alive = false; + let k = (e.uid, std::mem::take(&mut e.name)); + if self.live.get(&k) == Some(&at) { + self.live.remove(&k); + } + } + } + + /// The entry `at` names `name`, of `kind`, from now on: a rename made through it. + fn rename(&mut self, at: usize, name: &str, kind: Option) { + let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return }; + self.kill(at); + if let Some(e) = self.entries.get_mut(at) { + *e = Entry { uid, name: name.to_string(), kind, alive: true }; + } + self.live.insert((uid, name.to_string()), at); + } + + /// Kills each live entry `keep` refuses. + fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) { + let gone: Vec = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect(); + for at in gone { + self.kill(at); + } + } +} + +/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last +/// checked against it. +#[derive(Default)] +pub(super) struct Handles { + vars: RefCell, + sets: RefCell
, + seen: RefCell>, +} + +/// After each command a script runs: the objects whose variable or data set it removed stop +/// working, so one made again under the same name does not bring them back. A command that replaces +/// the data sets (an import) stops every `Dataset` of its document. +pub(super) fn after_command(h: &Host, id: &str) { + let hs = &h.dom.vars; + if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { + return; + } + let Ok(s) = h.session.try_borrow() else { return }; + let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); + let changed: HashSet = { + let seen = hs.seen.borrow(); + now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect() + }; + *hs.seen.borrow_mut() = now; + if changed.is_empty() && replaced.is_none() { + return; + } + let mut kinds: HashMap> = HashMap::new(); + let mut sets: HashMap> = HashMap::new(); + for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) { + let vars = &st.doc.variables; + kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect()); + sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect()); + } + hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind); + hs.sets + .borrow_mut() + .sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str())))); +} + +fn kind_text(k: VariableKind) -> Data { + let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n); + text(format!("VariableKind.{name}")) +} + +fn kind_of(d: &Data) -> std::result::Result { + let found = match d { + Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k), + _ => None, + }; + match found { + Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())), + Some(k) => Ok(k), + None => Err(HostError::Type("kind must be a VariableKind value".into())), + } +} + +/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes. +fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("the {what} is too long"))); + } + Ok(s) +} + +/// The `name` field of a command's result. +fn result_name(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }) +} + +fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer { + let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?; + Ok(host_ref("Variable", &[float(h.run), float(at as u64)])) +} + +fn set_ref(h: &Host, uid: u64, name: &str) -> Answer { + let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?; + Ok(host_ref("Dataset", &[float(h.run), float(at as u64)])) +} + +/// A variable or data set an object names: its document, its handle's index and its name. +struct Named { + doc: Doc, + at: usize, + name: String, + kind: Option, +} + +/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its +/// document. +fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result { + let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) }; + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let stale = || HostError::Error(stale.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?; + let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets }; + let (uid, name, kind) = { + let t = table.borrow(); + let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?; + (e.uid, e.name.clone(), e.kind) + }; + let doc = find_doc(h, float(h.run), float(uid)); + let there = doc.is_some_and(|doc| { + with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() } + }) + }); + match doc { + Some(doc) if there => Ok(Named { doc, at, name, kind }), + _ => { + table.borrow_mut().kill(at); + Err(stale()) + } + } +} + +fn this_var(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), true) +} + +fn this_set(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), false) +} + +/// The index argument of a collection's indexer: a whole number, or `None`. +fn index_arg(d: &Data) -> Option { + match d { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_variables(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Variables", &[float(h.run), float(doc.uid)])) +} + +fn doc_datasets(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)])) +} + +fn doc_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked))) +} + +/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so. +fn doc_set_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) }; + if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked { + on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?; + } + Ok(Data::Undefined) +} + +fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Null), + } +} + +/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active +/// one and the art already shows it. +fn display(h: &Host, set: &Named) -> Answer { + let shown = with_doc(h, set.doc, |_, st| { + let vars = &st.doc.variables; + vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values())) + }); + if !shown { + on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?; + } + Ok(Data::Undefined) +} + +fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + if handle_of(arg(a, 1), "Dataset").is_none() { + return Err(HostError::Type("activeDataset must be a Dataset".into())); + } + let set = named_of(h, arg(a, 1), false)?; + if set.doc.uid != doc.uid { + return Err(HostError::Error("the data set is in another document".into())); + } + display(h, &set) +} + +/// The path of the `File` argument of `what`, which must be a file the script may reach for +/// `access` through its own `File` objects. +fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result { + let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) }; + if path.chars().count() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(format!("{what}: the path is too long"))); + } + let gate = h.disk.borrow().gate(Vec::new()); + gate.check(path, access).map_err(HostError::Error)?; + Ok(path.to_string()) +} + +/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's +/// variables and data sets with the library's. +fn doc_import(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "importVariables", Access::Read)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +/// `exportVariables(file)`: `variable.saveLibrary` into the file. +fn doc_export(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "exportVariables", Access::Write)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +// ---- Variables ---- + +fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Variables") +} + +fn vars_typename(h: &Host, a: &[Data]) -> Answer { + vars_doc(h, a)?; + Ok(text("Variables")) +} + +fn vars_length(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64))) +} + +fn vars_parent(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn vars_at(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) { + Some(v) => var_ref(h, doc.uid, &v), + None => Ok(Data::Undefined), + } +} + +fn vars_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.variables.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.variable(name).cloned()) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v)) +} + +fn vars_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => vars_by_name(h, a), + Data::Number(_) => match vars_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the +/// first free name). → the new variable. +fn vars_add(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + (1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default() + }); + on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?; + var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text }) +} + +/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is +/// none. +fn vars_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Variable ---- + +fn var_typename(h: &Host, a: &[Data]) -> Answer { + this_var(h, a)?; + Ok(text("Variable")) +} + +fn var_parent(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(doc_ref(h, v.doc.uid)) +} + +fn var_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_var(h, a)?.name)) +} + +/// `name = text`: `variable.rename`, which trims it, with no command when the name stays. +fn var_set_name(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == v.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind); + Ok(Data::Undefined) +} + +fn var_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown))) +} + +/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot +/// hold it and drops the variable's values, with no command when the kind stays. +fn var_set_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let kind = kind_of(arg(a, 1))?; + if Some(kind) == v.kind { + return Ok(Data::Undefined); + } + on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?; + h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind)); + Ok(Data::Undefined) +} + +fn var_page_items(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + with_doc(h, v.doc, |_, st| { + let ids: Vec = + st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) + }) +} + +/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values. +fn var_remove(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?; + h.dom.vars.vars.borrow_mut().kill(v.at); + Ok(Data::Undefined) +} + +// ---- Datasets ---- + +fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Datasets") +} + +fn sets_typename(h: &Host, a: &[Data]) -> Answer { + sets_doc(h, a)?; + Ok(text("Datasets")) +} + +fn sets_length(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64))) +} + +fn sets_parent(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn sets_at(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Undefined), + } +} + +fn sets_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.datasets.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone())) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n)) +} + +fn sets_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sets_by_name(h, a), + Data::Number(_) => match sets_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new +/// data set and makes it the active one. → the new data set. +fn sets_add(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?; + let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?; + set_ref(h, doc.uid, &name) +} + +/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is +/// none. +fn sets_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Dataset ---- + +fn set_typename(h: &Host, a: &[Data]) -> Answer { + this_set(h, a)?; + Ok(text("Dataset")) +} + +fn set_parent(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + Ok(doc_ref(h, d.doc.uid)) +} + +fn set_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_set(h, a)?.name)) +} + +/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays. +fn set_set_name(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == d.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.sets.borrow_mut().rename(d.at, &name, None); + Ok(Data::Undefined) +} + +fn set_display(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + display(h, &d) +} + +/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no +/// command when it already holds what the bound objects hold. +fn set_update(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let same = with_doc(h, d.doc, |_, st| { + let doc = &st.doc; + let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()); + bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values())) + }); + if !same { + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?; + } + Ok(Data::Undefined) +} + +/// `dataset.remove()`: `dataset.delete` of this data set. +fn set_remove(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?; + h.dom.vars.sets.borrow_mut().kill(d.at); + Ok(Data::Undefined) +} + +// ---- Page items ---- + +/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its +/// content. +fn slot_kind(n: &Node, content: bool) -> std::result::Result { + if !content { + return Ok(VariableKind::Visibility); + } + crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into())) +} + +/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's +/// kind bound to the object, in the order the variables are defined, or `null`. +fn binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let found = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned()) + })?; + match found { + Some(v) => var_ref(h, item.doc.uid, &v), + None => Ok(Data::Null), + } +} + +/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of +/// the object's document, or with none for `null`. No command runs when the object already has just +/// that binding of the slot's kind. +fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let variable = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "Variable").is_some() => { + let v = named_of(h, d, true)?; + if v.doc.uid != item.doc.uid { + return Err(HostError::Error("the variable is in another document".into())); + } + Some(v.name) + } + _ => return Err(HostError::Type("give a Variable or null".into())), + }; + let same = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + let held: Vec<&str> = + vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect(); + Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::>()) + })?; + if !same { + let slot = if content { "content" } else { "visibility" }; + edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?; + } + Ok(Data::Undefined) +} + +fn item_visibility(h: &Host, a: &[Data]) -> Answer { + binding(h, a, false) +} + +fn item_set_visibility(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, false) +} + +fn item_content(h: &Host, a: &[Data]) -> Answer { + binding(h, a, true) +} + +fn item_set_content(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, true) +} + +// ---- Registration ---- + +/// The members this module adds to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("variables", get(l, doc_variables)), + ("dataSets", get(l, doc_datasets)), + ("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)), + ("variablesLocked", property(l, doc_locked, doc_set_locked)), + ("importVariables", method(l, doc_import)), + ("exportVariables", method(l, doc_export)), + ]) +} + +/// The members this module adds to `PageItem`. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))]) +} + +/// The members this module adds to the page item class `class`. +pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> { + match class { + "TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]), + _ => Vec::new(), + } +} + +/// The classes this module adds. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "Variables", + None, + named(vec![ + ("typename", get(l, vars_typename)), + ("length", get(l, vars_length)), + ("parent", get(l, vars_parent)), + ("index", method(l, vars_index)), + ("getByName", method(l, vars_by_name)), + ("add", method(l, vars_add)), + ("removeAll", method(l, vars_remove_all)), + ]), + Some(function(l, vars_at)), + ), + class( + "Variable", + None, + named(vec![ + ("typename", get(l, var_typename)), + ("parent", get(l, var_parent)), + ("name", property(l, var_name, var_set_name)), + ("kind", property(l, var_kind, var_set_kind)), + ("pageItems", get(l, var_page_items)), + ("remove", method(l, var_remove)), + ]), + None, + ), + class( + "Datasets", + None, + named(vec![ + ("typename", get(l, sets_typename)), + ("length", get(l, sets_length)), + ("parent", get(l, sets_parent)), + ("index", method(l, sets_index)), + ("getByName", method(l, sets_by_name)), + ("add", method(l, sets_add)), + ("removeAll", method(l, sets_remove_all)), + ]), + Some(function(l, sets_at)), + ), + class( + "Dataset", + None, + named(vec![ + ("typename", get(l, set_typename)), + ("parent", get(l, set_parent)), + ("name", property(l, set_name, set_set_name)), + ("display", method(l, set_display)), + ("update", method(l, set_update)), + ("remove", method(l, set_remove)), + ]), + None, + ), + ] +} + +/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings. +pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect(); + realm.define_host_object("VariableKind", items) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..0780a34e98 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1346,6 +1346,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + dom::after_command(host, &id); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..f62236f90f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_variables; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs new file mode 100644 index 0000000000..e60afb03d2 --- /dev/null +++ b/crates/engine/src/tests/script_variables.rs @@ -0,0 +1,433 @@ +//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the +//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::tests_links::{Folder, RED, place, png, write}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A document with a type object and a rectangle. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + (s, t, r) +} + +fn variables(s: &Session) -> Vec<(String, &'static str)> { + s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect() +} + +#[test] +fn variables_collection_adds_finds_renames_and_removes() { + let (mut s, _, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var v = app.activeDocument.variables; + vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename); + var a = v.add(), b = v.add(); + vc.log([a.name, b.name, a.kind, v.length].join()); + b.name = 'title'; b.kind = VariableKind.VISIBILITY; + vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join()); + vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined); + a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#, + ); + assert_eq!( + out, + vec![ + json!(0), + json!("Variables"), + json!("Document"), + json!("Variable1,Variable2,VariableKind.TEXTUAL,2"), + json!("title,VariableKind.VISIBILITY,title,Variable1,title"), + json!(true), + json!(1), + json!("Document,Variable") + ] + ); + assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index")); +} + +#[test] +fn variable_names_and_kinds_are_checked_before_anything_changes() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown")); + let long = "x".repeat(5000); + assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long")); + // Setting what the variable already has runs no command. + log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;"); + assert_eq!(undo_steps(&s), before); + assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]); +} + +#[test] +fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var v = app.activeDocument.variables.add();\ + vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\ + v.name;", + ); + assert!(e.contains("Stale variable"), "{e}"); + // A failed run keeps nothing, so the variable is defined outside the script. + s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap(); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;"); + assert!(e.contains("Stale variable"), "{e}"); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;"); + assert!(e.contains("Stale variable"), "{e}"); + // A rename through the object keeps it. + assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap(); + let e = failure(&mut s, "#targetengine keepvars\nheld.name;"); + assert!(e.contains("Stale variable"), "{e}"); +} + +#[test] +fn collections_from_an_earlier_run_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap(); + for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] { + let e = failure(&mut s, &format!("#targetengine keepcols\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn content_and_visibility_variables_bind_one_variable_per_slot() { + let (mut s, t, r) = doc(); + for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1]; + vc.log(t.contentVariable === null && t.visibilityVariable === null); + t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other'); + r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide'); + vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name); + vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename); + vc.log(r.contentVariable === undefined);"#, + ); + assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["other".to_string()])); + assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::>()), Some(vec!["hide".to_string()])); + assert_eq!(undo_steps(&s), before + 1); + // A variable of another kind is refused, and nothing changes; null unbinds that slot only. + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');"); + assert!(e.contains("visibility variable"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');"); + assert!(e.contains("text variable"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null")); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["show".to_string()])); + // Assigning the binding the object already has runs no command. + let steps = undo_steps(&s); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn an_embedded_image_cannot_take_an_image_variable() { + let dir = Folder::new("script-vars-embedded"); + let path = dir.file("red.png"); + write(&path, &png(10, 10, RED)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = place(&mut s, &path); + s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);"); + assert_eq!(out, vec![json!("photo")]); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); + assert!(e.contains("embedded image"), "{e}"); + assert!(s.active().unwrap().doc.variables.bindings.is_empty()); +} + +#[test] +fn data_sets_capture_display_update_and_remove() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, sets = d.dataSets; + vc.log(sets.length + ',' + (d.activeDataset === null)); + var one = sets.add(); + vc.run('text.setText', {id: TEXT_ID, text: 'World'}); + var two = sets.add(); + vc.log([one.name, two.name, sets.length, d.activeDataset.name].join()); + one.display(); vc.log(d.activeDataset.name); + vc.run('text.setText', {id: TEXT_ID, text: 'Again'}); + two.update(); vc.log(d.activeDataset.name); + two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name); + d.activeDataset = two; vc.log(d.activeDataset.name); + one.remove(); vc.log(sets.length);"# + .replace("TEXT_ID", &t.0.to_string()) + .as_str(), + ); + assert_eq!( + out, + vec![ + json!("0,true"), + json!("Data Set 1,Data Set 2,2,Data Set 2"), + json!("Data Set 1"), + json!("Data Set 1"), + json!("Second,Second"), + json!("Second"), + json!(1) + ] + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.datasets.len(), 1); + assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("Second")); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); + log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();"); + assert!(s.active().unwrap().doc.variables.datasets.is_empty()); + assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset")); +} + +#[test] +fn update_of_a_data_set_that_holds_the_art_runs_no_command() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap(); + assert_eq!(undo_steps(&s), before); + assert_eq!(r["slowestCommands"], json!([]), "{r}"); +} + +#[test] +fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn variables_locked_refuses_new_variables_but_not_bindings() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\ + d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);", + ); + assert_eq!(out, vec![json!(false), json!(true)]); + assert!(s.active().unwrap().doc.variables.locked); + let e = failure(&mut s, "app.activeDocument.variables.add();"); + assert!(e.contains("locked"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false")); + assert_eq!(variables(&s).len(), 1); +} + +/// A variable library of two variables and two data sets, written for these tests from the elements +/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of +/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements +/// with `dataSetName`. +const LIBRARY: &str = r#" + + + + + + + + <p>Hello</p>true + <p>World</p>false + + + +"#; + +/// A fresh folder with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// Runs `main/main.jsx` in `base` with `text`, on `s`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +#[test] +fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() { + let base = folder("import"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let r = run_file( + &mut s, + &base, + "var d = app.activeDocument; d.importVariables(new File('lib.xml'));\ + vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\ + d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!(["2,2,Two", "title"])); + assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]); + assert_eq!(s.active().unwrap().doc.story_text(t), "World"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn import_variables_takes_only_a_file_the_script_may_read() { + let base = folder("import-refused"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + std::fs::write(base.join("outside.xml"), LIBRARY).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string(); + assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File")); + assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File")); + let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/"); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));")); + assert!(e.contains("access denied"), "{e}"); + // The open document's own file is refused, though the script's commands may open it. + let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/"))); + assert!(e.contains("access denied"), "{e}"); + // A plain object cannot pass for a File. + let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);"); + assert!(e.contains("not plain data"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn import_variables_refuses_hostile_libraries_before_any_edit() { + let base = folder("import-hostile"); + let external = r#"]>"#; + std::fs::write(base.join("main/external.xml"), external).unwrap(); + let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + std::fs::write(base.join("main/deep.xml"), deep).unwrap(); + let mut big = LIBRARY.as_bytes().to_vec(); + big.resize((8 << 20) + 1, b' '); + std::fs::write(base.join("main/big.xml"), big).unwrap(); + let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\""); + std::fs::write(base.join("main/twice.xml"), twice).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] { + let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string(); + assert!(e.contains(says), "{file}: {e}"); + } + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); + assert_eq!(undo_steps(&s), before); + // Locked variables refuse a library that would delete or define one. + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn export_variables_writes_a_library_that_import_reads_back() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\ + d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\ + d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);", + ); + let xml = out[0].as_str().unwrap(); + for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "

Hello

"] { + assert!(xml.contains(part), "{part} in {xml}"); + } + assert_eq!(out[1], json!("title,Row")); +} + +#[test] +fn export_variables_writes_only_where_the_script_may_write() { + let base = folder("export-refused"); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + // The open document's own file is refused, though the script's commands may save it. + let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let before = std::fs::read(&saved).unwrap(); + let path = saved.replace('\\', "/"); + let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert_eq!(std::fs::read(&saved).unwrap(), before); + // The script's own folder is only read. + let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert!(!base.join("main/out.xml").exists()); + assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File")); + // A library that cannot be written leaves no file. + s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap(); + let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));"); + assert!(e.contains("can't be saved"), "{e}"); + let out = + log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);"); + assert_eq!(out, vec![json!(false)]); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..59f385cabb 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose +/// path is in its own slot. `None` for anything else, a `Folder` included. +pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { + let Some(c) = &i.files else { return Ok(None) }; + if i.object(id)?.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match slot(i, id, PATH)? { + Value::String(s) => Some(s.to_rust_string()), + _ => None, + }) +} + fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..26ab1e14ed 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -190,8 +190,8 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, - /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object - /// that has [`crate::HOST_REF_KEY`] is refused. + /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under + /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. hosted: bool, } @@ -261,6 +261,12 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + if r.hosted + && let Some(path) = crate::file_classes::file_path(self, id)? + { + self.charge_reading(r, path.len().saturating_add(16))?; + return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))])); + } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => { return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); @@ -313,7 +319,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..4a790957c6 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -110,6 +110,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data { Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) } +/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host +/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d`, an argument of a host class's member, stands for. +pub fn file_ref_path(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + /// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { let Data::Object(items) = d else { return None }; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..e3141d9e0f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -82,7 +82,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, host_ref, host_ref_parts}; 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, SourceLocator, UNKNOWN_SOURCE}; diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..4c92dafa13 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and each document's variables, data sets and variable + libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, 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 diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..2d35d2d0b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,29 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and + `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` + (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` + (https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/) have `length`, `parent`, `[i]`, `index(key)`, + `getByName(name)`, `add()` and `removeAll()`. A `Variable` (https://ai-scripting.docsforadobe.dev/jsobjref/Variable/) + has `name`, `kind`, `pageItems` and `remove()`, and a `Dataset` (https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/) + has `name`, `display()`, `update()` and `remove()`. Every page item has `visibilityVariable`, and a `TextFrame`, + `PlacedItem`, `RasterItem` or `GraphItem` has `contentVariable` as well + (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each change runs a `variable.*` or `dataset.*` command: + `variables.add()` runs `variable.define` of a text variable named `Variable1`, `Variable2` and so on (the first free + name), `dataSets.add()` runs `dataset.capture`, `display()` and assigning `activeDataset` run `dataset.select`, + `update()` runs `dataset.update {name}`, assigning `visibilityVariable` or `contentVariable` runs + `variable.setBinding`, `importVariables` runs `variable.loadLibrary` and `exportVariables` runs + `variable.saveLibrary`. `kind` is one of the strings of the enumeration `VariableKind` + (`"VariableKind.TEXTUAL"`, `VISIBILITY`, `IMAGE`, `GRAPH` and `Unknown`); `Unknown` cannot be assigned. + VectorCraft's own rules: a `Variable` or `Dataset` names its variable or data set by name. A rename made through + it keeps it working; once the name leaves the document any other way (a delete, an undo, a rename or kind change by + another command, or an import that replaces the data sets), it throws `Stale variable` or `Stale data set`, also + after the name comes back. A run gives out at most 10,000 of each. `visibilityVariable` and `contentVariable` give + the first bound variable of their kind in the order the variables were defined, or `null`, and `null` unbinds. + `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or + write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs + no command. - `$.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 @@ -4267,7 +4290,13 @@ already walks Image Trace. Short agent entry points: defined in. Names compare without regard to case; by object, unbound variables come first and variables bound to several objects last, and ties go by name. Another `by` value, or a `descending` that is not true or false, is an error. The sort is panel state, not saved and not an undo step; `variable.list` lists the variables in - that order and reports it as `sort: {by, descending}`. + that order and reports it as `sort: {by, descending}`. `variable.setBinding {id, slot: visibility|content, + variable?}` binds one object to `variable` for one slot and unbinds the object's other variables of that slot's + kind: `visibility` takes a visibility variable, and `content` the kind that drives the object (text for type, image + for a linked image, graph for a graph). Without `variable`, or with null, it unbinds them all. A variable of + another kind, an object of no content kind, and an embedded image for an image variable are errors, and nothing + changes. One undo step, and none when the object already has just that binding → `{id, slot, variable, + unbound}`. - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / @@ -5038,8 +5067,9 @@ locked; `skipped` counts those objects. A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. -`dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the -data set holds. A variable whose objects report no value, because they are deleted or, for a text, image or graph +`dataset.update {all?, name?}` writes what the bound objects hold now into the active data set, for each variable that +the data set holds. With `name`, it writes into that data set instead and the active data set stays as it is; a +`name` that is not a string, or names no data set, is an error. A variable whose objects report no value, because they are deleted or, for a text, image or graph variable, locked or inside a locked layer or group, or for any variable on a locked artboard, keeps the data set's value. With `all: true` it also adds every other variable that the objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..a760266f23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.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: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6db0f6c1adef609bba16c8eec4ce0a37e178d2ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:15:47 -0800 Subject: [PATCH 025/298] Scripts: visibility variables on embedded images, data sets kept after a no-op import - variable.setBinding refuses an embedded image only for an image variable, so a script can bind an embedded image's visibility. - A Dataset object stays usable after dataset.import, variable.loadLibrary or variable.import leaves the document's data sets as they were, or the import is put back; it goes stale only when the data sets change. - script.check reports a document's exportVariables as filesWritten and file.write, and the script host test lists the variable and data set names the host adds. Docs: docs/mcp.md. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/script/dom.rs | 10 +++++++-- crates/engine/src/script/dom/variables.rs | 22 ++++++++++++++----- crates/engine/src/script/mod.rs | 3 ++- crates/engine/src/tests/script_variables.rs | 19 ++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/catalog.rs | 3 +++ crates/scriptcheck/src/tests.rs | 8 +++++++ docs/mcp.md | 7 +++--- 10 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index fdd4231dc3..28022865e6 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -500,7 +500,7 @@ fn set_binding(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); } check_bindable(doc, &[id], kind, C)?; - if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a7303cf4e6..7e46779791 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,9 +42,15 @@ mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + /// After each command a script runs ([`variables::after_command`]). -pub(super) fn after_command(h: &Host, id: &str) { - variables::after_command(h, id); +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); } /// The error for a member read or called with no document open. diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs index 270a7cfc08..d36c9f1f45 100644 --- a/crates/engine/src/script/dom/variables.rs +++ b/crates/engine/src/script/dom/variables.rs @@ -46,7 +46,7 @@ use super::{ Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, }; -use crate::doc::{Node, Variable, VariableKind}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; use crate::file_access::Access; /// The error for a `Variable` whose variable left the document, or that came from an earlier run. @@ -138,16 +138,28 @@ pub(super) struct Handles { seen: RefCell>, } +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + /// After each command a script runs: the objects whose variable or data set it removed stop -/// working, so one made again under the same name does not bring them back. A command that replaces -/// the data sets (an import) stops every `Dataset` of its document. -pub(super) fn after_command(h: &Host, id: &str) { +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { let hs = &h.dom.vars; if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { return; } let Ok(s) = h.session.try_borrow() else { return }; - let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); let changed: HashSet = { let seen = hs.seen.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0780a34e98..39acd9897b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1313,6 +1313,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1346,7 +1347,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } - dom::after_command(host, &id); + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs index e60afb03d2..5ff2301bbf 100644 --- a/crates/engine/src/tests/script_variables.rs +++ b/crates/engine/src/tests/script_variables.rs @@ -188,6 +188,13 @@ fn an_embedded_image_cannot_take_an_image_variable() { let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); assert!(e.contains("embedded image"), "{e}"); assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); } #[test] @@ -259,6 +266,18 @@ fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { assert!(e.contains("Stale data set"), "{e}"); } +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + #[test] fn variables_locked_refuses_new_variables_but_not_bindings() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..4519f35c5e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -70,6 +71,23 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + // Variables and data sets. `importVariables` reads the library file it is given. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("PageItem.prototype.", "visibilityVariable visibilityVariable="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..eef0fb77c1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -301,7 +301,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..940b1db4e0 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -72,6 +72,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..1f4c9f3e70 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,14 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 2d35d2d0b9..7d454966ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,9 +2558,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, - `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, - `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `exportVariables`), + `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), + `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` + (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper From ee7576975ed005cac23c428c3de33ec47cb55050 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:10:19 -0800 Subject: [PATCH 026/298] Scripts: the script check counts exportVariables named in brackets as a file write doc['exportVariables'](f) now reports file.write and filesWritten on its line, as the dot form does. Reading the method without calling it reports nothing. --- crates/scriptcheck/src/analyze/features.rs | 10 ++++++++++ crates/scriptcheck/src/tests.rs | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index eef0fb77c1..b7630e064b 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -287,6 +287,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1f4c9f3e70..785ebf6c62 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -538,6 +538,21 @@ fn export_variables_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); } +/// `exportVariables` called with its name as a string literal in brackets writes the file too; +/// reading the method without calling it does not. +#[test] +fn export_variables_in_brackets_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['importVariables'](f);\n", + "app.activeDocument[\"exportVariables\"](f);\n", + "var d = app.activeDocument; d['exportVariables'] (f);\n", + "var n = d['exportVariables'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From e67211f07036a29014aeec2e27179b7488d416ab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:17:06 -0800 Subject: [PATCH 027/298] Fix #8583: document tab titles draw in a condensed face, so more tabs fit Desktop builds with a craft-fonts checkout that has Noto Sans Condensed SemiBold in its opt-in Latin catalog (fonts/latin-manifest.txt) embed that one face as vectorcraft_text::CONDENSED_UI_FONT. Tab titles draw in a new theme::FONT_TAB family headed by it, scaled to the x-height of the interface's semibold face, with the semibold faces after it on its baseline. In a 1280 pt window, 9 tabs named "Poster draft N" fit whole instead of 8. Without CRAFT_FONTS_DIR, on the web, or with a checkout that lacks the row (a build warning), FONT_TAB is the semibold family and tabs look as before. The tab tests that count tabs measure in the semibold face. --- crates/text/build.rs | 71 +++++++++++++++++++----- crates/text/src/craft_fonts.rs | 3 + crates/text/src/lib.rs | 11 +++- crates/ui-egui/src/chrome/tabs.rs | 9 +-- crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/tests/tab_overflow.rs | 41 +++++++++++++- crates/ui-egui/src/theme.rs | 53 +++++++++++++++++- crates/ui-egui/src/ui_fonts.rs | 2 +- docs/development.md | 6 ++ docs/ui-parity.md | 1 + 10 files changed, 171 insertions(+), 27 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 5402ddbe07..5979c6557c 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -12,6 +12,10 @@ //! `fonts//` beside the wasm instead of embedding (`cargo xtask web-fonts` copies them //! there; `apps/vectorcraft-web/src/fonts.rs` fetches them). A list line the manifest lacks is left //! out with a warning, never an error, and never costs the desktop its fonts. +//! +//! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in +//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A +//! checkout without that row leaves it `None` with a warning, never an error. use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -25,7 +29,7 @@ fn main() { println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); - let (mut fonts, mut web) = (String::new(), String::new()); + let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { let dir = from_workspace(dir); match craft_fonts(&dir) { @@ -48,8 +52,16 @@ fn main() { Err(e) if required => println!("cargo::error=web-fonts.txt: {e}"), Err(e) => println!("cargo::warning=web build fetches no craft fonts: web-fonts.txt: {e}"), } + if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { + match condensed_ui_font(&dir) { + Ok(entry) => condensed = format!("Some({entry})"), + Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + } + } } - let src = format!("pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\n"); + let src = format!( + "pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\npub static CONDENSED_UI_FONT: Option = {condensed};\n" + ); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); // Unchanged output keeps its mtime. Rewritten just before this crate compiles, it can read as // newer than that compile where cargo's recorded times lose their sub-second part (ecryptfs @@ -91,23 +103,52 @@ fn craft_fonts(dir: &Path) -> Result { if wasm && !(*family == WEB_FONT.0 && *style == WEB_FONT.1) { continue; } - let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; - // The manifest is supplier data: embed only regular files inside the checkout. - if !path.starts_with(&root) || !path.is_file() { - return Err(format!("{file}: not a file inside the font checkout")); - } - println!("cargo::rerun-if-changed={}", path.display()); - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); - let _ = writeln!( - out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", - scripts.join(", "), - path.display().to_string(), - ); + let _ = writeln!(out, " {},", craft_font(dir, &root, family, style, file, scripts)?); } Ok(out) } +/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { + let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } + println!("cargo::rerun-if-changed={}", path.display()); + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + Ok(format!( + "CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }}", + scripts.join(", "), + path.display().to_string(), + )) +} + +/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in +/// Latin catalog. +const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. +fn condensed_ui_font(dir: &Path) -> Result { + let manifest = dir.join("fonts/latin-manifest.txt"); + // A checkout without the catalog is watched through its folder, so the build runs again once + // the catalog appears. + let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; + println!("cargo::rerun-if-changed={}", watched.display()); + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; + let row = text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); + let Some([family, style, file, scripts, ..]) = row.as_deref() else { + return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + }; + craft_font(dir, &root, family, style, file, scripts) +} + /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and /// the listed faces the manifest lacks (an older craft-fonts checkout), which are left out. fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 24eef3de40..68ddc548b9 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -3,6 +3,9 @@ //! Built with `CRAFT_FONTS_DIR=`, [`CRAFT_FONTS`] holds every font in its //! manifest (Japanese UI and document fonts, Arabic fonts and Noto Sans Thai); built without it, //! it is empty and that text falls back to the installed system fonts. Release builds always set it. See `build.rs`. +//! [`CONDENSED_UI_FONT`] is the condensed face document tab titles draw in, from the checkout's +//! opt-in Latin catalog: `None` on wasm32, without `CRAFT_FONTS_DIR`, or with a checkout that +//! lacks it. /// A font from the optional craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`). pub struct CraftFont { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..2028639af4 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -37,7 +37,7 @@ pub mod thread; pub use bitmap::GlyphImage; pub use context_alternates::{ContextAlternate, ContextAlternates, alternate_changes, alternates_in_context, is_alternate_feature}; -pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; +pub use craft_fonts::{CONDENSED_UI_FONT, CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; @@ -1059,6 +1059,15 @@ pub fn line_metrics(data: &[u8], index: u32) -> Option<(f32, f32, f32, f32)> { Some((f32::from(m.units_per_em.max(1)), m.ascent, m.descent, m.leading)) } +/// The x-height of the font at `index` of `data`, at its default axis settings, in ems. `None` if +/// the font can't be read or gives no x-height. +pub fn x_height(data: &[u8], index: u32) -> Option { + use skrifa::MetadataProvider; + let f = skrifa::FontRef::from_index(data, index).ok()?; + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..1aff4fe1a9 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -190,7 +190,8 @@ fn tab_close_box(ui: &Ui, t: &Tokens, xr: egui::Rect, w: f32, id: egui::Id) -> O /// (#746). The first tab that doesn't fit whole fills the room left before the » button with its /// title shortened, when that room holds some of the title (#8584). When the active tab is among /// the last ones and the tabs from it to the end leave room, the tab before them fills that room -/// instead. An active tab wider than the whole strip is shortened to it. +/// instead. An active tab wider than the whole strip is shortened to it. Titles draw in +/// [`theme::FONT_TAB`], a condensed face in builds with craft-fonts (#8583). /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] @@ -224,7 +225,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::semibold(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); (w, text, title, galley) }) .collect(); @@ -258,7 +259,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::semibold(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..7954785e30 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1498,6 +1498,7 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_UI.into()), egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), + egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index 59af211e17..c9f9edec0a 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -44,6 +44,12 @@ fn frame_sized(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, texts } +/// The interface fonts with tab titles in the semibold face, as in a build without craft-fonts' +/// condensed face: the tab counts below are measured in it. +fn install_semibold_tab_fonts(ctx: &egui::Context) { + ctx.set_fonts(crate::theme::interface_fonts_with(None)); +} + fn click(at: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } } @@ -61,7 +67,7 @@ fn the_tab_that_does_not_fit_whole_fills_the_rest_of_the_strip() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -100,7 +106,7 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -118,6 +124,35 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { assert!(texts.iter().any(|(t, _)| t == "Tab test 2 @ 100 % (RGB/Preview)"), "the tooltip shows the whole title: {texts:?}"); } +/// With craft-fonts' condensed face, tab titles draw in it at the semibold face's x-height, and +/// more tabs fit whole in the strip of a 1280 pt window than with the semibold face (#8583). +#[test] +fn tab_titles_in_the_condensed_face_fit_more_tabs() { + let Some(condensed) = vectorcraft_text::CONDENSED_UI_FONT.as_ref() else { + eprintln!("skipped: built without craft-fonts' condensed face (set CRAFT_FONTS_DIR to a craft-fonts checkout that has it)"); + return; + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..24 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Poster draft {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + let mut whole_tabs = |face: Option<&vectorcraft_text::CraftFont>| { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(face)); + let texts = frame_sized(&mut app, &ctx, egui::vec2(1280.0, 700.0), 0.0, vec![]); + let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); + // The height of an x, in the tab font and in semibold text. + let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; + (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + }; + let (semibold, _, _) = whole_tabs(None); + let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); + assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); + assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + /// With the last document active, the tabs from it to the end leave room before the » button, and /// the tab before them fills that room with its title shortened instead of the strip ending short /// of the » button (#8584). @@ -132,7 +167,7 @@ fn with_the_last_document_active_the_tab_before_the_shown_ones_fills_the_room() app.session.set_active(7); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f539ddbe71..11e8af8e22 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -494,16 +494,29 @@ pub fn strong_selected_text(ui: &mut egui::Ui) { pub const FONT_UI: &str = "ui"; pub const FONT_UI_SEMIBOLD: &str = "ui-semibold"; pub const FONT_MONO: &str = "mono"; +/// The family document tab titles draw in. In a build with craft-fonts' condensed face +/// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the +/// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so +/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } +/// A document tab's title font ([`FONT_TAB`]). +pub fn tab_font(size: f32) -> FontId { + FontId::new(size, FontFamily::Name(FONT_TAB.into())) +} +/// Whether `family` draws semibold text and takes the bold fallback faces. +pub(crate) fn is_semibold(family: &FontFamily) -> bool { + matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) +} pub fn mono(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_MONO.into())) } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -520,6 +533,11 @@ pub fn install_fonts(ctx: &egui::Context) { /// whether egui applied them at once or deferred them to the next pass (it must not take input /// or draw with fallback metrics while they are pending). pub fn interface_fonts() -> FontDefinitions { + interface_fonts_with(vectorcraft_text::CONDENSED_UI_FONT.as_ref()) +} + +/// [`interface_fonts`] with `condensed` as the face that heads [`FONT_TAB`]. +pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFont>) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let (ui, semi, mono) = interface_faces(&mut fonts); let stack = |fonts: &FontDefinitions, family: FontFamily| fonts.families.get(&family).cloned().unwrap_or_default(); @@ -529,13 +547,42 @@ pub fn interface_fonts() -> FontDefinitions { let family = |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); - fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), family(semi, &fallback)); + let semi = family(semi, &fallback); + let tab = tab_faces(&mut fonts, &semi, condensed); + fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); fonts } +/// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first +/// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its +/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { + let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); + let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; + let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let name = craft_font_name(f); + let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); + // `baseline_copies` reads the head of each family it is given: here only this one. + let mut row = FontDefinitions::empty(); + row.font_data.insert(name.clone(), Arc::new(head.clone())); + row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + let mut faces = vec![name.clone()]; + for face in semi { + let Some(data) = fonts.font_data.get(face).cloned() else { continue }; + for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + fonts.font_data.insert(copy.clone(), Arc::new(data)); + faces.push(copy); + } + } + fonts.font_data.insert(name, Arc::new(head)); + faces +} + /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace /// faces that head their families, in order. #[cfg(feature = "interface-fonts")] @@ -587,7 +634,7 @@ fn add_craft_fonts(fonts: &mut FontDefinitions) { } } for (family, stack) in fonts.families.iter_mut() { - let bold = *family == FontFamily::Name(FONT_UI_SEMIBOLD.into()); + let bold = is_semibold(family); let copy = |f: &vectorcraft_text::CraftFont| { let name = craft_font_name(f); copies.get(&(family.clone(), name.clone())).cloned().unwrap_or(name) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 73c1a30891..cb419067e1 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -454,7 +454,7 @@ mod tests { let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, egui::Color32::WHITE)).rows[0].glyphs.clone(); for family in families { - let semibold = family == FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()); + let semibold = crate::theme::is_semibold(&family); for &(regular, bold, c) in &probes { let face = if semibold { bold } else { regular }; for size in [13.0_f32, 24.0, 40.0] { diff --git a/docs/development.md b/docs/development.md index fb30fad2bb..66f925324e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -174,6 +174,12 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- Noto Sans Georgian for the Georgian interface), after the UI fonts and before the installed fonts `ui_fonts.rs` discovers for other scripts. On the web, Noto Sans Georgian is fetched at startup and reaches the UI through `ui_fonts.rs`. +- Document tab titles: on desktop builds, `crates/text/build.rs` also reads one row of the + checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as + `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the + x-height of the interface's semibold face, so more tabs fit in the strip. Without + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab + titles draw in the semibold face. - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..8b5a9f315a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,6 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From 2400aa7712cd7be374ef957fdd4b6caa470293ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:51:26 -0800 Subject: [PATCH 028/298] Scripts: reflect describes an object's properties and methods Every object now has a read-only reflect property. Each read gives a new frozen reflection with the class name, the properties and methods as entries (name, type, dataType, defaultValue, min, max, isCollection, arguments), and find(name). - app, its documents, page items, layers, DocumentPreset and each class constructor are described from the host class registry: the installed members give the names and access, and the new HostClass.info gives the types, bounds, defaults and method arguments dom.rs declares beside each member. Members that are not available yet are left out. A class that names a member twice or describes a member it does not have is refused. - Any other object is described by its own properties without running a getter; a JavaScript function's parameters are its arguments. - An object with more than 10,000 members and arguments throws a RangeError. - script.check counts reflection as a language feature, not host-only. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 312 +++++++++++++---- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/builtins/extensions.rs | 7 +- crates/js/src/host_classes.rs | 139 +++++++- crates/js/src/host_tests.rs | 2 +- crates/js/src/lib.rs | 6 +- crates/js/src/realm.rs | 4 +- crates/js/src/reflect.rs | 331 ++++++++++++++++++ crates/js/src/reflect_tests.rs | 242 +++++++++++++ crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 7 + docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 13 files changed, 995 insertions(+), 80 deletions(-) create mode 100644 crates/js/src/reflect.rs create mode 100644 crates/js/src/reflect_tests.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..6fda66efe1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,7 +25,12 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. -//! - Members the help pages list that are not here yet throw an error that says so. +//! - Members the help pages list that are not here yet throw an error that says so, and `reflect` +//! leaves them out. +//! - `reflect` on an object or a class gives each member's type from the declaration that installs +//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of +//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of +//! more than one type. use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -33,7 +38,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; +use vectorcraft_js::{ + ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, +}; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; @@ -151,9 +158,23 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// A member of a class with what `reflect` tells of it. +type Described = (String, HostMember, MemberInfo); + +/// A property's or a method's result's type for `reflect`. +fn typed(data_type: &str) -> MemberInfo { + MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } +} + +/// A method's result's type and its arguments' names and types, for `reflect`. +fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { + let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); + MemberInfo { arguments, ..typed(data_type) } +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -170,7 +191,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM } Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) } fn text(s: impl Into) -> Data { @@ -1765,12 +1786,30 @@ fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } -fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { - HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +fn class(name: &str, parent: Option<&str>, members: Vec, index: Option) -> HostClass { + let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect(); + let members = members.into_iter().map(|(n, m, _)| (n, m)).collect(); + HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None } } -fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { - items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec { + items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect() +} + +/// The type of a `DocumentPreset` field's value. +fn preset_type(field: &str) -> &'static str { + match field { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "documentBleedLink" => "boolean", + "documentBleedOffsetRect" => "Array", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "title" => "string", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => "number", + } } /// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. @@ -1807,14 +1846,20 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))]) +} + +/// The classes of the object model, each member with the type `reflect` gives for it. +fn classes(link: &Link) -> Vec { let l = link; + let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")]; let mut application = named(vec![ - ("typename", typename_of("Application")), - ("documents", get(l, app_documents)), - ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), - ("coordinateSystem", property(l, app_coords, app_set_coords)), - ("getIsFileOpen", method(l, app_is_open)), + ("typename", typename_of("Application"), typed("string")), + ("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }), + ("activeDocument", property(l, app_active, app_set_active), typed("Document")), + ("selection", get(l, app_selection), typed("*")), + ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), + ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ]); application.push(later(l, "Application", "beep")); let preset = { @@ -1824,9 +1869,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), h.charge_call(64)?; new_preset(&h) }); - let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; - members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); - HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"), typed("string"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); + HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } }; let mut classes = vec![ class("Application", None, application, None), @@ -1835,29 +1880,52 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "Documents", None, named(vec![ - ("typename", typename_of("Documents")), - ("length", get(l, docs_length)), - ("parent", get(l, app_ref)), - ("index", method(l, docs_index)), - ("getByName", method(l, docs_by_name)), - ("add", method(l, docs_add)), - ("addDocument", method(l, docs_add_document)), + ("typename", typename_of("Documents"), typed("string")), + ("length", get(l, docs_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])), + ("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])), + ( + "add", + method(l, docs_add), + returns( + "Document", + &[ + ("colorSpace", "DocumentColorSpace"), + ("width", "number"), + ("height", "number"), + ("numArtBoards", "number"), + ("artboardLayout", "DocumentArtboardLayout"), + ("artboardSpacing", "number"), + ("artboardRowsOrCols", "number"), + ], + ), + ), + ( + "addDocument", + method(l, docs_add_document), + returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), + ), ]), Some(function(l, docs_at)), ), ]; let mut document = named(vec![ - ("typename", get(l, doc_typename)), - ("parent", get(l, doc_parent)), - ("name", get(l, doc_name)), - ("width", get(l, doc_width)), - ("height", get(l, doc_height)), - ("rulerUnits", get(l, doc_units)), - ("documentColorSpace", get(l, doc_color_space)), - ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), - ("convertCoordinate", method(l, doc_convert)), - ("pageItems", get(l, doc_page_items)), - ("selection", property(l, doc_selection, doc_set_selection)), + ("typename", get(l, doc_typename), typed("string")), + ("parent", get(l, doc_parent), typed("Application")), + ("name", get(l, doc_name), typed("string")), + ("width", get(l, doc_width), typed("number")), + ("height", get(l, doc_height), typed("number")), + ("rulerUnits", get(l, doc_units), typed("RulerUnits")), + ("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")), + ( + "convertCoordinate", + method(l, doc_convert), + returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), + ), + ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ]); document.extend( ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] @@ -1869,38 +1937,44 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "PageItems", None, named(vec![ - ("typename", get(l, items_typename)), - ("length", get(l, items_length)), - ("parent", get(l, items_parent)), - ("index", method(l, items_index)), - ("getByName", method(l, items_by_name)), - ("removeAll", method(l, items_remove_all)), + ("typename", get(l, items_typename), typed("string")), + ("length", get(l, items_length), typed("number")), + ("parent", get(l, items_parent), typed("Document")), + ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), + ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), + ("removeAll", method(l, items_remove_all), returns("undefined", &[])), ]), Some(function(l, items_at)), )); let mut page_item = named(vec![ - ("typename", get(l, item_typename)), - ("parent", get(l, item_parent)), - ("name", property(l, item_name, item_set_name)), - ("note", property(l, item_note, item_set_note)), - ("hidden", property(l, item_hidden, item_set_hidden)), - ("locked", property(l, item_locked, item_set_locked)), - ("selected", property(l, item_selected, item_set_selected)), - ("opacity", property(l, item_opacity, item_set_opacity)), - ("position", property(l, item_position, item_set_position)), - ("left", property(l, item_left, item_set_left)), - ("top", property(l, item_top, item_set_top)), - ("width", property(l, item_width, item_set_width)), - ("height", property(l, item_height, item_set_height)), - ("geometricBounds", get(l, item_geometric)), - ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), - ("editable", get(l, item_editable)), - ("zOrderPosition", get(l, item_z_order_position)), - ("duplicate", method(l, item_duplicate)), - ("move", method(l, item_move)), - ("remove", method(l, item_remove)), - ("zOrder", method(l, item_z_order)), + ("typename", get(l, item_typename), typed("string")), + ("parent", get(l, item_parent), typed("*")), + ("name", property(l, item_name, item_set_name), typed("string")), + ("note", property(l, item_note, item_set_note), typed("string")), + ("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")), + ("locked", property(l, item_locked, item_set_locked), typed("boolean")), + ("selected", property(l, item_selected, item_set_selected), typed("boolean")), + ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("position", property(l, item_position, item_set_position), typed("Array")), + ("left", property(l, item_left, item_set_left), typed("number")), + ("top", property(l, item_top, item_set_top), typed("number")), + ("width", property(l, item_width, item_set_width), typed("number")), + ("height", property(l, item_height, item_set_height), typed("number")), + ("geometricBounds", get(l, item_geometric), typed("Array")), + ("visibleBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_visible), typed("Array")), + ("editable", get(l, item_editable), typed("boolean")), + ("zOrderPosition", get(l, item_z_order_position), typed("number")), + ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), + ("move", method(l, item_move), { + let mut info = returns("PageItem", &placement); + if let Some(at) = info.arguments.get_mut(1) { + at.default = Some(text("ElementPlacement.PLACEATBEGINNING")); + } + info + }), + ("remove", method(l, item_remove), returns("undefined", &[])), + ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ]); page_item.extend( [ @@ -1928,8 +2002,13 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); - realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename), typed("string")), ("name", get(l, layer_name), typed("string"))]), + None, + )); + classes } #[cfg(test)] @@ -1944,4 +2023,107 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + /// A script function that writes a reflection as one line, in the form [`expected_line`] gives. + const LINE: &str = "function line(r) {\ + function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\ + function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\ + s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\ + return r.name + '|' + list(r.properties) + '|' + list(r.methods); }"; + + fn shown(d: Option<&Data>) -> String { + match d { + None | Some(Data::Undefined) => String::new(), + Some(Data::String(s)) => s.clone(), + Some(Data::Number(n)) => n.to_string(), + Some(other) => panic!("no form for {other:?}"), + } + } + + /// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it + /// declares again in its parent's place, without the members that are not available. + fn expected_line(classes: &[HostClass], class: &HostClass) -> String { + let mut chain = vec![class]; + while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) { + chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}"))); + } + let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new(); + for c in chain.iter().rev() { + for (name, member) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default(); + let kind = match member { + HostMember::Get(_) => "readonly", + HostMember::Property { .. } => "readwrite", + HostMember::Method(_) => "method", + }; + match members.iter_mut().find(|(n, ..)| n == name) { + Some(slot) => *slot = (name.clone(), kind, info), + None => members.push((name.clone(), kind, info)), + } + } + } + members.retain(|(.., i)| !i.unavailable); + let one = |(name, kind, i): &(String, &str, MemberInfo)| { + let args: Vec = + i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect(); + let number = |n: Option| n.map(|n| n.to_string()).unwrap_or_default(); + format!( + "{name}:{kind}:{}:{}:{}:{}:{}:{}", + i.data_type, + i.collection, + number(i.min), + number(i.max), + shown(i.default.as_ref()), + args.join(",") + ) + }; + let properties: Vec = members.iter().filter(|m| m.1 != "method").map(one).collect(); + let methods: Vec = members.iter().filter(|m| m.1 == "method").map(one).collect(); + format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" ")) + } + + fn logged(s: &mut Session, source: &str) -> Vec { + let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect() + } + + #[test] + fn reflect_of_every_class_equals_its_declaration() { + let link = Link::default(); + let classes = classes(&link); + // Every member that is available declares its type, so `reflect` never answers `unknown`. + for c in &classes { + for (name, _) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i); + assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name); + } + } + let mut s = Session::new(); + let logs: Vec = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect(); + let script = format!("{LINE} {}", logs.join(" ")); + let got = logged(&mut s, &script); + let want: Vec = classes.iter().map(|c| expected_line(&classes, c)).collect(); + assert_eq!(got, want); + assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING"))); + } + + #[test] + fn reflect_of_an_object_equals_its_class_and_calls_no_member() { + let link = Link::default(); + let classes = classes(&link); + let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}"))); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}")); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}")); + let script = format!( + "{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\ + vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\ + p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));" + ); + let got = logged(&mut s, &script); + let path = want("PathItem"); + let expected = + [want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()]; + assert_eq!(got, expected); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..4b3b95e517 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), - ("Object.prototype.", "toSource"), + ("Object.prototype.", "reflect toSource"), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..68eca8d657 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -1,6 +1,6 @@ //! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global -//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind -//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of +//! `localize`, the global `toSource` and `Object.prototype.toSource`, `Object.prototype.reflect` +//! ([`crate::reflect`]), and the getters behind [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of //! [`Localization`]. //! //! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression @@ -96,7 +96,8 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, global, "localize", localize, 1)?; method(interp, global, "toSource", to_source, 1)?; let object_proto = interp.intrinsics.object_proto; - method(interp, object_proto, "toSource", to_source_method, 0) + method(interp, object_proto, "toSource", to_source_method, 0)?; + crate::reflect::install(interp) } /// The text of the localization object `id` for the current locale: the string value of the first diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..2af2fc130f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,6 +17,11 @@ //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each //! array index `i` with it, called with `this` and the index, and `i in object` is true when it //! gives a value other than `undefined`; other names are looked up as usual. +//! +//! A script's `reflect` ([`crate::reflect`]) describes an object of a host class, and the class's +//! constructor, from the members installed here and their [`HostClass::info`], so what a script is +//! told always matches what the class has. A class that names a member twice, or describes a member +//! it does not have, is refused. use std::rc::Rc; @@ -40,6 +45,39 @@ pub enum HostMember { Method(HostFunction), } +/// What a script's `reflect` tells of a member of a host class ([`HostClass::info`]). The member's +/// name and whether it is read-only, read-write or a method come from the [`HostMember`] itself. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MemberInfo { + /// The type of the member's value, or of a method's result: `boolean`, `number`, `string`, a + /// class name, `*` for any type, `null` or `undefined`. Empty reads as `unknown`. + pub data_type: String, + pub description: Option, + pub help: Option, + /// The value an omitted value means. + pub default: Option, + pub min: Option, + pub max: Option, + /// The value, or a method's result, is a collection. + pub collection: bool, + /// A method's arguments, in order. + pub arguments: Vec, + /// The member is installed but throws when used: `reflect` leaves it out. + pub unavailable: bool, +} + +/// What a script's `reflect` tells of an argument of a host class's method ([`MemberInfo::arguments`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ArgInfo { + pub name: String, + /// As [`MemberInfo::data_type`]. + pub data_type: String, + pub description: Option, + pub default: Option, + pub min: Option, + pub max: Option, +} + /// A class [`crate::Realm::define_host_classes`] adds. #[derive(Clone)] pub struct HostClass { @@ -48,6 +86,9 @@ pub struct HostClass { /// class's prototype inherits from. pub parent: Option, pub members: Vec<(String, HostMember)>, + /// What `reflect` tells of the members, each under the name of one of `members`. A member + /// without an entry has the type `unknown` and nothing else. + pub info: Vec<(String, MemberInfo)>, /// What `object[i]` gives for an array index `i`. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. @@ -72,6 +113,26 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The parent class, as an index into the realm's classes. + parent: Option, + /// The class's own members as `reflect` lists them. + members: Rc<[Reflected]>, +} + +/// How a script may use a member of a host class. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Access { + ReadOnly, + ReadWrite, + Method, +} + +/// A member of a host class as `reflect` lists it. +#[derive(Clone, Debug)] +pub(crate) struct Reflected { + pub(crate) name: Rc, + pub(crate) access: Access, + pub(crate) info: MemberInfo, } impl Entry { @@ -168,6 +229,41 @@ impl Interp { self.host_classes.iter().any(|e| e.ctor == id) } + /// The name of the host class of `id`, when it is an object of a host class. + pub(crate) fn host_class_name(&self, id: ObjId) -> JsResult>> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).map(|e| e.name.clone())) + } + + /// The name and members of the host class of `id`, an object of the class or its constructor: + /// the members of its parents first, then its own, a member a class declares again in the place + /// of its parent's. Members marked [`MemberInfo::unavailable`] are left out. `None` when `id` is + /// neither. + pub(crate) fn host_class_members(&self, id: ObjId) -> JsResult, Vec)>> { + let class = match &self.object(id)?.class { + Class::Host(h) => Some(h.class as usize), + _ => self.host_classes.iter().position(|e| e.ctor == id), + }; + let Some(class) = class else { return Ok(None) }; + let Some(entry) = self.host_classes.get(class) else { return Err(Abrupt::Internal("host class out of range".into())) }; + let mut chain = vec![entry]; + while let Some(p) = chain.last().and_then(|e| e.parent) { + let Some(parent) = self.host_classes.get(p as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + chain.push(parent); + } + let mut out: Vec = Vec::new(); + for e in chain.iter().rev() { + for m in e.members.iter() { + match out.iter_mut().find(|r| r.name == m.name) { + Some(slot) => *slot = m.clone(), + None => out.push(m.clone()), + } + } + } + out.retain(|m| !m.info.unavailable); + Ok(Some((entry.name.clone(), out))) + } + /// The indexer of the host class of `id`, when it is an object of a host class that has one. pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; @@ -223,24 +319,57 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_index) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, Some(u32::try_from(n).unwrap_or(u32::MAX))), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; + let members = match reflected_members(&class) { + Ok(m) => m, + Err(message) => return Err(i.throw(ErrorType::Type, &message)), + }; let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); let mark = i.temp_roots.len(); i.temp_roots.push(Value::Object(proto)); let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_index, members }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } +/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the +/// error's message when a member is named twice, or an entry names no member or is given twice. +fn reflected_members(class: &HostClass) -> Result, String> { + let mut out: Vec = Vec::with_capacity(class.members.len()); + for (name, member) in &class.members { + if out.iter().any(|r| *r.name == **name) { + return Err(format!("the host class {} names the member {name} twice", class.name)); + } + let access = match member { + HostMember::Get(_) => Access::ReadOnly, + HostMember::Property { .. } => Access::ReadWrite, + HostMember::Method(_) => Access::Method, + }; + out.push(Reflected { name: name.as_str().into(), access, info: MemberInfo::default() }); + } + let mut seen: Vec<&str> = Vec::with_capacity(class.info.len()); + for (name, info) in &class.info { + if seen.contains(&name.as_str()) { + return Err(format!("the host class {} describes the member {name} twice", class.name)); + } + seen.push(name); + let Some(slot) = out.iter_mut().find(|r| *r.name == **name) else { + return Err(format!("the host class {} describes {name}, which is not one of its members", class.name)); + }; + slot.info = info.clone(); + } + Ok(out.into()) +} + /// Puts the members of `class` on `proto` and makes its constructor. → the constructor. fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { let path = &class.name; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..040361d460 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -644,7 +644,7 @@ fn with_thing(r: &mut Realm, make: Option) { let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; - let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: make }; r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..8d61712e36 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -65,6 +65,7 @@ mod number; mod number_builtins; mod parser; mod realm; +mod reflect; mod regexp; mod regexp_builtins; mod regexp_vm; @@ -82,10 +83,11 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{ArgInfo, HOST_REF_KEY, HostClass, HostMember, MemberInfo, host_ref, host_ref_parts}; 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, SourceLocator, UNKNOWN_SOURCE}; +pub use reflect::MAX_REFLECTED_MEMBERS; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -211,6 +213,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod reflect_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..745c2b9364 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -539,7 +539,9 @@ impl Realm { /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, - /// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`]. + /// `Object.prototype.reflect`, which describes an object's properties and methods (a host + /// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while + /// [`crate::Localization::enabled`]. pub fn add_script_extensions(&mut self) -> Result<(), RunError> { match crate::builtins::extensions::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs new file mode 100644 index 0000000000..a84c221d3a --- /dev/null +++ b/crates/js/src/reflect.rs @@ -0,0 +1,331 @@ +//! The script extension `reflect` ([`crate::Realm::add_script_extensions`]): a read-only property +//! of `Object.prototype` that gives, on each read, a new reflection object describing the object it +//! is read on. +//! +//! A reflection object has `name` (the object's class), `description` and `help` (`undefined`), +//! `properties` and `methods` (arrays of ReflectionInfo objects), and `find(name)`, which gives the +//! ReflectionInfo of the property or method with that name, or `null`. A ReflectionInfo has `name` +//! (a string, or a number for an array index), `description`, `help`, `type` (`readonly`, +//! `readwrite`, `method`, or `parameter` for a method's argument), `dataType`, `defaultValue`, +//! `min`, `max`, `isCollection` and `arguments` (an array of ReflectionInfo objects, empty for a +//! property). Each entry of `properties`, `methods` and `arguments` is also under its name when +//! that name is not an array index or `length`. +//! +//! An object of a host class and the class's constructor are described by the class's members +//! ([`crate::HostClass::members`] and [`crate::HostClass::info`]), its parents' included. Any other +//! object is described by its own properties: a property whose value is a function is a method, +//! with the parameter names of a function written in JavaScript as its arguments; a data property +//! is read-write when it is writable and gives the type of its value; an accessor is read-write +//! when it has a setter and its type is `unknown`. A string, number or boolean is described by its +//! prototype's own properties. No getter or other script code runs. +//! +//! Every object made is frozen, so a script cannot change one; `reflect` itself has no setter. +//! Each member described takes fuel, and an object with more than [`MAX_REFLECTED_MEMBERS`] +//! members and arguments throws a `RangeError`. + +use crate::builtins::native; +use crate::heap::{Class, ENUMERABLE, Func, Key, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, key}; +use crate::host::Data; +use crate::host_classes::{Access, Reflected}; +use crate::interp::{ErrorType, Interp, JsResult}; +use crate::value::{Str, Value, array_index, index_key, number_to_str}; + +/// The most members and arguments `reflect` describes for one object. +pub const MAX_REFLECTED_MEMBERS: usize = 10_000; + +/// The properties of a ReflectionInfo object. +const INFO_PROPS: usize = 10; + +/// A member or argument as a ReflectionInfo object describes it. +struct Info { + name: Value, + kind: &'static str, + data_type: String, + description: Option, + help: Option, + default: Option, + min: Option, + max: Option, + collection: bool, + arguments: Vec, +} + +impl Info { + fn new(name: Value, kind: &'static str, data_type: &str) -> Self { + Self { + name, + kind, + data_type: data_type.to_string(), + description: None, + help: None, + default: None, + min: None, + max: None, + collection: false, + arguments: Vec::new(), + } + } +} + +/// The type a [`crate::MemberInfo`] gives, `unknown` when it gives none. +fn declared(data_type: &str) -> &str { + if data_type.is_empty() { "unknown" } else { data_type } +} + +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let get = native(interp, "reflect", reflect, 0, NativeKind::Plain, false)?; + let object_proto = interp.intrinsics.object_proto; + interp.define(object_proto, key("reflect"), Prop::Accessor { get: Some(get), set: None, flags: 0 }) +} + +/// Counts one more member or argument against [`MAX_REFLECTED_MEMBERS`], with a unit of fuel. +fn count(interp: &mut Interp, total: &mut usize) -> JsResult<()> { + interp.use_fuel()?; + *total += 1; + if *total > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + Ok(()) +} + +/// The getter of `Object.prototype.reflect`. +fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (id, primitive) = match &this { + Value::Undefined | Value::Null => return Err(interp.type_error("reflect needs an object")), + Value::String(_) => (interp.intrinsics.string_proto, Some("String")), + Value::Number(_) => (interp.intrinsics.number_proto, Some("Number")), + Value::Bool(_) => (interp.intrinsics.boolean_proto, Some("Boolean")), + Value::Object(o) => (*o, None), + }; + let (name, properties, methods) = match interp.host_class_members(id)? { + Some((name, members)) if primitive.is_none() => { + let (properties, methods) = host_infos(interp, &members)?; + (name.to_string(), properties, methods) + } + _ => { + let name = primitive.unwrap_or(interp.object(id)?.class.name()).to_string(); + let (properties, methods) = own_infos(interp, id)?; + (name, properties, methods) + } + }; + interp.rooted(&[this], |i| { + let mark = i.temp_roots.len(); + let r = reflection(i, &name, &properties, &methods); + i.temp_roots.truncate(mark); + r + }) +} + +/// The properties and methods of a host class's `members`. +fn host_infos(interp: &mut Interp, members: &[Reflected]) -> JsResult<(Vec, Vec)> { + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for m in members { + count(interp, &mut total)?; + let kind = match m.access { + Access::ReadOnly => "readonly", + Access::ReadWrite => "readwrite", + Access::Method => "method", + }; + let mut info = Info::new(Value::str(&m.name), kind, declared(&m.info.data_type)); + info.description = m.info.description.clone(); + info.help = m.info.help.clone(); + info.default = m.info.default.clone(); + info.min = m.info.min; + info.max = m.info.max; + info.collection = m.info.collection; + for a in &m.info.arguments { + count(interp, &mut total)?; + let mut arg = Info::new(Value::str(&a.name), "parameter", declared(&a.data_type)); + arg.description = a.description.clone(); + arg.default = a.default.clone(); + arg.min = a.min; + arg.max = a.max; + info.arguments.push(arg); + } + if m.access == Access::Method { methods.push(info) } else { properties.push(info) } + } + Ok((properties, methods)) +} + +/// The properties and methods of the own properties of `id`. No getter runs. +fn own_infos(interp: &mut Interp, id: ObjId) -> JsResult<(Vec, Vec)> { + let o = interp.object(id)?; + let extra = match &o.class { + Class::String(s) => s.len().saturating_add(1), + Class::Array { .. } => 1, + _ => 0, + }; + // Checked before the names are listed, so a huge object costs no more than a small one. + if o.props.len().saturating_add(extra) > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + let keys = interp.own_keys(id)?; + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for k in keys { + count(interp, &mut total)?; + let Some(prop) = interp.get_own_property(id, &k)? else { continue }; + let name = member_name(&k); + match prop { + Prop::Data { value, .. } if interp.is_callable(&value) => { + let mut info = Info::new(name, "method", "unknown"); + if let Some(params) = parameters(interp, &value)? { + for p in params { + count(interp, &mut total)?; + info.arguments.push(Info::new(Value::String(Str::from_rc(p)), "parameter", "*")); + } + } + methods.push(info); + } + Prop::Data { value, flags } => { + let kind = if flags & WRITABLE != 0 { "readwrite" } else { "readonly" }; + let data_type = value_type(interp, &value)?; + properties.push(Info::new(name, kind, &data_type)); + } + Prop::Accessor { set, .. } => properties.push(Info::new(name, if set.is_some() { "readwrite" } else { "readonly" }, "unknown")), + } + } + Ok((properties, methods)) +} + +/// A property name as a ReflectionInfo's `name`: a number for an array index. +fn member_name(k: &Key) -> Value { + match array_index(k) { + Some(i) => Value::Number(f64::from(i)), + None => Value::String(Str::from_rc(k.clone())), + } +} + +/// The parameter names of the function `f` when it is written in JavaScript. +fn parameters(interp: &Interp, f: &Value) -> JsResult>> { + let Some(id) = f.as_object() else { return Ok(None) }; + Ok(match &interp.object(id)?.class { + Class::Function(Func::Closure { code, .. }) => Some(code.params.clone()), + _ => None, + }) +} + +/// The `dataType` of a data property holding `v`. +fn value_type(interp: &Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => "undefined".into(), + Value::Null => "null".into(), + Value::Bool(_) => "boolean".into(), + Value::Number(_) => "number".into(), + Value::String(_) => "string".into(), + Value::Object(o) => match interp.host_class_name(*o)? { + Some(name) => name.to_string(), + None => interp.object(*o)?.class.name().into(), + }, + }) +} + +/// The reflection object. Every object it makes is kept in `interp.temp_roots`. +fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[Info]) -> JsResult { + let properties = info_array(interp, properties)?; + let methods = info_array(interp, methods)?; + interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; + let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.temp_roots.push(Value::Object(find)); + let r = interp.new_object(); + interp.temp_roots.push(Value::Object(r)); + for (k, v) in [ + ("name", Value::str(name)), + ("description", Value::Undefined), + ("help", Value::Undefined), + ("properties", Value::Object(properties)), + ("methods", Value::Object(methods)), + ] { + interp.define(r, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.define(r, key("find"), Prop::Data { value: Value::Object(find), flags: 0 })?; + interp.object_mut(r)?.extensible = false; + Ok(Value::Object(r)) +} + +/// A frozen array of ReflectionInfo objects for `infos`, each also under its name when that name +/// is not an array index or `length`. +fn info_array(interp: &mut Interp, infos: &[Info]) -> JsResult { + interp.reserve_heap(OBJECT_BYTES.saturating_add(infos.len().saturating_mul(2 * PROP_BYTES)))?; + let proto = interp.intrinsics.array_proto; + let a = interp.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: false }, Some(proto))); + interp.temp_roots.push(Value::Object(a)); + for (n, info) in infos.iter().enumerate() { + let o = info_object(interp, info)?; + interp.define(a, index_key(u32::try_from(n).unwrap_or(u32::MAX)), Prop::Data { value: Value::Object(o), flags: ENUMERABLE })?; + } + for (n, info) in infos.iter().enumerate() { + let Value::String(s) = &info.name else { continue }; + let k = s.flat(); + if array_index(&k).is_some() || *k == *key("length") || interp.object(a)?.props.contains(&k) { + continue; + } + let Some(Prop::Data { value, .. }) = interp.get_own_property(a, &index_key(u32::try_from(n).unwrap_or(u32::MAX)))? else { continue }; + interp.define(a, k, Prop::Data { value, flags: 0 })?; + } + interp.object_mut(a)?.extensible = false; + Ok(a) +} + +/// A frozen ReflectionInfo object for `info`. +fn info_object(interp: &mut Interp, info: &Info) -> JsResult { + let arguments = info_array(interp, &info.arguments)?; + interp.reserve_heap(OBJECT_BYTES + INFO_PROPS * PROP_BYTES)?; + let o = interp.new_object(); + interp.temp_roots.push(Value::Object(o)); + let text = |s: &Option| s.as_deref().map_or(Value::Undefined, Value::str); + let number = |n: Option| n.map_or(Value::Undefined, Value::Number); + let default = match &info.default { + Some(d) => interp.write_data(d.clone(), 0, true)?, + None => Value::Undefined, + }; + let fields = [ + ("name", info.name.clone()), + ("description", text(&info.description)), + ("help", text(&info.help)), + ("type", Value::str(info.kind)), + ("dataType", Value::str(&info.data_type)), + ("defaultValue", default), + ("min", number(info.min)), + ("max", number(info.max)), + ("isCollection", Value::Bool(info.collection)), + ("arguments", Value::Object(arguments)), + ]; + for (k, v) in fields { + interp.define(o, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.object_mut(o)?.extensible = false; + Ok(o) +} + +/// `reflect.find(name)`: the ReflectionInfo of the property, or else the method, named `name` (a +/// string, or a number for an array index), or `null`. +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let wanted = match args.first() { + Some(Value::String(s)) => s.flat(), + Some(Value::Number(n)) => number_to_str(*n).flat(), + _ => return Err(interp.type_error("reflect.find: give the member's name, as a string or a number")), + }; + let not_reflection = "reflect.find must be called on a reflection object"; + let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) }; + for list in ["properties", "methods"] { + let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else { + return Err(interp.type_error(not_reflection)); + }; + let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) }; + for i in 0..length { + interp.use_fuel()?; + let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue }; + let name = match interp.get_own_property(e, &key("name"))? { + Some(Prop::Data { value: Value::String(s), .. }) => s.flat(), + Some(Prop::Data { value: Value::Number(n), .. }) => number_to_str(n).flat(), + _ => continue, + }; + if *name == *wanted { + return Ok(Value::Object(e)); + } + } + } + Ok(Value::Null) +} diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs new file mode 100644 index 0000000000..3e8827cf4f --- /dev/null +++ b/crates/js/src/reflect_tests.rs @@ -0,0 +1,242 @@ +//! `reflect`: the description of an object's properties and methods, from a host class's members +//! or from an object's own properties. + +use std::rc::Rc; + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_script_extensions().unwrap(); + r +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn thrown(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Err(e) if e.kind == RunErrorKind::Thrown => e.message, + other => panic!("{source}: {other:?}"), + } +} + +/// `name:type:dataType` of each entry of a list, joined with spaces. +const LIST: &str = "function list(a) { var s = []; for (var i = 0; i < a.length; i++) s.push(a[i].name + ':' + a[i].type + ':' + a[i].dataType); \ + return s.join(' '); }"; + +#[test] +fn a_script_object_lists_its_own_properties_and_methods_without_running_getters() { + let mut r = realm(); + let setup = "var o = {a: 1, b: 'x', c: null, d: [1], f: function (p, q) {}, get g() { throw new Error('ran'); }, set h(v) {}};\ + Object.defineProperty(o, 'k', {value: true, writable: false});"; + r.run(setup).unwrap(); + r.run(LIST).unwrap(); + assert_eq!(text(&mut r, "o.reflect.name"), "Object"); + assert_eq!( + text(&mut r, "list(o.reflect.properties)"), + "a:readwrite:number b:readwrite:string c:readwrite:null d:readwrite:Array g:readonly:unknown h:readwrite:unknown k:readonly:boolean" + ); + assert_eq!(text(&mut r, "list(o.reflect.methods)"), "f:method:unknown"); + assert_eq!(text(&mut r, "list(o.reflect.methods[0].arguments)"), "p:parameter:* q:parameter:*"); + assert_eq!(text(&mut r, "list(o.reflect.properties[0].arguments) + '|' + o.reflect.description + '|' + o.reflect.help"), "|undefined|undefined"); + // A value replaced by a function becomes a method on the next read; each read is a new snapshot. + assert_eq!( + text(&mut r, "var before = o.reflect; o.a = function () {}; delete o.b; list(before.methods) + '|' + list(o.reflect.methods)"), + "f:method:unknown|a:method:unknown f:method:unknown" + ); + assert_eq!(text(&mut r, "String(o.reflect.find('b'))"), "null"); +} + +#[test] +fn find_and_names_look_up_properties_then_methods() { + let mut r = realm(); + r.run("var o = {width: 2, draw: function () {}};").unwrap(); + assert_eq!(text(&mut r, "o.reflect.find('width').dataType + ' ' + o.reflect.find('draw').type"), "number method"); + assert_eq!(text(&mut r, "String(o.reflect.find('nothing'))"), "null"); + assert_eq!(text(&mut r, "o.reflect.properties.width.name + ' ' + o.reflect.methods.draw.name"), "width draw"); + // Array indexes are numbers, found by number or by their text. + assert_eq!( + text( + &mut r, + "var a = [5, 'x']; a[3] = true; var f = a.reflect.find(1); typeof f.name + ' ' + f.dataType + ' ' + a.reflect.find('3').dataType" + ), + "number string boolean" + ); + assert_eq!(text(&mut r, "[5].reflect.properties.length + ' ' + [5].reflect.find('length').type"), "2 readwrite"); + // A name that is missing or of another type is refused. + assert!(thrown(&mut r, "o.reflect.find();").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find({});").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find.call({}, 'width');").starts_with("TypeError")); +} + +#[test] +fn a_reflection_info_has_every_field() { + let mut r = realm(); + let fields = "var i = ({a: 1}).reflect.properties[0]; var k = []; for (var n in i) k.push(n); k.join(' ')"; + assert_eq!(text(&mut r, fields), "name description help type dataType defaultValue min max isCollection arguments"); + let values = + "var i = ({a: 1}).reflect.properties[0]; [i.description, i.help, i.defaultValue, i.min, i.max, i.isCollection, i.arguments.length].join()"; + assert_eq!(text(&mut r, values), ",,,,,false,0"); + assert_eq!(text(&mut r, "var k = []; for (var n in ({}).reflect) k.push(n); k.join(' ')"), "name description help properties methods"); +} + +#[test] +fn functions_primitives_and_built_ins_are_described() { + let mut r = realm(); + r.run(LIST).unwrap(); + assert_eq!( + text(&mut r, "function f(a, b) {} f.reflect.name + ' ' + list(f.reflect.properties)"), + "Function length:readonly:number prototype:readwrite:Object" + ); + assert_eq!(text(&mut r, "Math.reflect.name + ' ' + Math.reflect.find('PI').type + ' ' + Math.reflect.find('max').type"), "Math readonly method"); + assert_eq!(text(&mut r, "'abc'.reflect.name + ' ' + 'abc'.reflect.find('charAt').type"), "String method"); + assert_eq!(text(&mut r, "(5).reflect.name + ' ' + true.reflect.name"), "Number Boolean"); + assert!(thrown(&mut r, "var n = null; n.reflect;").starts_with("TypeError")); + let getter = "Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get"; + assert!(thrown(&mut r, &format!("{getter}.call(undefined);")).starts_with("TypeError")); + // Neither a getter nor `toString` runs, so a cyclic object is described as it is. + assert_eq!(text(&mut r, "var c = {}; c.self = c; c.toString = function () { throw 1; }; c.reflect.find('self').dataType"), "Object"); +} + +#[test] +fn a_reflection_cannot_be_changed() { + let mut r = realm(); + r.run("var o = {a: 1}; var x = o.reflect;").unwrap(); + // Outside strict mode the writes are ignored. + let tries = "o.reflect = 5; x.name = 'y'; x.properties[0].dataType = 'y'; x.properties[1] = 2; x.extra = 1; delete x.methods;\ + [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; + assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); + // In strict mode each one throws a TypeError. + for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); + } + assert_eq!( + text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), + "true true true" + ); +} + +#[test] +fn a_very_wide_object_is_refused() { + let mut r = realm(); + let wide = |n: usize| format!("var w = {{}}; for (var i = 0; i < {n}; i++) w['p' + i] = i;"); + r.run(&wide(MAX_REFLECTED_MEMBERS)).unwrap(); + assert_eq!(text(&mut r, "String(w.reflect.properties.length)"), MAX_REFLECTED_MEMBERS.to_string()); + r.run(&wide(MAX_REFLECTED_MEMBERS + 1)).unwrap(); + assert!(thrown(&mut r, "w.reflect;").starts_with("RangeError")); + // A function with too many parameters is counted with the members. + let params = (0..MAX_REFLECTED_MEMBERS).map(|i| format!("a{i}")).collect::>().join(","); + assert!(thrown(&mut r, &format!("({{f: function ({params}) {{}}}}).reflect;")).starts_with("RangeError")); +} + +fn constant(value: f64) -> HostFunction { + Rc::new(move |_| Ok(Data::Number(value))) +} + +/// `Item` with `size` (read-write, 1 to 10, default 5), `kind` and the method `fit(target, +/// margin?)`; and `Box`, a child that declares `kind` again as a method and adds `cut`, which is +/// not available. +fn classes() -> Vec { + let item = HostClass { + name: "Item".into(), + parent: None, + members: vec![ + ("size".into(), HostMember::Property { get: constant(5.0), set: constant(0.0) }), + ("kind".into(), HostMember::Get(constant(1.0))), + ("fit".into(), HostMember::Method(constant(2.0))), + ], + info: vec![ + ( + "size".into(), + MemberInfo { + data_type: "number".into(), + description: Some("The size.".into()), + help: Some("How large the item is.".into()), + default: Some(Data::Number(5.0)), + min: Some(1.0), + max: Some(10.0), + ..MemberInfo::default() + }, + ), + ( + "fit".into(), + MemberInfo { + data_type: "boolean".into(), + collection: true, + arguments: vec![ + ArgInfo { name: "target".into(), data_type: "Item".into(), ..ArgInfo::default() }, + ArgInfo { + name: "margin".into(), + data_type: "number".into(), + default: Some(Data::Number(0.0)), + min: Some(0.0), + ..ArgInfo::default() + }, + ], + ..MemberInfo::default() + }, + ), + ], + index: None, + construct: None, + }; + let child = HostClass { + name: "Box".into(), + parent: Some("Item".into()), + members: vec![("kind".into(), HostMember::Method(constant(3.0))), ("cut".into(), HostMember::Method(constant(4.0)))], + info: vec![("cut".into(), MemberInfo { unavailable: true, ..MemberInfo::default() })], + index: None, + construct: None, + }; + vec![item, child] +} + +#[test] +fn a_host_class_is_described_by_its_members_and_their_info() { + let mut r = realm(); + r.define_host_classes(classes(), vec![("item".into(), host_ref("Item", &[1.0])), ("box".into(), host_ref("Box", &[2.0]))]).unwrap(); + r.run(LIST).unwrap(); + for target in ["item", "Item"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Item"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number kind:readonly:unknown"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "fit:method:boolean"); + } + let size = "var s = item.reflect.find('size'); [s.description, s.help, s.defaultValue, s.min, s.max, s.isCollection].join('|')"; + assert_eq!(text(&mut r, size), "The size.|How large the item is.|5|1|10|false"); + let fit = "var f = item.reflect.find('fit'); f.isCollection + ' ' + list(f.arguments) + ' ' + f.arguments.margin.defaultValue + ' ' + f.arguments[1].min"; + assert_eq!(text(&mut r, fit), "true target:parameter:Item margin:parameter:number 0 0"); + // The child lists its parent's members first, its own declaration of one in its place, and + // leaves out the member that is not available. + for target in ["box", "Box"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Box"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "kind:method:unknown fit:method:boolean"); + assert_eq!(text(&mut r, &format!("String({target}.reflect.find('cut'))")), "null"); + } + // No member's function ran: a data property of the class's type names it. + assert_eq!(text(&mut r, "({b: box}).reflect.find('b').dataType"), "Box"); +} + +#[test] +fn info_for_a_member_a_class_does_not_have_is_refused() { + for (info, message) in [ + (vec![("nothing".to_string(), MemberInfo::default())], "not one of its members"), + (vec![("size".to_string(), MemberInfo::default()), ("size".to_string(), MemberInfo::default())], "twice"), + ] { + let mut r = realm(); + let mut class = classes().remove(0); + class.info = info; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains(message), "{}", e.message); + } + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("size".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names the member size twice"), "{}", e.message); +} diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..1e61b47bf5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -174,7 +174,7 @@ features! { Notify "notify" Language, OperatorOverloading "operatorOverloading" HostOnly, Preferences "preferences" Language, - Reflection "reflection" HostOnly, + Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..ac75fb0256 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -212,6 +212,13 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() { assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine"); } +#[test] +fn reflection_needs_only_the_language() { + let r = report("var p = obj.reflect.properties;\nvar m = $.reflect.find('write');\n"); + assert_eq!(feature(&r, "reflection").map(|f| f.lines.clone()), Some(vec![1, 2])); + assert_eq!(r.needs, [Need::Language], "VectorCraft runs reflect"); +} + #[test] fn a_byte_order_mark_and_every_line_break_are_read() { // U+2028 ends line 2. diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..eff8b953f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2540,9 +2540,9 @@ top-level `import` or `export`, such as a React `.jsx` file), `notText` (a NUL b control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, the reply holds these lists: - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects - and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's + and directives, such as `$`, `alert`, `UnitValue`, `reflect`, `#target` and `#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions + palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and @@ -2794,6 +2794,22 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`value.reflect` describes an object, as the reflection interface page lays out +(https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/). Each read +gives a new frozen object with `name` (the class), `description` and `help` (`undefined`), `properties` and +`methods` (arrays of entries), and `find(name)`, which gives the entry of the property, or else the method, with that +name, or `null`; a name that is not a string or a number throws a `TypeError`. Each entry has `name` (a number for an +array index), `description`, `help`, `type` (`readonly`, `readwrite`, `method`, or `parameter` for an argument), +`dataType`, `defaultValue`, `min`, `max`, `isCollection` and `arguments`; an entry is also under its name in its array +when that name is not an array index or `length`. `app`, its documents, page items and layers, `DocumentPreset` and +each class's constructor list the members of their class and its parents, with the types, bounds, defaults and method +arguments the object model declares for them (VectorCraft's own values); members that are not available yet are left +out. Any other object lists its own properties: a function value is a method, with a JavaScript function's parameter +names as its arguments, a data property gives the type of its value, and an accessor gives `unknown`. A string, number +or boolean lists its prototype's own properties. No getter runs. `reflect` has no setter, and nothing in a reflection +can be changed: a write is ignored, or throws a `TypeError` in strict mode. An object with more than 10,000 members +and arguments throws a `RangeError`. + 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..762fde881d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: every object has a read-only `reflect` property (https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/) that gives its class name, its properties and methods with their types, access, bounds, defaults and method arguments, and `find(name)`. `app`, its documents and page items and their classes are described from the declarations that install their members, and any other object from its own properties, without running a getter. `script.check` no longer counts it as host-only. `crates/js/src/reflect_tests.rs`, `crates/engine/src/script/dom.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. From 9e6c315689cbb59d9ae67a6cba04385fb3e34e1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:36:43 -0800 Subject: [PATCH 029/298] Scripts: selection, controlBounds, Revert and preset limits in the object model - Document.selection = undefined throws a TypeError and keeps the selection; null and [] still clear it. The assignment finds the locked artboards once and drops repeated objects with a set. - PageItem.controlBounds is the visible bounds widened to take in the direction points of every path in the object. - A page item or layer handle carries the document's revert count, so an object read before file.revert throws Stale page item. - Restoring a selection gives a path with only segments selected no anchors of its own before its segments are added back. - A failed object-model call and a vc.run result that cannot reach the script put back the growth they were charged. - DocumentPreset values count against the run's heap by what they hold now; an assignment past it throws a RangeError. - A host class member named constructor is refused, and reflect's find function is frozen. - file.new keeps the stored columns while rows are set, so a change of spacing alone no longer changes the grid a later layout uses. - command_value passes the id and params through without copying them. - Tests: the getIsFileOpen test passes its paths as JSON strings, and the locked removeAll test checks both objects from inside the script. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 139 ++++++++++++++++++------- crates/engine/src/script/mod.rs | 29 ++++-- crates/engine/src/tests/script_dom.rs | 143 ++++++++++++++++++++++++-- crates/js/src/host_classes.rs | 4 + crates/js/src/reflect.rs | 1 + crates/js/src/reflect_tests.rs | 20 +++- docs/mcp.md | 14 +-- 8 files changed, 295 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..0a5ed93ba3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -394,9 +394,8 @@ impl DocSettings { if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { self.rows = 0; } - if self.grid_rows().is_some() { - self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); - } + // While rows are set, `grid_columns` gives the columns they make; the stored columns stay as + // they were given, and are the ones a later layout without rows uses. Ok(()) } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6fda66efe1..0753cc5263 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -6,9 +6,10 @@ //! describe them. //! //! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the -//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the -//! document and the object up again. An object that was deleted, a document that was closed and an -//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! document's [`crate::DocState::uid`] and, for art and layers, the document's +//! [`crate::DocState::reverts`] and the object's id, and every read looks the document and the +//! object up again. An object that was deleted, a document that was closed, an object from before +//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs //! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each //! changed document; a change that changes nothing runs no command. A change to a document that is //! not the active one makes it active for the command and makes the other one active again after. @@ -24,7 +25,9 @@ //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object -//! must be one of that document's that can be selected, or nothing changes. +//! must be one of that document's that can be selected, or nothing changes. `undefined` throws. +//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path +//! in the object. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. //! - `reflect` on an object or a class gives each member's type from the declaration that installs @@ -33,6 +36,7 @@ //! more than one type. use std::cell::{Cell, RefCell}; +use std::collections::HashSet; use std::rc::Rc; use std::sync::Arc; @@ -93,16 +97,24 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made, with the size +/// of the values they hold now and the most they may hold: the run's heap. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, presets: RefCell>>, + preset_bytes: Cell, + preset_limit: u64, } impl State { + /// The state of a run whose heap is `heap_bytes`. + pub(super) fn new(heap_bytes: usize) -> Self { + Self { preset_limit: heap_bytes as u64, ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() @@ -111,20 +123,25 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state, and the growth its commands were charged is not +/// counted. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + let mark = h.growth_mark(); h.dom.saving.set(true); let r = f(h); h.dom.saving.set(false); let mut s = h.session.borrow_mut(); if r.is_ok() { save.keep(&mut s); - } else if !save.restore(&mut s) { - return Err(HostError::Abort(HISTORY_LOST.to_string())); + } else { + h.put_growth_back(mark); + if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } } r } @@ -304,11 +321,17 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result bool { + whole(reverts) != Some(with_doc(h, doc, |_, st| st.reverts)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).filter(|doc| !reverted_since(h, *doc, *reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; @@ -346,8 +369,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), }, None => Data::Null, } @@ -509,6 +532,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - .map(|i| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + // A path with only segments selected gets them back below, with no anchors. + None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), }; json!({"id": i.0, "anchors": anchors}) @@ -963,17 +988,30 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } +/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and +/// refuses when they would hold more than the run's heap. +fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> { + let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added); + if total > h.dom.preset_limit { + return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit))); + } + h.dom.preset_bytes.set(total); + Ok(()) +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1026,8 +1064,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; - match fields.iter_mut().find(|(k, _)| k == key) { - Some((_, v)) => *v = value, + // The values the presets hold now count against the run's heap: a value assigned again + // replaces the one before it. + let at = fields.iter().position(|(k, _)| k == key); + hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + match at { + Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), } Ok(Data::Undefined) @@ -1157,28 +1199,33 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } /// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or -/// `[]`. Every one must be an object of that document that can be selected. +/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as +/// an index past the end of `pageItems`, is refused and clears nothing. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], }; - let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; - let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); - if !ok { - let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); - return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + // The locked artboards are found once for the whole list, and repeated objects are kept once. + with_doc(h, doc, |_, st| { + let locks = st.doc.locked_artboards(); + let mut seen: HashSet = HashSet::with_capacity(list.len()); + let mut ids: Vec = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, item.id) { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } } - if !ids.contains(&item.id) { - ids.push(item.id); - } - } - Ok(ids) + Ok(ids) + }) } fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { @@ -1440,6 +1487,25 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in +/// the object. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let r = with_doc(h, item.doc, |_, st| { + let mut r = r; + if let Some(n) = st.doc.node(item.id) { + n.walk(&mut |c| { + if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) { + r = r.union(handles); + } + }); + } + r + }); + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1611,13 +1677,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let doc = find_doc(h, run, uid).filter(|doc| !reverted_since(h, *doc, reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -1771,8 +1837,11 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if reverted_since(h, doc, *reverts) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -1962,7 +2031,7 @@ fn classes(link: &Link) -> Vec { ("height", property(l, item_height, item_set_height), typed("number")), ("geometricBounds", get(l, item_geometric), typed("Array")), ("visibleBounds", get(l, item_visible), typed("Array")), - ("controlBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_control), typed("Array")), ("editable", get(l, item_editable), typed("boolean")), ("zOrderPosition", get(l, item_z_order_position), typed("number")), ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..8e79b7bdda 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1076,6 +1076,20 @@ impl Host { self.pause.set(true); Ok(()) } + + /// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about + /// it, for [`Host::put_growth_back`]. + fn growth_mark(&self) -> (u64, u64, bool) { + (self.objects.get(), self.bytes_kept.get(), self.waiting.get()) + } + + /// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added + /// it were put back. + fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) { + self.objects.set(objects); + self.bytes_kept.set(bytes); + self.waiting.set(waiting); + } } /// A run in progress. @@ -1309,16 +1323,14 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { - let id = id.to_string(); - let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { let mut s = session.borrow_mut(); - step(&mut s, host, &id, ¶ms) + step(&mut s, host, id, params) }; // Only commands that exist are timed, so the table holds at most one row per command. - if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { + if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { let nanos = started.elapsed().as_nanos(); let mut times = host.commands.borrow_mut(); let row = times.entry(spec.id).or_insert((0, 0, 0)); @@ -1331,13 +1343,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())), Err(e) => return Err(HostError::Error(e.to_string())), }; + let mark = host.growth_mark(); let crossed = host.charge_growth(objects, added).and_then(|()| { let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; host.charge_call(data_size(&data))?; Ok(data) }); - // A command whose result does not reach the script is put back, like one that failed. + // A command whose result does not reach the script is put back, like one that failed, and so is + // the growth it was charged. + if crossed.is_err() { + host.put_growth_back(mark); + } if let Some(save) = save { let mut s = session.borrow_mut(); if crossed.is_ok() { @@ -2064,7 +2081,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(heap_bytes), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..d0cb4e7ecd 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -229,6 +229,41 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +/// An index past the end of `pageItems` gives `undefined`, which does not clear the selection; +/// `null` and `[]` do. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let caught = "var d = app.activeDocument, m = '';\ + try { d.selection = d.pageItems[99]; } catch (e) { m = e.name; }\ + vc.log(m); vc.log(d.selection.length);"; + assert_eq!(log(&mut s, caught), vec![json!("TypeError"), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + for clear in ["null", "[]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, &format!("app.activeDocument.selection = {clear};")); + assert!(s.active().unwrap().selection.objects.is_empty(), "{clear}"); + } +} + +/// `controlBounds` takes in a direction point that lies past the curve; `visibleBounds` does not. +#[test] +fn control_bounds_take_in_direction_points_past_the_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.pageItems;\ + vc.log(p[2].controlBounds); vc.log(p[2].visibleBounds); vc.log(p[0].controlBounds); vc.log(p[0].visibleBounds);", + ); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!((top(&out[0]) + 100.0).abs() < 1e-9, "{out:?}"); + assert!(top(&out[1]) > -90.0, "{out:?}"); + // A rectangle's direction points lie on its edges. + assert_eq!(out[2], out[3]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -364,6 +399,17 @@ fn a_copy_that_cannot_be_placed_is_deleted() { assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); // The refused copy leaves no undo step and does not change the document's step. assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step)); + // Nor does it count toward the run's growth allowance: many refused copies stay within one + // that a few kept copies would pass. + crate::script::TEST_GROWTH.with(|g| g.set(Some(5))); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], refused = 0;\ + for (var k = 0; k < 20; k++) { try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { refused++; } }\ + vc.log(refused);", + ); + crate::script::TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(r.unwrap()["log"], json!([20])); } #[test] @@ -482,6 +528,14 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); } + // A change of spacing alone leaves the stored columns as they are, so leaving the rows later + // gives the same grid with or without it. + let to_row = json!({"artboardLayout": {"layout": "gridByRow"}}); + let plain = stored.clone().with_params(&json!({"artboards": 9}), "file.new").unwrap(); + let spaced = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": {"spacing": 20}}), "file.new").unwrap(); + assert_eq!((plain.grid_columns(), spaced.grid_columns()), (3, 3)); + let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); + assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); assert!(e.contains("rows must be 1 or more"), "{e}"); for layout in ["gridByRow", "row", "column"] { @@ -549,6 +603,26 @@ fn an_edit_keeps_the_order_of_a_mixed_selection() { assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); } +/// A path with segments selected and no anchors gets the segments back, not every anchor. +#[test] +fn an_edit_keeps_a_path_with_only_a_segment_selected() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.doc_mut().unwrap().selection.anchors.remove(&b); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((&sel.objects, &sel.segments, sel.anchors.get(&a)), (&before.objects, &before.segments, before.anchors.get(&a))); + // The segment brings back its own two end points, as `select.segments` selects them, and none + // of the path's other anchors: the journaled restore selects none of them first. + assert_eq!(sel.anchors.get(&b).map(|k| k.len()), Some(2), "{sel:?}"); + let restore = s.journal.iter().rev().find(|(id, _)| id == "select.anchorsMany").map(|(_, p)| p.clone()).unwrap(); + let path = restore["items"].as_array().unwrap().iter().find(|i| i["id"] == json!(b.0)).cloned().unwrap(); + assert_eq!(path["anchors"], json!([]), "{restore}"); +} + #[test] fn assigning_the_selection_clears_a_layers_panel_target() { let (mut s, a, _) = doc(); @@ -733,6 +807,28 @@ fn a_document_preset_is_an_instance_of_its_class() { assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); } +/// The values the presets hold count against the run's heap, a value assigned again in place of +/// the one before it. +#[test] +fn document_preset_values_are_bounded_by_the_runs_heap() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let big = "var s = 'a'; while (s.length < (1 << 19)) s += s;"; + let again = + format!("#targetengine presets\n{big} var p = new DocumentPreset(); for (var k = 0; k < 40; k++) p.title = s + k; vc.log(p.title.length);"); + assert_eq!(log(&mut s, &again), vec![json!(524_290)]); + let many = format!( + "#targetengine presets\n{big} var m = '';\ + try {{ for (var k = 0; k < 40; k++) {{ var p = new DocumentPreset(); p.title = s; }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\ + vc.log(k < 40); vc.log(m);" + ); + let out = log(&mut s, &many); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); @@ -928,20 +1024,52 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// File › Revert loads objects with the ids they were saved with: an object or a layer read before +/// the revert does not name the loaded one. +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, a, _) = doc(); + let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { + let source = format!("var i = app.activeDocument.pageItems[0], l = i.parent; i.name = 'before'; vc.run('file.revert'); {read};"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{read}: {e}"); + } + // Objects read after the revert are the loaded ones. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p[0].name = 'before'; vc.run('file.revert');\ + app.activeDocument.pageItems[0].name = 'loaded'; vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(2)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("loaded")); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&b.0.to_string()), "{e}"); - assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The script catches the error and finds both objects still there before the run ends, so the + // run's own rollback cannot hide a deletion. + let caught = "var p = app.activeDocument.pageItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); // A locked object inside an unlocked group stops it too. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&g.to_string()), "{e}"); + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&g.to_string()), "{out:?}"); + assert_eq!(out[1], json!(3)); assert!(s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); @@ -1002,8 +1130,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy().to_string(); + let (p, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 2af2fc130f..7380cc574c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -349,6 +349,10 @@ fn reflected_members(class: &HostClass) -> Result, String> { if out.iter().any(|r| *r.name == **name) { return Err(format!("the host class {} names the member {name} twice", class.name)); } + // The prototype's `constructor` is the class's own constructor. + if name == "constructor" { + return Err(format!("the host class {} names a member constructor, which is the name of its constructor", class.name)); + } let access = match member { HostMember::Get(_) => Access::ReadOnly, HostMember::Property { .. } => Access::ReadWrite, diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index a84c221d3a..0b6b7fffff 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -227,6 +227,7 @@ fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[I let methods = info_array(interp, methods)?; interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.object_mut(find)?.extensible = false; interp.temp_roots.push(Value::Object(find)); let r = interp.new_object(); interp.temp_roots.push(Value::Object(r)); diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs index 3e8827cf4f..e28247e162 100644 --- a/crates/js/src/reflect_tests.rs +++ b/crates/js/src/reflect_tests.rs @@ -112,13 +112,20 @@ fn a_reflection_cannot_be_changed() { [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); // In strict mode each one throws a TypeError. - for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + for write in + ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find", "x.find.extra = 1"] + { assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); } assert_eq!( - text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), - "true true true" + text( + &mut r, + "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments) + ' ' + Object.isFrozen(x.find)" + ), + "true true true true" ); + // The frozen `find` still finds. + assert_eq!(text(&mut r, "x.find('a').name"), "a"); } #[test] @@ -239,4 +246,11 @@ fn info_for_a_member_a_class_does_not_have_is_refused() { class.members.push(("size".into(), HostMember::Get(constant(1.0)))); let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); assert!(e.message.contains("names the member size twice"), "{}", e.message); + // `constructor` is the class's own constructor, so no member may take its name. + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("constructor".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names a member constructor"), "{}", e.message); + assert_eq!(text(&mut r, "typeof Item"), "undefined"); } diff --git a/docs/mcp.md b/docs/mcp.md index eff8b953f8..8219fb3d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2631,7 +2631,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + starts with the defaults that page gives. The values a run's `DocumentPreset` objects hold together may not take + more than the run's heap; an assignment past that throws a `RangeError`, and a value assigned again replaces the + one before it in that count. A preset's `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a @@ -2648,7 +2650,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds, widened to take in the direction points of every path in the object), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same @@ -2670,16 +2672,16 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active - tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + tab as it was. A bad value throws an error and changes nothing. An object that was deleted, that was read before + `file.revert` reloaded its document, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + a list of at most 10,000, `null` or `[]`; `undefined`, such as an index past the end of `pageItems`, throws a + `TypeError`, and an object that cannot be selected throws `Cannot select`, both with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, From 99e07b0f6bd5129ffbc46c2b33a86d1e19542272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:40:07 -0800 Subject: [PATCH 030/298] Scripts: DocumentPreset arrays count each element against the heap The heap limit on DocumentPreset values counted a boolean as 4 bytes, while the host keeps a whole value for each array element, so arrays kept by many presets could hold several times the run's heap. The limit now counts the host's copy: a value for the field and for each element or property, plus the text of its strings and property names. --- crates/engine/src/script/dom.rs | 16 ++++++++++++++-- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0753cc5263..8054a1b174 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -996,7 +996,7 @@ fn new_preset(h: &Host) -> Answer { item("numArtboards", num(1.0)), item("width", num(612.0)), ]; - hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?; presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } @@ -1012,6 +1012,18 @@ fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result Ok(()) } +/// The bytes the host's copy of `d` takes: a `Data` for the value and each element or property +/// in it, plus the text of its strings and property names. +fn held_bytes(d: &Data) -> u64 { + let owned = match d { + Data::String(s) => s.len() as u64, + Data::Array(a) => a.iter().map(held_bytes).sum(), + Data::Object(o) => o.iter().map(|(k, v)| (size_of::() + k.len()) as u64 + held_bytes(v)).sum(), + Data::Undefined | Data::Null | Data::Bool(_) | Data::Number(_) => 0, + }; + size_of::() as u64 + owned +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1067,7 +1079,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { // The values the presets hold now count against the run's heap: a value assigned again // replaces the one before it. let at = fields.iter().position(|(k, _)| k == key); - hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + hold_preset_bytes(&h, at.map_or(0, |n| held_bytes(&fields[n].1)), held_bytes(&value))?; match at { Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d0cb4e7ecd..039d5d17e8 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -829,6 +829,24 @@ fn document_preset_values_are_bounded_by_the_runs_heap() { assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); } +/// An array a preset holds counts a whole value for each element, so arrays of booleans kept by +/// many presets stop at the run's heap too. +#[test] +fn document_preset_arrays_count_each_element_they_hold() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar a = []; for (var i = 0; i < 20000; i++) a.push(true); var m = '';\ + try { for (var k = 0; k < 40; k++) { var p = new DocumentPreset(); p.title = a; } } catch (e) { m = e.name + ': ' + e.message; }\ + vc.log(k < 40); vc.log(m);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); From b19d017c317132873d2f69fd9961dec383f4e3f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:46:20 -0800 Subject: [PATCH 031/298] JavaScript: Map, Set, WeakMap, WeakSet and typed arrays in ES2015 realms A realm with Options::es2015 now has Map, Set, WeakMap and WeakSet, and ArrayBuffer, DataView and the nine typed arrays from Int8Array to Float64Array with %TypedArray%.from, of and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2). A realm without the option, the ExtendScript realm included, has none of these names. - Map and Set compare keys with SameValueZero and keep insertion order. forEach and iterators skip entries deleted before they reach them and visit entries added during the walk; the collector removes holes and moves live iterators. - WeakMap and WeakSet hold their keys weakly. The collector marks a WeakMap value only once its key is reachable another way and drops the entries of unreachable keys, also when a value refers to its key. - Typed arrays store elements little-endian; DataView is big-endian unless littleEndian is true. Numeric property names are elements or nothing, with the element descriptors of later editions. Copies to the same element type keep every bit. - An ArrayBuffer longer than 2^32 - 1 bytes or than the heap limit is a RangeError before anything is allocated, and every element a method visits takes fuel. - Until the language has iterators, the collection constructors and %TypedArray%.from read an array, a string by code point or an object with a length, by index. A typed array constructor reads an array or an object with a length the same way, and converts a first argument that is not an object to a length. - The %TypedArray%.prototype methods that share an Array method use the element count, and an Array method called on a typed array reads its length property. Array methods visit every element of a typed array longer than 4,096. - Check Script counts new of these constructors as the language's. test262 runs the Map, Set, WeakMap, WeakSet, ArrayBuffer, DataView, TypedArray and TypedArrayConstructors folders in ES2015 realms. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/array.rs | 39 +- crates/js/src/builtins/binary.rs | 1143 +++++++++++++++++++++++++ crates/js/src/builtins/collections.rs | 696 +++++++++++++++ crates/js/src/collections_tests.rs | 412 +++++++++ crates/js/src/heap.rs | 328 ++++++- crates/js/src/interp.rs | 52 +- crates/js/src/lib.rs | 20 +- crates/js/tests/test262.rs | 114 ++- crates/scriptcheck/src/catalog.rs | 20 +- crates/scriptcheck/src/tests.rs | 11 + docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 13 files changed, 2832 insertions(+), 29 deletions(-) create mode 100644 crates/js/src/builtins/binary.rs create mode 100644 crates/js/src/builtins/collections.rs create mode 100644 crates/js/src/collections_tests.rs diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..6c2eff73ca 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,13 +3,16 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Map`, `Set`, `WeakMap` and +//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can //! run past [`crate::Limits`]. mod array; +pub(crate) mod binary; +pub(crate) mod collections; pub(crate) mod extensions; mod global; mod json; @@ -145,6 +148,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + collections::install(interp)?; + binary::install(interp)?; + } Ok(()) } @@ -165,8 +172,16 @@ fn key_of(n: f64) -> Key { number_to_str(n).flat() } -/// ToUint32 of an object's `length`. +/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array +/// method it shares, the typed array's length is its element count, whatever its `length` +/// property says (ECMA-262 6.0 section 22.2.3). fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + if interp.typed_length == Some(o) { + interp.typed_length = None; + if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) { + return Ok(u32::try_from(view.length).unwrap_or(u32::MAX)); + } + } let len = interp.get_from(o, &key("length"), &Value::Object(o))?; Ok(to_uint32(interp.to_number(&len)?)) } diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..1c91d602b0 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option { Some(n) } -/// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. +/// The indices a String object or a typed array holds without properties for them. +fn index_count(class: &Class) -> usize { + match class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + } +} + +/// The objects of the prototype chain from `obj`, with how many properties (and String object or +/// typed array indices) each holds. fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { let Some(o) = interp.heap.object(id) else { break }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - out.push((id, o.props.len().saturating_add(string_len))); + out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } out @@ -141,8 +149,7 @@ impl Indices { } interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?; let Some(o) = interp.heap.object(id) else { continue }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); + let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); for p in present { for map in &self.maps { let p = p as i64; @@ -335,13 +342,13 @@ fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { } /// `Array.prototype.join` (section 15.4.4.5). -fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let separator = arg(args, 0); with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item)) } /// `Array.prototype.toLocaleString` (section 15.4.4.3). -fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { +pub(super) fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } @@ -413,7 +420,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { +pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let middle = len / 2; @@ -692,7 +699,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js // ---- searching ---- /// `Array.prototype.indexOf` (section 15.4.4.14). -fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -717,7 +724,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu } /// `Array.prototype.lastIndexOf` (section 15.4.4.15). -fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -794,15 +801,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe }) } -fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Every) } -fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Some) } -fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Visit) } @@ -852,10 +859,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu }) } -fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, false) } -fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, true) } diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs new file mode 100644 index 0000000000..8c10723a74 --- /dev/null +++ b/crates/js/src/builtins/binary.rs @@ -0,0 +1,1143 @@ +//! `ArrayBuffer`, `DataView` and the typed arrays (ECMA-262 6.0 sections 24.1, 24.2 and 22.2): +//! `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, +//! `Uint32Array`, `Float32Array` and `Float64Array`, with `%TypedArray%` and its prototype's +//! methods. A realm has them with [`crate::Options::es2015`]. +//! +//! A buffer's bytes are zero when it is made and never change length; no operation detaches +//! one. Views share their buffer's bytes. Typed arrays store their elements little-endian on +//! every platform, and a `DataView` reads and writes big-endian unless `littleEndian` is true. +//! A typed array's numeric property names are its elements or nothing (section 9.4.5, with the +//! element descriptors of later editions: writable, enumerable and configurable, and an element +//! that cannot be deleted); [`crate::interp::Interp`] calls [`element`], [`set_element`] and +//! [`define_element`] for them. +//! +//! A buffer longer than the realm's heap limit, or than 2^32 - 1 bytes, is a `RangeError`, and +//! every buffer's bytes are checked against the heap before they are allocated. Every element +//! a method visits takes a unit of fuel, and a sort's comparisons take one each. +//! +//! The language has no iterators yet, so constructing from an object and `%TypedArray%.from` +//! read an array, a string (by code point) or an object with a `length`, by index. + +use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, require_callable, to_integer}; +use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; +use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; + +/// The longest buffer, in bytes. +const MAX_BUFFER: u64 = u32::MAX as u64; + +/// The bytes each item a method gathers before it writes them is charged. +const ITEM_BYTES: usize = 16; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + install_array_buffer(interp)?; + install_data_view(interp)?; + install_typed_arrays(interp) +} + +fn install_array_buffer(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.array_buffer_proto = proto; + let ctor = native(interp, "ArrayBuffer", array_buffer_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "ArrayBuffer", ctor, proto)?; + method(interp, ctor, "isView", is_view, 1)?; + getter(interp, proto, "get byteLength", buffer_byte_length)?; + method(interp, proto, "slice", buffer_slice, 2) +} + +fn install_data_view(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.data_view_proto = proto; + let ctor = native(interp, "DataView", data_view_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "DataView", ctor, proto)?; + getter(interp, proto, "get buffer", view_buffer)?; + getter(interp, proto, "get byteLength", view_byte_length)?; + getter(interp, proto, "get byteOffset", view_byte_offset)?; + let methods: [(&'static str, NativeFn, u32); 16] = [ + ("getInt8", get_int8, 1), + ("getUint8", get_uint8, 1), + ("getInt16", get_int16, 1), + ("getUint16", get_uint16, 1), + ("getInt32", get_int32, 1), + ("getUint32", get_uint32, 1), + ("getFloat32", get_float32, 1), + ("getFloat64", get_float64, 1), + ("setInt8", set_int8, 2), + ("setUint8", set_uint8, 2), + ("setInt16", set_int16, 2), + ("setUint16", set_uint16, 2), + ("setInt32", set_int32, 2), + ("setUint32", set_uint32, 2), + ("setFloat32", set_float32, 2), + ("setFloat64", set_float64, 2), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + Ok(()) +} + +fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.typed_array_proto = proto; + let ctor = native(interp, "TypedArray", abstract_ctor, 0, NativeKind::Plain, true)?; + interp.intrinsics.es2015.typed_array_ctor = ctor; + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + data(interp, proto, "constructor", Value::Object(ctor), HIDDEN)?; + method(interp, ctor, "from", typed_from, 1)?; + method(interp, ctor, "of", typed_of, 0)?; + for (name, f) in + [("get buffer", ta_buffer as NativeFn), ("get byteLength", ta_byte_length), ("get byteOffset", ta_byte_offset), ("get length", ta_length)] + { + getter(interp, proto, name, f)?; + } + let methods: [(&'static str, NativeFn, u32); 23] = [ + ("copyWithin", copy_within, 2), + ("entries", ta_entries, 0), + ("every", ta_every, 1), + ("fill", fill, 1), + ("filter", filter, 1), + ("find", find, 1), + ("findIndex", find_index, 1), + ("forEach", ta_for_each, 1), + ("indexOf", ta_index_of, 1), + ("join", ta_join, 1), + ("keys", ta_keys, 0), + ("lastIndexOf", ta_last_index_of, 1), + ("map", map, 1), + ("reduce", ta_reduce, 1), + ("reduceRight", ta_reduce_right, 1), + ("reverse", ta_reverse, 0), + ("set", set, 1), + ("slice", slice, 2), + ("some", ta_some, 1), + ("sort", sort, 1), + ("subarray", subarray, 2), + ("toLocaleString", ta_to_locale_string, 0), + ("values", ta_values, 0), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). + let array_proto = interp.intrinsics.array_proto; + let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; + interp.define(proto, key("toString"), crate::heap::Prop::Data { value: to_string, flags: HIDDEN })?; + + let ctors: [NativeFn; 9] = + [int8_ctor, uint8_ctor, uint8_clamped_ctor, int16_ctor, uint16_ctor, int32_ctor, uint32_ctor, float32_ctor, float64_ctor]; + for (elem, f) in Elem::ALL.into_iter().zip(ctors) { + let sub_proto = new_proto(interp, proto); + let sub = native(interp, elem.name(), f, 3, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(sub) { + o.proto = Some(ctor); + } + super::constructor(interp, elem.name(), sub, sub_proto)?; + #[allow(clippy::cast_precision_loss)] + let size = Value::Number(elem.size() as f64); + data(interp, sub, "BYTES_PER_ELEMENT", size.clone(), 0)?; + data(interp, sub_proto, "BYTES_PER_ELEMENT", size, 0)?; + if let Some(slot) = interp.intrinsics.es2015.typed_ctors.get_mut(elem.index()) { + *slot = sub; + } + if let Some(slot) = interp.intrinsics.es2015.typed_protos.get_mut(elem.index()) { + *slot = sub_proto; + } + } + Ok(()) +} + +// ---- elements ---- + +/// CanonicalNumericIndexString (section 7.1.16): the number a property name stands for when it +/// is the canonical text of that number, `-0` included. +pub(crate) fn canonical_index(k: &[u16]) -> Option { + if let Some(i) = array_index(k) { + return Some(f64::from(i)); + } + let first = *k.first()?; + if !(u16::from(b'0')..=u16::from(b'9')).contains(&first) && !b"-IN".iter().any(|c| u16::from(*c) == first) { + return None; + } + if k == [u16::from(b'-'), u16::from(b'0')] { + return Some(-0.0); + } + let n = string_to_number(k); + (*number_to_str(n).flat() == *k).then_some(n) +} + +/// The position of the element `n` names in a typed array of `length` elements, if it names one. +fn valid_index(n: f64, length: usize) -> Option { + if n.fract() != 0.0 || (n == 0.0 && n.is_sign_negative()) || n < 0.0 || !n.is_finite() { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = n as usize; + (i < length).then_some(i) +} + +/// The buffer's bytes. +fn bytes(interp: &Interp, buffer: ObjId) -> Option<&[u8]> { + match &interp.heap.object(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +fn bytes_mut(interp: &mut Interp, buffer: ObjId) -> Option<&mut [u8]> { + match &mut interp.heap.object_mut(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +/// Reads a value of `elem` from the start of `b` (GetValueFromBuffer, section 24.1.1.5). +fn decode(b: &[u8], elem: Elem, little: bool) -> Option { + let size = elem.size(); + let raw = b.get(..size)?; + let mut bits = 0u64; + for j in 0..size { + let byte = if little { raw.get(j) } else { raw.get(size - 1 - j) }; + bits |= u64::from(*byte?) << (8 * j); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Some(match elem { + Elem::Int8 => f64::from(bits as u8 as i8), + Elem::Uint8 | Elem::Uint8Clamped => f64::from(bits as u8), + Elem::Int16 => f64::from(bits as u16 as i16), + Elem::Uint16 => f64::from(bits as u16), + Elem::Int32 => f64::from(bits as u32 as i32), + Elem::Uint32 => f64::from(bits as u32), + Elem::Float32 => f64::from(f32::from_bits(bits as u32)), + Elem::Float64 => f64::from_bits(bits), + }) +} + +/// ToUint8Clamp (section 7.1.11): rounds to the nearest integer in 0 to 255, ties to even. +pub(crate) fn to_uint8_clamp(n: f64) -> u8 { + if n.is_nan() || n <= 0.0 { + return 0; + } + if n >= 255.0 { + return 255; + } + let f = n.floor(); + let r = if f + 0.5 < n { + f + 1.0 + } else if n < f + 0.5 || f % 2.0 == 0.0 { + f + } else { + f + 1.0 + }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = r as u8; + byte +} + +/// Writes `n` as a value of `elem` at the start of `b` (SetValueInBuffer, section 24.1.1.6). +/// The integer types keep the low bits of ToUint32, which equal those of ToInt8, ToInt16 and +/// ToInt32. +fn encode(b: &mut [u8], elem: Elem, n: f64, little: bool) { + let size = elem.size(); + let bits = match elem { + Elem::Uint8Clamped => u64::from(to_uint8_clamp(n)), + #[allow(clippy::cast_possible_truncation)] + Elem::Float32 => u64::from((n as f32).to_bits()), + Elem::Float64 => n.to_bits(), + _ => u64::from(to_uint32(n)), + }; + for j in 0..size { + let slot = if little { b.get_mut(j) } else { b.get_mut(size - 1 - j) }; + if let Some(slot) = slot { + #[allow(clippy::cast_possible_truncation)] + let byte = (bits >> (8 * j)) as u8; + *slot = byte; + } + } +} + +/// The element of `view` at the index `n`, or `None` when `n` names no element. +pub(crate) fn element(interp: &Interp, view: &View, n: f64) -> Option { + let i = valid_index(n, view.length)?; + let at = view.offset.checked_add(i.checked_mul(view.elem.size())?)?; + decode(bytes(interp, view.buffer)?.get(at..)?, view.elem, true) +} + +/// The view of the typed array `id`. +fn view_of(interp: &Interp, id: ObjId) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(view) => Some(**view), + _ => None, + } +} + +/// Writes `n` to the element at position `i` of `view`, when there is one. +fn write(interp: &mut Interp, view: &View, i: usize, n: f64) { + let Some(at) = i.checked_mul(view.elem.size()).and_then(|o| o.checked_add(view.offset)) else { return }; + if i < view.length + && let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) + { + encode(b, view.elem, n, true); + } +} + +/// Copies `count` elements of `src` from position `from` to `dst` at position `to` byte for byte, as +/// a typed array is copied to one of the same element type (sections 22.2.3.22.2, 22.2.3.23 and +/// 22.2.4.3), so every bit pattern, a NaN's included, is kept. Overlapping ranges of one buffer copy +/// correctly. Each element takes a unit of fuel. +fn copy_elements(interp: &mut Interp, src: &View, from: usize, dst: &View, to: usize, count: usize) -> JsResult<()> { + for _ in 0..count { + interp.use_fuel()?; + } + let size = src.elem.size(); + let (s, d, n) = (src.offset + from * size, dst.offset + to * size, count * size); + if src.buffer == dst.buffer { + if let Some(b) = bytes_mut(interp, src.buffer) + && s + n <= b.len() + && d + n <= b.len() + { + b.copy_within(s..s + n, d); + } + return Ok(()); + } + // The destination's bytes are moved out while the source's are read, so no third copy is made. + let mut out = match &mut interp.object_mut(dst.buffer)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(from_bytes), Some(to_bytes)) = (bytes(interp, src.buffer).and_then(|b| b.get(s..s + n)), out.get_mut(d..d + n)) { + to_bytes.copy_from_slice(from_bytes); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(dst.buffer)?.class { + *b = out; + } + Ok(()) +} + +/// The number a typed array `id`'s numeric property name `k` stands for. +pub(crate) fn typed_key(interp: &Interp, id: ObjId, k: &[u16]) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(_) => canonical_index(k), + _ => None, + } +} + +/// `[[Set]]` of a numeric name of a typed array: the value is converted with ToNumber, then +/// written when the index names an element and ignored otherwise. +pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> JsResult<()> { + let num = interp.to_number(v)?; + if let Some(view) = view_of(interp, id) + && let Some(i) = valid_index(n, view.length) + { + write(interp, &view, i, num); + } + Ok(()) +} + +/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the +/// configurable elements of later editions). +pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let view = view_of(interp, id); + let index = canonical_index(k).zip(view).and_then(|(n, view)| valid_index(n, view.length)); + let refused = + index.is_none() || desc.configurable == Some(false) || desc.enumerable == Some(false) || desc.is_accessor() || desc.writable == Some(false); + if refused { + if throw { + let name = String::from_utf16_lossy(k); + return Err(interp.type_error(&format!("cannot define property '{name}' of a typed array"))); + } + return Ok(false); + } + if let (Some(v), Some(view), Some(i)) = (&desc.value, view, index) { + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(true) +} + +// ---- making buffers and views ---- + +/// ToIndex (section 7.1.17 of later editions): `undefined` is 0, and a negative or too large +/// integer is a `RangeError`. +fn to_index(interp: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(0); + } + let n = to_integer(interp, v)?; + if !(0.0..=9_007_199_254_740_991.0).contains(&n) { + return Err(interp.throw(ErrorType::Range, &format!("{what} must be an integer from 0 to 2^53 - 1"))); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(n as u64) +} + +/// A new zeroed buffer of `len` bytes. A length past [`MAX_BUFFER`] or the heap limit is a +/// `RangeError`; otherwise the bytes and `extra` more are reserved before the buffer is +/// allocated. +fn new_buffer(interp: &mut Interp, len: u64, extra: usize) -> JsResult { + if len > MAX_BUFFER || len > interp.limits.heap_bytes as u64 { + return Err(interp.throw(ErrorType::Range, &format!("an array buffer of {len} bytes is larger than the heap limit allows"))); + } + let len = usize::try_from(len).map_err(|_| interp.throw(ErrorType::Range, "the array buffer is too large"))?; + interp.reserve_heap(OBJECT_BYTES.saturating_add(len).saturating_add(extra))?; + let mut b = Vec::new(); + if b.try_reserve_exact(len).is_err() { + return Err(interp.throw(ErrorType::Range, "the memory for the array buffer could not be allocated")); + } + b.resize(len, 0); + let proto = interp.intrinsics.es2015.array_buffer_proto; + let o = interp.heap.alloc_object(Object::new(Class::ArrayBuffer(b.into_boxed_slice()), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(len); + Ok(o) +} + +/// A new view object of `class` on a buffer that is reachable. Its heap was reserved before. +fn new_view(interp: &mut Interp, class: Class, proto: ObjId) -> ObjId { + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + o +} + +fn typed_proto(interp: &Interp, elem: Elem) -> ObjId { + interp.intrinsics.es2015.typed_protos.get(elem.index()).copied().unwrap_or(interp.intrinsics.es2015.typed_array_proto) +} + +/// A new typed array of `len` zero elements of `elem`, with a new buffer. +fn new_typed(interp: &mut Interp, elem: Elem, len: u64) -> JsResult { + let byte_len = len.saturating_mul(elem.size() as u64); + let buffer = new_buffer(interp, byte_len, OBJECT_BYTES + VIEW_BYTES)?; + let length = usize::try_from(len).unwrap_or(0); + let proto = typed_proto(interp, elem); + Ok(new_view(interp, Class::TypedArray(Box::new(View { buffer, offset: 0, length, elem })), proto)) +} + +/// `new ArrayBuffer(length)` (section 24.1.2.1). +fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("ArrayBuffer must be called with new")); + } + let len = to_index(interp, &arg(args, 0), "the length")?; + new_buffer(interp, len, 0).map(Value::Object) +} + +/// `ArrayBuffer.isView` (section 24.1.3.1). +fn is_view(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let view = + arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::DataView(_) | Class::TypedArray(_))); + Ok(Value::Bool(view)) +} + +fn this_buffer(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if bytes(interp, o).is_some() => Ok(o), + _ => Err(interp.type_error(&format!("ArrayBuffer.prototype.{name} was called on a value that is not an ArrayBuffer"))), + } +} + +fn buffer_len(interp: &Interp, o: ObjId) -> usize { + bytes(interp, o).map_or(0, <[u8]>::len) +} + +fn buffer_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "byteLength")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(buffer_len(interp, o) as f64)) +} + +/// A relative index (as `slice` reads its arguments): negative counts from `len`, and the result +/// is clamped to 0 to `len`. `undefined` gives `default`. +fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(default); + } + let n = to_integer(interp, v)?; + #[allow(clippy::cast_precision_loss)] + let len_f = len as f64; + let r = if n < 0.0 { (len_f + n).max(0.0) } else { n.min(len_f) }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(r as usize) +} + +/// `ArrayBuffer.prototype.slice` (section 24.1.4.3). +fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "slice")?; + let len = buffer_len(interp, o); + let first = relative(interp, &arg(args, 0), len, 0)?; + let last = relative(interp, &arg(args, 1), len, len)?; + let count = last.saturating_sub(first); + // Each copied byte takes a unit of fuel, charged before the copy is made. + for _ in 0..count { + interp.use_fuel()?; + } + let new = interp.rooted(std::slice::from_ref(&this), |i| new_buffer(i, count as u64, 0))?; + // The new buffer's bytes are moved out while the source's are read, so no third copy is made. + let mut dst = match &mut interp.object_mut(new)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(src), Some(to)) = (bytes(interp, o).and_then(|b| b.get(first..first + count)), dst.get_mut(..count)) { + to.copy_from_slice(src); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(new)?.class { + *b = dst; + } + Ok(Value::Object(new)) +} + +// ---- DataView ---- + +/// `new DataView(buffer, byteOffset, byteLength)` (section 24.2.2.1). +fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("DataView must be called with new")); + } + let buffer = match arg(args, 0).as_object() { + Some(o) if bytes(interp, o).is_some() => o, + _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), + }; + let offset = to_index(interp, &arg(args, 1), "the byte offset")?; + let len = buffer_len(interp, buffer) as u64; + if offset > len { + return Err(interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer")); + } + let view_len = match arg(args, 2) { + Value::Undefined => len - offset, + v => to_index(interp, &v, "the byte length")?, + }; + if offset.saturating_add(view_len) > len { + return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = interp.intrinsics.es2015.data_view_proto; + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; + Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) +} + +fn this_data_view(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + if let Some(Class::DataView(view)) = this.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + return Ok(**view); + } + Err(interp.type_error(&format!("DataView.prototype.{name} was called on a value that is not a DataView"))) +} + +fn view_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_data_view(interp, &this, "buffer")?.buffer)) +} + +fn view_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteLength")?.length as f64)) +} + +fn view_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteOffset")?.offset as f64)) +} + +/// The byte position in the buffer of a `DataView` access of `elem` at `index`, or a +/// `RangeError` when it does not fit in the view (sections 24.2.1.1 and 24.2.1.2). +fn view_position(interp: &mut Interp, view: &View, index: u64, elem: Elem) -> JsResult { + let end = index.saturating_add(elem.size() as u64); + if end > view.length as u64 { + return Err(interp.throw(ErrorType::Range, "the offset is outside the bounds of the DataView")); + } + Ok(view.offset + usize::try_from(index).unwrap_or(0)) +} + +/// GetViewValue (section 24.2.1.1). +fn view_get(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let little = arg(args, 1).truthy(); + let at = view_position(interp, &view, index, elem)?; + let n = bytes(interp, view.buffer).and_then(|b| b.get(at..)).and_then(|b| decode(b, elem, little)).unwrap_or(0.0); + Ok(Value::Number(n)) +} + +/// SetViewValue (section 24.2.1.2): the offset, then the value, then `littleEndian` are read +/// before the bounds are checked. +fn view_set(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let n = interp.to_number(&arg(args, 1))?; + let little = arg(args, 2).truthy(); + let at = view_position(interp, &view, index, elem)?; + if let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) { + encode(b, elem, n, little); + } + Ok(Value::Undefined) +} + +macro_rules! view_methods { + ($($get:ident, $set:ident, $elem:ident, $getname:literal, $setname:literal;)*) => { + $( + fn $get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_get(interp, &this, args, Elem::$elem, $getname) + } + + fn $set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_set(interp, &this, args, Elem::$elem, $setname) + } + )* + }; +} + +view_methods! { + get_int8, set_int8, Int8, "getInt8", "setInt8"; + get_uint8, set_uint8, Uint8, "getUint8", "setUint8"; + get_int16, set_int16, Int16, "getInt16", "setInt16"; + get_uint16, set_uint16, Uint16, "getUint16", "setUint16"; + get_int32, set_int32, Int32, "getInt32", "setInt32"; + get_uint32, set_uint32, Uint32, "getUint32", "setUint32"; + get_float32, set_float32, Float32, "getFloat32", "setFloat32"; + get_float64, set_float64, Float64, "getFloat64", "setFloat64"; +} + +// ---- typed array constructors ---- + +/// `%TypedArray%` itself (section 22.2.1.1) cannot be called or constructed. +fn abstract_ctor(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(interp.type_error("TypedArray cannot be called or constructed; use a typed array constructor such as Uint8Array")) +} + +/// `new Int8Array(…)` and the other typed array constructors (section 22.2.4). +fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Elem) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{} must be called with new", elem.name()))); + } + let first = arg(args, 0); + let Value::Object(o) = first else { + let len = to_index(interp, &first, "the length")?; + return new_typed(interp, elem, len).map(Value::Object); + }; + if bytes(interp, o).is_some() { + return typed_on_buffer(interp, o, &arg(args, 1), &arg(args, 2), elem).map(Value::Object); + } + if let Some(src) = view_of(interp, o) { + let ta = new_typed(interp, elem, src.length as u64)?; + let dst = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if src.elem == elem { + copy_elements(interp, &src, 0, &dst, 0, src.length)?; + return Ok(Value::Object(ta)); + } + for i in 0..src.length { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let n = element(interp, &src, i as f64).unwrap_or(0.0); + write(interp, &dst, i, n); + } + return Ok(Value::Object(ta)); + } + let len = length_of(interp, o)?; + let ta = new_typed(interp, elem, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; + Ok(Value::Object(ta)) +} + +/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, +/// each converted with ToNumber. +fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { + let Value::Object(o) = src else { return Ok(()) }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(()) +} + +/// A typed array on part of `buffer` (section 22.2.4.5). +fn typed_on_buffer(interp: &mut Interp, buffer: ObjId, offset: &Value, length: &Value, elem: Elem) -> JsResult { + let size = elem.size() as u64; + let offset = to_index(interp, offset, "the byte offset")?; + if !offset.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the byte offset of a {} must be a multiple of {size}", elem.name()))); + } + let new_length = match length { + Value::Undefined => None, + v => Some(to_index(interp, v, "the length")?), + }; + let buf_len = buffer_len(interp, buffer) as u64; + let byte_len = match new_length { + None => { + if !buf_len.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the buffer's length must be a multiple of {size}"))); + } + buf_len.checked_sub(offset).ok_or_else(|| interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer"))? + } + Some(n) => n.saturating_mul(size), + }; + if offset.saturating_add(byte_len) > buf_len { + return Err(interp.throw(ErrorType::Range, "the typed array does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = typed_proto(interp, elem); + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(byte_len / size).unwrap_or(0), elem }; + Ok(new_view(interp, Class::TypedArray(Box::new(view)), proto)) +} + +macro_rules! typed_ctors { + ($($f:ident, $elem:ident;)*) => { + $( + fn $f(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + typed_ctor(interp, args, constructing, Elem::$elem) + } + )* + }; +} + +typed_ctors! { + int8_ctor, Int8; + uint8_ctor, Uint8; + uint8_clamped_ctor, Uint8Clamped; + int16_ctor, Int16; + uint16_ctor, Uint16; + int32_ctor, Int32; + uint32_ctor, Uint32; + float32_ctor, Float32; + float64_ctor, Float64; +} + +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let ctors = interp.intrinsics.es2015.typed_ctors; + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) +} + +/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). +fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !interp.is_callable(&this) { + return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); + } + let map_fn = arg(args, 1); + let mapping = !matches!(map_fn, Value::Undefined); + if mapping { + require_callable(interp, &map_fn, "the map function")?; + } + let this_arg = arg(args, 2); + let source = arg(args, 0); + if !matches!(source, Value::String(_)) { + // An array-like source: each element is read, mapped and written before the next is read. + let src = interp.to_object(&source)?; + let src_value = Value::Object(src); + let len = length_of(interp, src)?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(Value::Object(ta)) + }); + } + // A string is read by code point first, as an iterable source is, and then mapped. + let mark = interp.temp_roots.len(); + let mut held = crate::interp::HeldBytes::new(interp); + let gathered = for_each_item(interp, &source, false, |interp, item| { + held.add(interp, ITEM_BYTES)?; + interp.temp_roots.push(item); + Ok(()) + }); + let result = gathered.and_then(|()| { + let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; + interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, item) in items.into_iter().enumerate() { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }); + interp.temp_roots.truncate(mark); + drop(held); + result +} + +/// `%TypedArray%.of(...items)` (section 22.2.2.2). +fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(ta)], |interp| { + for (i, v) in args.iter().enumerate() { + interp.use_fuel()?; + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }) +} + +// ---- %TypedArray%.prototype ---- + +/// The typed array a method was called on (ValidateTypedArray, section 22.2.3.5.1). +fn this_typed(interp: &mut Interp, this: &Value, name: &str) -> JsResult<(ObjId, View)> { + if let Some(o) = this.as_object() + && let Some(view) = view_of(interp, o) + { + return Ok((o, view)); + } + Err(interp.type_error(&format!("TypedArray.prototype.{name} was called on a value that is not a typed array"))) +} + +fn ta_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_typed(interp, &this, "buffer")?.1.buffer)) +} + +fn ta_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let view = this_typed(interp, &this, "byteLength")?.1; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number((view.length * view.elem.size()) as f64)) +} + +fn ta_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "byteOffset")?.1.offset as f64)) +} + +fn ta_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "length")?.1.length as f64)) +} + +/// The element at position `i`, 0 past the end. +fn at(interp: &Interp, view: &View, i: usize) -> f64 { + #[allow(clippy::cast_precision_loss)] + element(interp, view, i as f64).unwrap_or(0.0) +} + +/// Runs the array prototype's generic method `f` on a typed array, after checking `this`. +/// The array method reads the typed array's element count as its length, not its `length` +/// property. +fn generic(interp: &mut Interp, this: Value, args: &[Value], name: &str, f: NativeFn) -> JsResult { + let (o, _) = this_typed(interp, &this, name)?; + let saved = interp.typed_length.replace(o); + let result = f(interp, this, args, false); + interp.typed_length = saved; + result +} + +macro_rules! generic_methods { + ($($f:ident, $name:literal, $array:path;)*) => { + $( + fn $f(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + generic(interp, this, args, $name, $array) + } + )* + }; +} + +generic_methods! { + ta_every, "every", array::every; + ta_some, "some", array::some; + ta_for_each, "forEach", array::for_each; + ta_index_of, "indexOf", array::index_of; + ta_last_index_of, "lastIndexOf", array::last_index_of; + ta_join, "join", array::join; + ta_reduce, "reduce", array::reduce; + ta_reduce_right, "reduceRight", array::reduce_right; + ta_reverse, "reverse", array::reverse; + ta_to_locale_string, "toLocaleString", array::to_locale_string; +} + +fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { + let (o, _) = this_typed(interp, this, name)?; + new_iter(interp, o, IterSource::Array, kind, None).map(Value::Object) +} + +fn ta_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Keys, "keys") +} + +fn ta_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Values, "values") +} + +fn ta_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Entries, "entries") +} + +/// `fill(value, start, end)` (section 22.2.3.8): the value is converted once, before the range. +fn fill(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "fill")?; + let n = interp.to_number(&arg(args, 0))?; + let start = relative(interp, &arg(args, 1), view.length, 0)?; + let end = relative(interp, &arg(args, 2), view.length, view.length)?; + for i in start..end { + interp.use_fuel()?; + write(interp, &view, i, n); + } + Ok(this) +} + +/// Calls `f(element, index, array)` for each element in order until `stop` says the result is +/// found; returns the index and the element. +fn search(interp: &mut Interp, this: &Value, args: &[Value], name: &str) -> JsResult> { + let (_, view) = this_typed(interp, this, name)?; + let f = arg(args, 0); + require_callable(interp, &f, "the predicate")?; + let this_arg = arg(args, 1); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + return Ok(Some((i, v))); + } + } + Ok(None) +} + +/// `find` (section 22.2.3.10). +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + Ok(search(interp, &this, args, "find")?.map_or(Value::Undefined, |(_, v)| Value::Number(v))) +} + +/// `findIndex` (section 22.2.3.11). +fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(search(interp, &this, args, "findIndex")?.map_or(-1.0, |(i, _)| i as f64))) +} + +/// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. +fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "map")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let out = new_typed(interp, view.elem, view.length as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(out)], |interp| { + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + let n = interp.to_number(&r)?; + write(interp, &dst, i, n); + } + Ok(Value::Object(out)) + }) +} + +/// A new typed array of `elem` holding `values`. +fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResult { + let out = new_typed(interp, elem, values.len() as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, n) in values.iter().enumerate() { + write(interp, &dst, i, *n); + } + Ok(out) +} + +/// `filter` (section 22.2.3.9). +fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "filter")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let mut held = crate::interp::HeldBytes::new(interp); + let mut kept = Vec::new(); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + held.add(interp, 8)?; + kept.push(v); + } + } + let out = typed_from_values(interp, view.elem, &kept)?; + drop(held); + Ok(Value::Object(out)) +} + +/// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. +fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "slice")?; + let start = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + let count = end.saturating_sub(start); + let out = new_typed(interp, view.elem, count as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + copy_elements(interp, &view, start, &dst, 0, count)?; + Ok(Value::Object(out)) +} + +/// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. +fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "subarray")?; + let begin = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; + let proto = typed_proto(interp, view.elem); + Ok(Value::Object(new_view(interp, Class::TypedArray(Box::new(sub)), proto))) +} + +/// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like +/// object's elements converted with ToNumber, starting at `offset`. A source that does not fit +/// is a `RangeError`. A typed array source is read in full before anything is written, so a +/// source on the same buffer copies correctly. +fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "set")?; + let offset = to_integer(interp, &arg(args, 1))?; + if offset < 0.0 { + return Err(interp.throw(ErrorType::Range, "the offset must not be negative")); + } + let source = arg(args, 0); + let src_view = source.as_object().and_then(|o| view_of(interp, o)); + let src_len = match (&source, src_view) { + (_, Some(v)) => v.length as u64, + (Value::Object(o), None) => length_of(interp, *o)?, + _ => { + let o = interp.to_object(&source)?; + length_of(interp, o)? + } + }; + #[allow(clippy::cast_precision_loss)] + if offset + src_len as f64 > view.length as f64 { + return Err(interp.throw(ErrorType::Range, "the source does not fit in the typed array at that offset")); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let offset = offset as usize; + let count = usize::try_from(src_len).unwrap_or(0); + if let Some(src) = src_view.filter(|src| src.elem == view.elem) { + copy_elements(interp, &src, 0, &view, offset, count)?; + return Ok(Value::Undefined); + } + if let Some(src) = src_view { + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, count.saturating_mul(8))?; + let mut values = Vec::with_capacity(count); + for i in 0..count { + interp.use_fuel()?; + values.push(at(interp, &src, i)); + } + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + let src = interp.to_object(&source)?; + interp.rooted(&[Value::Object(src)], |interp| { + for i in 0..count { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(src, &super::key_of(i as f64), &Value::Object(src))?; + let n = interp.to_number(&v)?; + write(interp, &view, offset + i, n); + } + Ok(Value::Undefined) + }) +} + +/// `copyWithin(target, start, end)` (section 22.2.3.5): moves the bytes of the range within the +/// buffer, overlapping ranges included. +fn copy_within(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "copyWithin")?; + let len = view.length; + let to = relative(interp, &arg(args, 0), len, 0)?; + let from = relative(interp, &arg(args, 1), len, 0)?; + let end = relative(interp, &arg(args, 2), len, len)?; + let count = end.saturating_sub(from).min(len - to); + copy_elements(interp, &view, from, &view, to, count)?; + Ok(this) +} + +/// The default order of `sort` (section 22.2.3.25): numeric, with `-0` before `+0` and `NaN` +/// last. +fn default_order(a: f64, b: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a.is_nan(), b.is_nan()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + _ if a == 0.0 && b == 0.0 => b.is_sign_negative().cmp(&a.is_sign_negative()), + _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal), + } +} + +/// Whether `b` goes before `a`: by `compare` when it is a function, the default order otherwise. +/// Each comparison takes a unit of fuel. +fn goes_before(interp: &mut Interp, compare: &Value, a: f64, b: f64) -> JsResult { + interp.use_fuel()?; + if matches!(compare, Value::Undefined) { + return Ok(default_order(b, a) == std::cmp::Ordering::Less); + } + let r = interp.call(compare, &Value::Undefined, &[Value::Number(a), Value::Number(b)])?; + let n = interp.to_number(&r)?; + Ok(n > 0.0) +} + +/// Sorts `values` stably with a merge sort whose comparisons may fail. +fn merge_sort(interp: &mut Interp, values: &mut Vec, compare: &Value) -> JsResult<()> { + let n = values.len(); + let mut buf = values.clone(); + let mut width = 1; + while width < n { + let mut lo = 0; + while lo < n { + let mid = (lo + width).min(n); + let hi = (lo + 2 * width).min(n); + let (mut i, mut j) = (lo, mid); + for slot in buf.iter_mut().take(hi).skip(lo) { + let take_right = match (values.get(i), values.get(j)) { + (Some(&a), Some(&b)) if i < mid && j < hi => goes_before(interp, compare, a, b)?, + _ => i >= mid, + }; + let pick = if take_right { &mut j } else { &mut i }; + *slot = values.get(*pick).copied().unwrap_or(0.0); + *pick += 1; + } + lo = hi; + } + std::mem::swap(values, &mut buf); + width *= 2; + } + Ok(()) +} + +/// `sort(comparefn)` (section 22.2.3.25). +fn sort(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let compare = arg(args, 0); + if !matches!(compare, Value::Undefined) { + require_callable(interp, &compare, "the comparison function")?; + } + let (_, view) = this_typed(interp, &this, "sort")?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, view.length.saturating_mul(16))?; + let mut values: Vec = (0..view.length).map(|i| at(interp, &view, i)).collect(); + merge_sort(interp, &mut values, &compare)?; + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, i, n); + } + Ok(this) +} diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs new file mode 100644 index 0000000000..1798707aff --- /dev/null +++ b/crates/js/src/builtins/collections.rs @@ -0,0 +1,696 @@ +//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator +//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections +//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`]. +//! +//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order +//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries +//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet +//! entries hold their key weakly: the collector removes an entry once its key is reachable only +//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. +//! +//! The language has no iterators yet, so the constructors read their argument by index: an +//! array or an object with a `length`, or a string by code point. Every entry added is checked +//! against the heap limit before it is added, and every entry visited takes a unit of fuel. + +use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use crate::heap::{ + COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, + PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, +}; +use crate::interp::{Abrupt, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::{Str, Value}; + +/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does +/// to the globals. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Es2015 { + pub(crate) map_proto: ObjId, + pub(crate) set_proto: ObjId, + pub(crate) weak_map_proto: ObjId, + pub(crate) weak_set_proto: ObjId, + pub(crate) map_iter_proto: ObjId, + pub(crate) set_iter_proto: ObjId, + pub(crate) array_iter_proto: ObjId, + pub(crate) array_buffer_proto: ObjId, + pub(crate) data_view_proto: ObjId, + /// `%TypedArray%` and its prototype (section 22.2.1). + pub(crate) typed_array_ctor: ObjId, + pub(crate) typed_array_proto: ObjId, + /// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`]. + pub(crate) typed_ctors: [ObjId; 9], + pub(crate) typed_protos: [ObjId; 9], +} + +impl Es2015 { + pub(crate) fn placeholder() -> Self { + let o = ObjId(0); + Self { + map_proto: o, + set_proto: o, + weak_map_proto: o, + weak_set_proto: o, + map_iter_proto: o, + set_iter_proto: o, + array_iter_proto: o, + array_buffer_proto: o, + data_view_proto: o, + typed_array_ctor: o, + typed_array_proto: o, + typed_ctors: [o; 9], + typed_protos: [o; 9], + } + } + + pub(crate) fn all(&self) -> Vec { + let mut v = vec![ + self.map_proto, + self.set_proto, + self.weak_map_proto, + self.weak_set_proto, + self.map_iter_proto, + self.set_iter_proto, + self.array_iter_proto, + self.array_buffer_proto, + self.data_view_proto, + self.typed_array_ctor, + self.typed_array_proto, + ]; + v.extend(self.typed_ctors); + v.extend(self.typed_protos); + v + } +} + +/// A new ordinary object with `proto`, for a prototype. +pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId { + interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))) +} + +/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors +/// of ECMAScript 2015 are. +pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> { + let g = native(interp, name, f, 0, NativeKind::Plain, false)?; + let prop_name = name.strip_prefix("get ").unwrap_or(name); + interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE }) +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + + let map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.map_proto = map_proto; + let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Map", map, map_proto)?; + let map_methods: [(&'static str, NativeFn, u32); 9] = [ + ("get", map_get, 1), + ("set", map_set, 2), + ("has", map_has, 1), + ("delete", map_delete, 1), + ("clear", map_clear, 0), + ("forEach", map_for_each, 1), + ("keys", map_keys, 0), + ("values", map_values, 0), + ("entries", map_entries, 0), + ]; + for (name, f, length) in map_methods { + method(interp, map_proto, name, f, length)?; + } + getter(interp, map_proto, "get size", map_size)?; + + let set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.set_proto = set_proto; + let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Set", set, set_proto)?; + let set_methods: [(&'static str, NativeFn, u32); 7] = [ + ("has", set_has, 1), + ("add", set_add, 1), + ("delete", set_delete, 1), + ("clear", set_clear, 0), + ("entries", set_entries, 0), + ("forEach", set_for_each, 1), + ("values", set_values, 0), + ]; + for (name, f, length) in set_methods { + method(interp, set_proto, name, f, length)?; + } + getter(interp, set_proto, "get size", set_size)?; + // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). + let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; + interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + + let weak_map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_map_proto = weak_map_proto; + let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakMap", weak_map, weak_map_proto)?; + let weak_map_methods: [(&'static str, NativeFn, u32); 4] = + [("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)]; + for (name, f, length) in weak_map_methods { + method(interp, weak_map_proto, name, f, length)?; + } + + let weak_set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_set_proto = weak_set_proto; + let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakSet", weak_set, weak_set_proto)?; + let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)]; + for (name, f, length) in weak_set_methods { + method(interp, weak_set_proto, name, f, length)?; + } + + for source in [IterSource::Map, IterSource::Set, IterSource::Array] { + let proto = new_proto(interp, object_proto); + let next: NativeFn = match source { + IterSource::Map => map_iterator_next, + IterSource::Set => set_iterator_next, + IterSource::Array => array_iterator_next, + }; + method(interp, proto, "next", next, 0)?; + match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto, + } + } + Ok(()) +} + +// ---- keys ---- + +/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap. +fn coll_key(interp: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => CollKey::Undefined, + Value::Null => CollKey::Null, + Value::Bool(b) => CollKey::Bool(*b), + Value::Number(n) => CollKey::number(*n), + Value::String(s) => CollKey::String(flat_charged(interp, s)?), + Value::Object(o) => CollKey::Object(o.0), + }) +} + +/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1). +fn stored_key(v: Value) -> Value { + match v { + // `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`. + Value::Number(n) => Value::Number(n + 0.0), + v => v, + } +} + +// ---- reading a list ---- + +/// ToLength (section 7.1.15) of an object's `length`. +pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + let len = interp.get_from(o, &key("length"), &Value::Object(o))?; + let n = super::to_integer(interp, &len)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) +} + +/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, +/// or a string's code points. Any other value is a `TypeError`, and so is an object without a +/// `length` when `need_length` is true. Each item takes a unit of fuel. +pub(crate) fn for_each_item( + interp: &mut Interp, + list: &Value, + need_length: bool, + mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, +) -> JsResult<()> { + match list { + Value::Object(o) => { + if need_length && !interp.has_property(*o, &key("length"))? { + return Err(interp.type_error("the value is not an array, a string or an object with a length")); + } + let len = length_of(interp, *o)?; + let mut i = 0u64; + while i < len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(*o, &key_of(i as f64), list)?; + f(interp, item)?; + i += 1; + } + Ok(()) + } + Value::String(s) => { + let units = flat_charged(interp, s)?; + let mut i = 0; + while i < units.len() { + interp.use_fuel()?; + let width = match (units.get(i), units.get(i + 1)) { + (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, + _ => 1, + }; + let piece = units.get(i..i + width).unwrap_or_default().to_vec(); + let bytes = string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + f(interp, Value::String(Str::from_units(piece)))?; + i += width; + } + Ok(()) + } + _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), + } +} + +/// Adds the items of `list` to the new collection `target` with its `adder` method, as the +/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item +/// as a `[key, value]` entry. +fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { + if list.is_nullish() { + return Ok(()); + } + let this = Value::Object(target); + interp.rooted(&[this.clone(), list.clone()], |interp| { + let add = interp.get_from(target, &key(adder), &this)?; + require_callable(interp, &add, adder)?; + interp.rooted(std::slice::from_ref(&add), |interp| { + for_each_item(interp, list, true, |interp, item| { + if !pairs { + return interp.call(&add, &this, &[item]).map(drop); + } + let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) }; + let k = interp.get_from(entry, &key("0"), &item)?; + let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?; + interp.call(&add, &this, &[k, v]).map(drop) + }) + }) + }) +} + +/// A new collection object of `class` with `proto`, filled from `args[0]`. +fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{name} must be called with new"))); + } + interp.reserve_heap(OBJECT_BYTES)?; + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + let (adder, pairs) = match name { + "Map" | "WeakMap" => ("set", true), + _ => ("add", false), + }; + fill(interp, o, &arg(args, 0), adder, pairs)?; + Ok(Value::Object(o)) +} + +fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.map_proto; + construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) +} + +fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.set_proto; + construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto) +} + +fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_map_proto; + construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto) +} + +fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_set_proto; + construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto) +} + +// ---- Map and Set ---- + +/// The Map (or with `set`, the Set) a method was called on. +fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true)) + { + return Ok(*o); + } + let name = if set { "Set" } else { "Map" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> { + match &interp.object(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> { + match &mut interp.object_mut(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +/// Adds or replaces the entry of `k`, reserving the heap for a new one first. +fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> { + let ck = coll_key(interp, &k)?; + if !coll(interp, o)?.has(&ck) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES); + } + coll_mut(interp, o)?.set(ck, stored_key(k), v); + Ok(()) +} + +fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "get")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined)) +} + +fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "set")?; + coll_put(interp, o, arg(args, 0), arg(args, 1))?; + Ok(this) +} + +fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "has")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll(interp, o)?.has(&k))) +} + +fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "delete")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll_mut(interp, o)?.delete(&k))) +} + +fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "clear")?; + let slots = coll(interp, o)?.slots(); + // Clearing visits every position, and each takes a unit of fuel. + for _ in 0..slots { + interp.use_fuel()?; + } + coll_mut(interp, o)?.clear(); + Ok(Value::Undefined) +} + +fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "size")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(coll(interp, o)?.len() as f64)) +} + +fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, false) +} + +fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, false) +} + +fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, false) +} + +fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, false) +} + +fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, true, "add")?; + coll_put(interp, o, arg(args, 0), Value::Undefined)?; + Ok(this) +} + +fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, true) +} + +fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, true) +} + +fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, true) +} + +fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, true) +} + +/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a +/// Set, the value again) and the collection, in order, visiting entries added while it runs. The +/// position is kept in an iterator object, so a collection that removes holes moves it. +fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "forEach")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let source = if set { IterSource::Set } else { IterSource::Map }; + let it = new_iter(interp, o, source, IterKind::Entries, None)?; + interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| { + while let Some((k, v)) = advance(interp, it)? { + let v = if set { k.clone() } else { v }; + interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?; + } + Ok(Value::Undefined) + }) +} + +fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, false) +} + +fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, true) +} + +// ---- iterators ---- + +/// A new iterator over `target`, with `proto` (by default the prototype for `source`). +pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option) -> JsResult { + interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = proto.unwrap_or(match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto, + }); + let state = IterState { source, kind, target: Some(target), pos: 0 }; + let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + Ok(it) +} + +/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position +/// passed takes a unit of fuel. +fn advance(interp: &mut Interp, it: ObjId) -> JsResult> { + loop { + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) }; + let c = coll(interp, target)?; + let found = (pos < c.slots()).then(|| c.entry(pos).cloned()); + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + match found { + None => { + state.target = None; + return Ok(None); + } + Some(entry) => { + state.pos = pos + 1; + if let Some(entry) = entry { + return Ok(Some(entry)); + } + } + } + } +} + +/// An iterator result object `{ value, done }` (section 7.4.7). +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?; + let o = interp.new_object(); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new array `[a, b]`. +pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult { + interp.rooted(&[a.clone(), b.clone()], |interp| { + let arr = new_array(interp, 0)?; + interp.rooted(&[Value::Object(arr)], |interp| { + create_at(interp, arr, 0.0, a.clone())?; + create_at(interp, arr, 1.0, b.clone())?; + Ok(Value::Object(arr)) + }) + }) +} + +/// The iterator a `next` method was called on, when it goes through `source`. +fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> { + if let Value::Object(o) = this + && let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class) + && state.source == source + { + return Ok((*o, state.kind)); + } + Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator"))) +} + +fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult { + let (it, kind) = this_iter(interp, this, source, name)?; + let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) }; + let value = match (kind, source) { + (IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k, + (IterKind::Values, _) => v, + (IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?, + (IterKind::Entries, _) => pair(interp, k, v)?, + }; + iter_result(interp, value, false) +} + +fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Map, "Map") +} + +fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Set, "Set") +} + +/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays. +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?; + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (target, pos) = (state.target, state.pos); + let element = match target { + Some(t) => match &interp.object(t)?.class { + Class::TypedArray(view) => super::binary::element(interp, view, pos as f64), + _ => None, + }, + None => None, + }; + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let Some(element) = element else { + state.target = None; + return iter_result(interp, Value::Undefined, true); + }; + state.pos = pos + 1; + #[allow(clippy::cast_precision_loss)] + let index = Value::Number(pos as f64); + let value = match kind { + IterKind::Keys => index, + IterKind::Values => Value::Number(element), + IterKind::Entries => pair(interp, index, Value::Number(element))?, + }; + iter_result(interp, value, false) +} + +fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult { + let o = this_coll(interp, this, set, name)?; + let source = if set { IterSource::Set } else { IterSource::Map }; + new_iter(interp, o, source, kind, None).map(Value::Object) +} + +fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Keys, "keys") +} + +fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Values, "values") +} + +fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Entries, "entries") +} + +fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Values, "values") +} + +fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Entries, "entries") +} + +// ---- WeakMap and WeakSet ---- + +fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true)) + { + return Ok(*o); + } + let name = if set { "WeakSet" } else { "WeakMap" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> { + match &interp.object(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> { + match &mut interp.object_mut(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`. +fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> { + let Value::Object(key_obj) = k else { + let what = if set { "a WeakSet value" } else { "a WeakMap key" }; + return Err(interp.type_error(&format!("{what} must be an object"))); + }; + if !weak(interp, o)?.entries.contains_key(&key_obj.0) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES); + } + weak_mut(interp, o)?.entries.insert(key_obj.0, v); + Ok(()) +} + +fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "get")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) }; + Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined)) +} + +fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "set")?; + weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?; + Ok(this) +} + +fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "has")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0))) +} + +fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "delete")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some())) +} + +fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, false) +} + +fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, false) +} + +fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, true, "add")?; + weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?; + Ok(this) +} + +fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, true) +} + +fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, true) +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs new file mode 100644 index 0000000000..7c00b29532 --- /dev/null +++ b/crates/js/src/collections_tests.rs @@ -0,0 +1,412 @@ +use crate::heap::{Class, key}; +use crate::value::Value; +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn realm() -> Realm { + Realm::with_options(es2015(), Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match realm().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +fn limit(limits: &Limits, src: &str) -> LimitKind { + match Realm::with_options(es2015(), limits.clone()).run(src) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k, + other => panic!("{src}: {other:?}"), + } +} + +/// The object a global variable holds. +fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId { + let interp = realm.interp(); + let global = interp.global; + match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) { + Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o, + _ => panic!("{name} is not an object"), + } +} + +// ---- realms ---- + +#[test] +fn realms_without_the_option_keep_the_es5_globals() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \ + Uint32Array Float32Array Float64Array"; + for name in names.split_whitespace() { + assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}"); + } + } + truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'"); +} + +// ---- Map and Set ---- + +#[test] +fn keys_compare_with_same_value_zero() { + truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1"); + truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity"); + truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity"); + truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'"); + truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined"); + truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1"); +} + +#[test] +fn entries_keep_the_order_they_were_added_in() { + assert_eq!( + string( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \ + var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()" + ), + "a9true,c3true,b4true" + ); + assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy"); +} + +#[test] +fn for_each_skips_deleted_entries_and_visits_added_ones() { + assert_eq!( + string( + "var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \ + m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()" + ), + "a,c,d" + ); + assert_eq!( + string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"), + "1,2,3,4,5" + ); + assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1"); +} + +#[test] +fn iterators_step_through_live_entries() { + truth( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \ + var second = it.next(), third = it.next(), last = it.next(); \ + first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \ + last.done && last.value === undefined && it.next().done", + ); + truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values"); + truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'"); + throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError"); +} + +#[test] +fn constructors_read_arrays_strings_and_array_likes() { + truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); + truth("new Set('ab\u{1F600}b').size === 3"); + truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + truth("new Map(null).size === 0 && new Set(undefined).size === 0"); + truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); + throws("Map()", "TypeError"); + throws("Set([])", "TypeError"); + throws("new Map([1])", "TypeError"); + throws("new Set(5)", "TypeError"); + throws("new Map({})", "TypeError"); + throws("new WeakSet({})", "TypeError"); + truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); + // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). + truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); + throws("Map.prototype.get.call({}, 1)", "TypeError"); + throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); + // The constructor adds through the prototype's method, as section 23.1.1.1 says. + truth( + "var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \ + new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2", + ); + truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); +} + +// ---- WeakMap and WeakSet ---- + +#[test] +fn weak_collections_take_object_keys_only() { + truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)"); + truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)"); + truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)"); + throws("new WeakMap().set(1, 2)", "TypeError"); + throws("new WeakSet().add('x')", "TypeError"); + throws("new WeakMap([[1, 2]])", "TypeError"); + truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'"); +} + +#[test] +fn a_weak_map_entry_does_not_keep_its_key_alive() { + let mut realm = realm(); + realm + .run( + "var wm = new WeakMap(), ws = new WeakSet(), kept = {}; + (function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })(); + wm.set(kept, {back: kept}); ws.add(kept);", + ) + .unwrap(); + let wm = global_object(&mut realm, "wm"); + let ws = global_object(&mut realm, "ws"); + let before = realm.interp().heap.live_cells(); + realm.interp().collect_garbage(); + let after = realm.interp().heap.live_cells(); + let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) { + Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(), + _ => panic!("not a weak collection"), + }; + assert_eq!(count(&mut realm, wm), 1); + assert_eq!(count(&mut realm, ws), 1); + // Each dropped key and its value were freed. + assert!(before - after >= 100, "{before} -> {after}"); + assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_weak_map_value_reachable_through_another_key_is_kept() { + let mut realm = realm(); + realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap(); + realm.interp().collect_garbage(); + assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0)); +} + +#[test] +fn weak_maps_of_dropped_keys_stay_within_the_heap() { + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(es2015(), limits); + let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'"); + assert_eq!(r.unwrap(), JsValue::String("done".into())); + assert!(realm.interp().heap.collections > 0); +} + +#[test] +fn collections_of_millions_end_at_the_limits() { + let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); + assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); + let fuel = Limits { fuel: 100_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; + assert_eq!(limit(&fuel, m), LimitKind::Fuel); +} + +#[test] +fn a_collection_removes_holes_and_moves_live_iterators() { + let mut realm = realm(); + realm + .run( + "var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2); + var it = m.values(); it.next(); it.next(); + for (var j = 0; j < 90; j++) m.delete(j);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)), + _ => panic!("not a Map"), + } + let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap(); + assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); +} + +// ---- ArrayBuffer ---- + +#[test] +fn array_buffers_are_zeroed_and_sliced() { + truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0"); + truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'"); + truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))"); + truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2"); + throws("ArrayBuffer(1)", "TypeError"); + throws("new ArrayBuffer(-1)", "RangeError"); +} + +#[test] +fn a_huge_array_buffer_is_refused_before_it_is_allocated() { + throws("new ArrayBuffer(1e15)", "RangeError"); + throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError"); + throws("new Float64Array(Math.pow(2, 40))", "RangeError"); + truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught"); + // Larger than the realm's heap limit: a catchable RangeError, not an allocation. + let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() }); + assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into())); + // Within the limit but not within what is left of it: the heap limit. + assert_eq!( + limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"), + LimitKind::Heap + ); +} + +// ---- DataView ---- + +#[test] +fn data_views_read_and_write_both_byte_orders() { + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294"); + truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200"); + truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b"); + throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 5)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError"); + throws("new DataView({})", "TypeError"); + throws("DataView(new ArrayBuffer(1))", "TypeError"); +} + +// ---- typed arrays ---- + +#[test] +fn uint8_clamped_rounds_half_to_even() { + assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255"); + assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44"); +} + +#[test] +fn element_types_convert_their_values() { + assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1"); + assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0"); + assert_eq!(string("new Int32Array([4294967295]).join()"), "-1"); + assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295"); + assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000"); + assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN"); + truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8"); + truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'"); +} + +#[test] +fn views_share_their_buffer_little_endian() { + truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1"); + truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1"); + truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4"); + throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError"); + throws("new Int32Array(new ArrayBuffer(6))", "RangeError"); + throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError"); +} + +#[test] +fn numeric_names_are_elements_or_nothing() { + truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'"); + truth( + "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", + ); + truth("Int8Array.prototype[0] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[0]; r"); + truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); + // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. + truth( + "var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2", + ); + truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]"); + throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError"); + // An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]]. + truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined"); + truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable"); + truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5"); + throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError"); + throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError"); + throws("Object.freeze(new Uint8Array(1))", "TypeError"); + truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'"); + truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'"); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_typed_array() { + truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999"); + truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999"); + // The element count, not a `length` property defined on the array, bounds the methods. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \ + a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })", + ); + // A generic array method called on the typed array reads its `length` property. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \ + Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'", + ); +} + +#[test] +fn typed_array_methods() { + assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN"); + truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity"); + assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3"); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3"); + assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0"); + throws("new Uint8Array(2).set([1, 2, 3])", "RangeError"); + throws("new Uint8Array(2).set([1], -1)", "RangeError"); + assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5"); + assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0"); + assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7"); + truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1"); + truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1"); + truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'"); + truth( + "var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done", + ); + truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9"); + truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); + truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); + truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + truth( + "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", + ); + throws("Object.getPrototypeOf(Int8Array)()", "TypeError"); + throws("Int8Array(1)", "TypeError"); + throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError"); + throws("Int8Array.from.call(Object, [1])", "TypeError"); + throws("Int8Array.from.call({}, [1])", "TypeError"); + // The source's length is read before the constructor is checked to be a typed array's. + throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); + // A copy to the same element type keeps every bit, a signaling NaN's included. + truth( + "var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \ + function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \ + var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \ + bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \ + new DataView(g.buffer).getUint32(8, true) === 0x7f800001", + ); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); +} + +#[test] +fn typed_array_work_takes_fuel() { + let fuel = Limits { fuel: 50_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..4aed4b9c9b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,231 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. + Map(Box), + /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. + Set(Box), + /// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key + /// reachable, and its value is reachable only while its key is. + WeakMap(Box), + /// A `WeakSet` (section 23.4): objects that it does not keep reachable. + WeakSet(Box), + /// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5). + Iter(Box), + /// An `ArrayBuffer` (section 24.1) and its bytes, which never change length. + ArrayBuffer(Box<[u8]>), + /// A `DataView` (section 24.2): a range of a buffer's bytes. + DataView(Box), + /// A typed array (section 22.2): elements of one type in a range of a buffer's bytes. + TypedArray(Box), +} + +/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0` +/// equals `+0`, strings compare by their code units and objects by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum CollKey { + Undefined, + Null, + Bool(bool), + /// The bits of the number, with every `NaN` as one value and `-0` as `+0`. + Number(u64), + String(Rc<[u16]>), + Object(u32), +} + +impl CollKey { + /// The key of a number. + pub(crate) fn number(n: f64) -> Self { + CollKey::Number(if n.is_nan() { + f64::NAN.to_bits() + } else if n == 0.0 { + 0 + } else { + n.to_bits() + }) + } +} + +/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole, +/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes +/// the holes of a collection with more holes than entries and moves its live iterators with them. +#[derive(Clone, Default)] +pub(crate) struct Coll { + entries: Vec>, + index: HashMap, +} + +impl Coll { + /// The number of entries. + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + /// The number of positions, holes included. + pub(crate) fn slots(&self) -> usize { + self.entries.len() + } + + pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, v)| v) + } + + pub(crate) fn has(&self, k: &CollKey) -> bool { + self.index.contains_key(k) + } + + /// Sets the value under `k`, keeping its position when it is there already. Returns whether + /// a new entry was added. + pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool { + if let Some(&i) = self.index.get(&k) + && let Some(Some((_, v))) = self.entries.get_mut(i) + { + *v = value; + return false; + } + self.index.insert(k, self.entries.len()); + self.entries.push(Some((key, value))); + true + } + + /// Deletes the entry under `k`; returns whether there was one. + pub(crate) fn delete(&mut self, k: &CollKey) -> bool { + let Some(i) = self.index.remove(k) else { return false }; + if let Some(slot) = self.entries.get_mut(i) { + *slot = None; + } + true + } + + /// Deletes every entry, leaving the positions in place. + pub(crate) fn clear(&mut self) { + self.index.clear(); + self.entries.iter_mut().for_each(|e| *e = None); + } + + /// The entry at position `i`, or `None` for a hole or a position past the end. + pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> { + self.entries.get(i)?.as_ref() + } + + fn values(&self) -> impl Iterator { + self.entries.iter().flatten().flat_map(|(k, v)| [k, v]) + } + + fn should_compact(&self) -> bool { + let holes = self.entries.len() - self.index.len(); + holes > 16 && holes > self.index.len() + } + + /// Removes the holes. Returns, for each old position and the position past the end, the new + /// position of the first entry at or after it. + fn compact(&mut self) -> Vec { + let mut moved = Vec::with_capacity(self.entries.len() + 1); + let mut live = 0usize; + for e in &self.entries { + moved.push(live); + live += usize::from(e.is_some()); + } + moved.push(live); + self.entries.retain(Option::is_some); + for slot in self.index.values_mut() { + *slot = moved.get(*slot).copied().unwrap_or(*slot); + } + moved + } +} + +/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are +/// `undefined`. +#[derive(Clone, Default)] +pub(crate) struct WeakColl { + pub(crate) entries: HashMap, +} + +/// What an iterator object goes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterSource { + Map, + Set, + /// A typed array, by index. + Array, +} + +/// What each step of an iterator gives: the key, the value or a `[key, value]` array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. `target` is `None` once the iterator has finished. +#[derive(Clone, Debug)] +pub(crate) struct IterState { + pub(crate) source: IterSource, + pub(crate) kind: IterKind, + pub(crate) target: Option, + pub(crate) pos: usize, +} + +/// The element type of a typed array (section 22.2, table 50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Elem { + Int8, + Uint8, + Uint8Clamped, + Int16, + Uint16, + Int32, + Uint32, + Float32, + Float64, +} + +impl Elem { + pub(crate) const ALL: [Elem; 9] = + [Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64]; + + /// The bytes of one element. + pub(crate) fn size(self) -> usize { + match self { + Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1, + Elem::Int16 | Elem::Uint16 => 2, + Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4, + Elem::Float64 => 8, + } + } + + /// The name of the constructor. + pub(crate) fn name(self) -> &'static str { + match self { + Elem::Int8 => "Int8Array", + Elem::Uint8 => "Uint8Array", + Elem::Uint8Clamped => "Uint8ClampedArray", + Elem::Int16 => "Int16Array", + Elem::Uint16 => "Uint16Array", + Elem::Int32 => "Int32Array", + Elem::Uint32 => "Uint32Array", + Elem::Float32 => "Float32Array", + Elem::Float64 => "Float64Array", + } + } + + /// The position of the type in [`Elem::ALL`]. + pub(crate) fn index(self) -> usize { + Elem::ALL.iter().position(|e| *e == self).unwrap_or(0) + } +} + +/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting +/// `offset` bytes into `buffer`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct View { + pub(crate) buffer: ObjId, + pub(crate) offset: usize, + pub(crate) length: usize, + pub(crate) elem: Elem, } /// What an XML value is. @@ -322,6 +547,18 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::Map(_) => "Map", + Class::Set(_) => "Set", + Class::WeakMap(_) => "WeakMap", + Class::WeakSet(_) => "WeakSet", + Class::Iter(state) => match state.source { + IterSource::Map => "Map Iterator", + IterSource::Set => "Set Iterator", + IterSource::Array => "Array Iterator", + }, + Class::ArrayBuffer(_) => "ArrayBuffer", + Class::DataView(_) => "DataView", + Class::TypedArray(view) => view.elem.name(), } } } @@ -397,6 +634,12 @@ pub(crate) const XML_REF_BYTES: usize = 8; pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; +/// The estimated bytes of a Map or Set position, with its entry in the hash index. +pub(crate) const COLL_ENTRY_BYTES: usize = 96; +/// The estimated bytes of a WeakMap or WeakSet entry. +pub(crate) const WEAK_ENTRY_BYTES: usize = 64; +/// The estimated bytes of the state of an iterator, a typed array or a `DataView`. +pub(crate) const VIEW_BYTES: usize = 48; pub(crate) fn string_bytes(len: usize) -> usize { 32 + 2 * len @@ -476,11 +719,18 @@ impl Heap { /// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is /// the estimated size of what is left, strings reachable from it included. + /// + /// A WeakMap's entry marks its value only once its key is marked by another path, and the + /// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so + /// a value that refers back to its own key does not keep it alive. Values waiting for their + /// key are kept by key, so the marking stays linear in the number of entries. pub(crate) fn collect(&mut self, roots: &Roots<'_>) { let mut marks = vec![false; self.cells.len()]; let mut work: Vec = Vec::new(); let mut strings = StringSizes::default(); let mut live = 0usize; + let mut pending: HashMap> = HashMap::new(); + let mut weak: Vec = Vec::new(); for v in &roots.values { mark_value(v, &mut work, &mut strings); } @@ -495,21 +745,80 @@ impl Heap { continue; } *mark = true; + if let Some(values) = pending.remove(&i) { + for v in &values { + mark_value(v, &mut work, &mut strings); + } + } match self.cells.get(i as usize) { - Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings), + Some(Cell::Object(o)) => { + live += trace_object(o, &mut work, &mut strings); + match &o.class { + Class::WeakMap(w) => { + weak.push(i); + for (k, v) in &w.entries { + if marks.get(*k as usize).copied().unwrap_or(false) { + mark_value(v, &mut work, &mut strings); + } else if matches!(v, Value::Object(_) | Value::String(_)) { + pending.entry(*k).or_default().push(v.clone()); + } + } + } + Class::WeakSet(_) => weak.push(i), + _ => {} + } + } Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings), _ => {} } } + for i in weak { + if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize) + && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class + { + w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + live += WEAK_ENTRY_BYTES * w.entries.len(); + } + } for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() { if !marked && !matches!(cell, Cell::Free) { *cell = Cell::Free; self.free.push(u32::try_from(i).unwrap_or(u32::MAX)); } } + live = live.saturating_sub(self.compact_collections()); self.bytes = live + strings.bytes; self.collections += 1; } + + /// Removes the holes of the Maps and Sets that have more holes than entries, and moves the + /// positions of their iterators with them. Returns the bytes the holes held. + fn compact_collections(&mut self) -> usize { + let mut moved: HashMap> = HashMap::new(); + let mut freed = 0usize; + for (i, cell) in self.cells.iter_mut().enumerate() { + if let Cell::Object(o) = cell + && let Class::Map(c) | Class::Set(c) = &mut o.class + && c.should_compact() + { + freed += COLL_ENTRY_BYTES * (c.slots() - c.len()); + moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact()); + } + } + if moved.is_empty() { + return 0; + } + for cell in &mut self.cells { + if let Cell::Object(o) = cell + && let Class::Iter(state) = &mut o.class + && state.source != IterSource::Array + && let Some(map) = state.target.and_then(|t| moved.get(&t.0)) + { + state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0); + } + } + freed + } } /// What the collector starts from. @@ -680,6 +989,23 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Map(c) | Class::Set(c) => { + for v in c.values() { + mark_value(v, work, strings); + } + extra = COLL_ENTRY_BYTES * c.slots(); + } + // Their entries are marked and counted by the collector's weak pass. + Class::WeakMap(_) | Class::WeakSet(_) => {} + Class::Iter(state) => { + work.extend(state.target.iter().map(|o| o.0)); + extra = VIEW_BYTES; + } + Class::ArrayBuffer(bytes) => extra = bytes.len(), + Class::DataView(view) | Class::TypedArray(view) => { + work.push(view.buffer.0); + extra = VIEW_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..b90c354347 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -103,6 +103,8 @@ pub(crate) struct Intrinsics { pub(crate) xml_list_proto: ObjId, pub(crate) namespace_proto: ObjId, pub(crate) qname_proto: ObjId, + /// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]). + pub(crate) es2015: crate::builtins::collections::Es2015, } impl Intrinsics { @@ -125,6 +127,7 @@ impl Intrinsics { xml_list_proto: o, namespace_proto: o, qname_proto: o, + es2015: crate::builtins::collections::Es2015::placeholder(), } } @@ -160,6 +163,7 @@ impl Intrinsics { self.qname_proto, ]; v.extend(self.error_protos); + v.extend(self.es2015.all()); v } } @@ -251,6 +255,9 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// The typed array whose element count the next array method reads as its length, set while a + /// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read. + pub(crate) typed_length: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, /// The clock and time zone `Date` reads. @@ -517,6 +524,7 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + typed_length: None, files: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -1380,6 +1388,12 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + // A numeric name of a typed array is an element or nothing (section 9.4.5.1). + Class::TypedArray(view) => { + if let Some(n) = crate::builtins::binary::canonical_index(k) { + return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN })); + } + } _ => {} } Ok(o.props.get(k).cloned()) @@ -1393,6 +1407,10 @@ impl Interp { if let Some(p) = self.get_own_property(o, k)? { return Ok(Some(p)); } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok(None); + } cur = self.object(o)?.proto; steps += 1; if steps > 1_000_000 { @@ -1490,6 +1508,9 @@ impl Interp { } self.define_ordinary(id, k, desc, throw) } + Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => { + crate::builtins::binary::define_element(self, id, &k, desc, throw) + } Class::Arguments(map) => { let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned(); if !self.define_ordinary(id, k.clone(), desc, false)? { @@ -1642,7 +1663,12 @@ impl Interp { /// list is checked first. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { let o = self.object(id)?; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; + // A typed array's indices come first, as a String object's do (section 9.4.5.6). + let string_len = match &o.class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + }; let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); @@ -1684,6 +1710,9 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { + return crate::builtins::binary::set_element(self, id, n, &v); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -1759,6 +1788,18 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + // A typed array's element cannot be deleted, and a numeric name it has no element for + // is not a property it can hold (section 9.4.5.6 of later editions). + if crate::builtins::binary::typed_key(self, id, k).is_some() { + if self.get_own_property(id, k)?.is_none() { + return Ok(true); + } + if throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array"))); + } + return Ok(false); + } match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -2121,8 +2162,12 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { let obj = self.object(o)?; - let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; - let is_array = matches!(obj.class, Class::Array { .. }); + let string_len = match &obj.class { + Class::String(s) => Some(s.len()), + Class::TypedArray(view) => Some(view.length), + _ => None, + }; + let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_)); if let Some(len) = string_len { self.reserve_heap(index_keys_bytes(len))?; for i in 0..len { @@ -2132,7 +2177,6 @@ impl Interp { out.push(k); } } - seen.insert(key("length")); } if is_array { seen.insert(key("length")); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..34284a6fd9 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,18 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins +//! (): `Map` and `Set` (sections 23.1 and 23.2), whose +//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting +//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the +//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine +//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with +//! a `next` method. Until the language has iterators, the collection constructors and +//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by +//! index. A typed array constructor reads an array or an object with a `length` the same way, and +//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] pub mod ast; @@ -100,11 +112,15 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the ECMAScript 2015 built-ins this engine has: `Map`, `Set`, `WeakMap`, + /// `WeakSet`, `ArrayBuffer`, `DataView` and the typed arrays. Off, a realm has the ES5.1 + /// built-ins only, as ExtendScript scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -203,6 +219,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod collections_tests; +#[cfg(test)] mod extension_tests; #[cfg(test)] mod host_tests; diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..2b273d6359 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -28,6 +28,11 @@ //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. //! +//! A fifth test runs the tests under the folders [`ES2015_BUILT_INS`] names (`Map`, `Set`, +//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in +//! realms with [`Options::es2015`], each test whose feature tags are all in [`ES2015_FEATURES`]; its +//! failures go to `es2015-failures.txt`. It fails when the interpreter panics. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -444,7 +449,12 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool { /// Runs one test in a new realm; `Err` describes a failure. fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> { - let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + run_in(Options::default(), script, negative_type) +} + +/// Runs one test in a new realm with `options`; `Err` describes a failure. +fn run_in(options: Options, script: &str, negative_type: Option<&str>) -> Result<(), String> { + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); match (realm.run(script), negative_type) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), @@ -590,6 +600,108 @@ fn run_text_builtins(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections +/// and binary data, which run in a realm with [`Options::es2015`]. +const ES2015_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"]; + +/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides. +const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array"; + +/// The feature tags a test under [`ES2015_BUILT_INS`] may have and still run: the built-ins +/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of +/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or +/// detached buffers, `BigInt` and later additions) are counted as skipped. +const ES2015_FEATURES: &[&str] = &[ + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "TypedArray", + "Int8Array", + "Uint8Array", + "Float64Array", + "stable-typedarray-sort", +]; + +#[test] +fn es2015_collections_and_binary_data_run() { + let Some(dir) = suite_dir() else { + println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under the folders [`ES2015_BUILT_INS`] names in realms with +/// [`Options::es2015`], prints each folder's counts and writes the failures to +/// `es2015-failures.txt` beside the suite. +fn run_es2015_built_ins(dir: &Path) { + let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]); + let mut report = String::new(); + let mut panicked = 0; + for name in ES2015_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_es2015_tests(dir, &root, &missing); + println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary()); + report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures)); + panicked += counts.panicked; + } + let path = dir.join("es2015-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 ECMAScript 2015 built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the tests under `root` whose feature tags are all in [`ES2015_FEATURES`], as +/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`]. +fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts { + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let known = meta.features.iter().all(|f| ES2015_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype.")); + if !known || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_in(Options { es2015: true, ..Options::default() }, &script, negative_type.as_deref())) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + counts +} + /// Runs the tests under `root` that have no feature tag and are not module, asynchronous or /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..58c4525d84 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -87,8 +87,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa /// Text an action set written out at run time holds. pub(crate) const ACTION_TEXT: &str = "/actionCount"; -/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition, -/// section 13), and the platform's own: `new` of these is no document-model type. +/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary +/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and +/// the platform's own: `new` of these is no document-model type. pub(crate) const CONSTRUCTORS: &[&str] = &[ "Object", "Function", @@ -105,6 +106,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[ "SyntaxError", "TypeError", "URIError", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", "Namespace", "QName", "XML", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..676232545f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1392,6 +1392,17 @@ fn type_names_compared_or_created_are_listed() { assert_eq!(r.needs, [Need::Dom]); } +#[test] +fn collections_and_typed_arrays_are_not_type_names() { + let r = report(concat!( + "var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n", + "var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n", + "var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n", + "var f = [new Float32Array(1), new Float64Array(1)];\n", + )); + assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::>()); +} + #[test] fn menu_commands_are_counted_with_their_lines() { let r = report(concat!( diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..7204bf97a9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2616,8 +2616,10 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any 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 and runs other files through `$`: +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. An ES5.1 script does not +have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the typed arrays; the JavaScript engine's +ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. The +script reaches the 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..32a682ab00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 99c4a82b3088efaebb181d065f2c2b9d090e99b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:43:40 -0800 Subject: [PATCH 032/298] Tabs: fallback glyphs in tab titles sit on the condensed face's baseline The tab family's copies of the semibold faces took the copy made for egui's empty Proportional family, which has no baseline shift, instead of the one made for the tab family. They now take the tab family's copy. egui's own faces stay under their own names, as in the semibold family: egui skips some of their characters (the Ubuntu logo, two symbols in its emoji face) only under those names. ui_fonts::baseline_copies measured a fallback face without its own FontTweak scale, while egui draws the face and its y_offset_factor at that scale. The shift now uses it, so a scaled fallback (Inter SemiBold at 0.92) sits on the row's baseline. Faces added before this change are at scale 1 and keep their shift. Without the condensed face the tab family is no longer bound, and tabs draw in theme::tab_title_font: the tab family when the context's fonts bind it, otherwise the semibold family as it is. Fonts an embedder adds to the semibold family then reach tab titles too, and an embedder's own definitions that bind only the other families keep working. The condensed face and the lookup of its catalog row move to build/condensed_ui_face.rs, which the crate's tests include. With CRAFT_FONTS_REQUIRED=1, an unreadable catalog, a malformed row for the face or a row whose file can't be embedded is a build error; a checkout without the catalog or the row still gives a warning. A checkout whose catalog names the condensed face without its file is watched through the file's folder inside the checkout, so the build runs again once the file appears. docs/development.md lists FONT_TAB among the families an embedder adds fonts to. ASSETS.md and NOTICE name the face, and the docs/ui-parity.md row says official builds wait for the craft-fonts pin to move. Tests: with the monospace face standing in for the condensed face, and without craft-fonts, one test checks the tab family's x-height, the baseline of a character only the semibold face has, and that the characters egui skips draw in a tab title as in semibold text. Two tab-strip tests check that titles are laid out in the tab family with a stand-in face and in the semibold family without one. The condensed-face test checks the x-height at 200 pt, the shortened-title test also runs in the tab font, the install_fonts test checks the tab family, and ui_fonts' no-craft-fonts test allows the condensed face, which a checkout can give alone. A text-crate test finds the face's row as craft-fonts' catalog has it and rejects malformed rows for it. Two comments use American spelling. --- ASSETS.md | 2 +- NOTICE | 2 + crates/text/build.rs | 52 +++++++----- crates/text/build/condensed_ui_face.rs | 45 ++++++++++ crates/text/src/lib.rs | 3 + crates/ui-egui/src/chrome/tabs.rs | 7 +- crates/ui-egui/src/chrome/tests.rs | 22 ++--- crates/ui-egui/src/i18n/tests.rs | 3 + crates/ui-egui/src/tests/tab_overflow.rs | 79 +++++++++++++++++- crates/ui-egui/src/theme.rs | 101 +++++++++++++++++++---- crates/ui-egui/src/ui_fonts.rs | 26 +++--- crates/ui-egui/tests/install_fonts.rs | 14 +++- docs/development.md | 8 +- docs/ui-parity.md | 2 +- 14 files changed, 299 insertions(+), 67 deletions(-) create mode 100644 crates/text/build/condensed_ui_face.rs diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..b949197d4c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -24,7 +24,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/NOTICE b/NOTICE index 434cd3e524..99470afd8e 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/crates/text/build.rs b/crates/text/build.rs index 5979c6557c..2658094965 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -14,12 +14,16 @@ //! out with a warning, never an error, and never costs the desktop its fonts. //! //! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in -//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A -//! checkout without that row leaves it `None` with a warning, never an error. +//! (`build/condensed_ui_face.rs`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. +//! A checkout without the catalog or that row leaves it `None` with a warning, never an error; an +//! unreadable catalog, a malformed row or a file that can't be embedded is an error with +//! `CRAFT_FONTS_REQUIRED=1`. use std::fmt::Write as _; use std::path::{Path, PathBuf}; +#[path = "build/condensed_ui_face.rs"] +mod condensed_ui_face; #[path = "build/web_fonts.rs"] mod web_fonts; @@ -28,6 +32,7 @@ fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); + println!("cargo::rerun-if-changed=build/condensed_ui_face.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { @@ -55,7 +60,8 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { match condensed_ui_font(&dir) { Ok(entry) => condensed = format!("Some({entry})"), - Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, true)) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, _)) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } } @@ -108,7 +114,7 @@ fn craft_fonts(dir: &Path) -> Result { Ok(out) } -/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +/// The `CraftFont { .. }` initializer of one manifest row of the checkout `dir` (canonical `root`). fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; // The manifest is supplier data: embed only regular files inside the checkout. @@ -124,29 +130,33 @@ fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, sc )) } -/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in -/// Latin catalog. -const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); - -/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. -fn condensed_ui_font(dir: &Path) -> Result { +/// The `CraftFont { .. }` initializer of the condensed face's row in `fonts/latin-manifest.txt` +/// (`build/condensed_ui_face.rs`). The error says whether the checkout is broken: one without the +/// catalog or the row is an older craft-fonts, and an unreadable catalog, a malformed row or a row +/// whose file can't be embedded is broken. +fn condensed_ui_font(dir: &Path) -> Result { + let (family, style) = condensed_ui_face::FACE; let manifest = dir.join("fonts/latin-manifest.txt"); // A checkout without the catalog is watched through its folder, so the build runs again once // the catalog appears. let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; println!("cargo::rerun-if-changed={}", watched.display()); - let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; - let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; - let row = text - .lines() - .map(str::trim) - .filter(|l| !l.is_empty() && !l.starts_with('#')) - .map(|l| l.split(" | ").map(str::trim).collect::>()) - .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); - let Some([family, style, file, scripts, ..]) = row.as_deref() else { - return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + let text = std::fs::read_to_string(&manifest).map_err(|e| { + let older = e.kind() == std::io::ErrorKind::NotFound; + (format!("{}: {e}{}", manifest.display(), if older { " (an older craft-fonts?)" } else { "" }), !older) + })?; + let row = condensed_ui_face::row(&text).map_err(|e| (format!("{}: {e}", manifest.display()), true))?; + let Some((file, scripts)) = row else { + return Err((format!("{family} {style} not in {} (an older craft-fonts?)", manifest.display()), false)); }; - craft_font(dir, &root, family, style, file, scripts) + let root = dir.canonicalize().map_err(|e| (format!("{}: {e}", dir.display()), true))?; + // A row whose file is missing is watched through the file's folder inside the checkout (or the + // checkout's `fonts/`), so the build runs again once the file appears. + craft_font(dir, &root, family, style, file, scripts).map_err(|e| { + let inside = dir.join(file).parent().and_then(|p| p.canonicalize().ok()).filter(|p| p.starts_with(&root) && p.is_dir()); + println!("cargo::rerun-if-changed={}", inside.unwrap_or_else(|| dir.join("fonts")).display()); + (e, true) + }) } /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and diff --git a/crates/text/build/condensed_ui_face.rs b/crates/text/build/condensed_ui_face.rs new file mode 100644 index 0000000000..c70e2cb2a4 --- /dev/null +++ b/crates/text/build/condensed_ui_face.rs @@ -0,0 +1,45 @@ +//! The condensed craft-fonts face document tab titles draw in, and its row in the checkout's opt-in +//! Latin catalog (`fonts/latin-manifest.txt`). Shared by `build.rs` and the crate's tests +//! (`#[path]`-included by both, so it has no dependencies). + +/// The condensed face's family and style. +pub const FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The file and scripts fields of [`FACE`]'s row in the catalog `text`: `None` when no row names +/// the face, and an error when the row that names it does not have the catalog's 8 fields or leaves +/// the file or scripts empty. +pub fn row(text: &str) -> Result, String> { + for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + match fields.as_slice() { + [family, style, file, scripts, _, _, _, _] if (*family, *style) == FACE && !file.is_empty() && !scripts.is_empty() => { + return Ok(Some((*file, *scripts))); + } + [family, style, ..] if (*family, *style) == FACE => return Err(format!("malformed manifest line: {line}")), + _ => {} + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The face's row as storytold/craft-fonts#72 adds it to the catalog is found, rows for other + /// faces are not taken for it, and a row naming it without its file or scripts, or with one of + /// them empty, is an error. + #[test] + fn the_catalog_row_names_the_face() { + let catalog = "# Latin presentation fonts for the Crafting Apps (opt-in).\n\ + Inter | SemiBold | fonts/inter/Inter-SemiBold.ttf | Latn | OFL-1.1 | fonts/inter/OFL.txt | 78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3 | https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip#extras/ttf/Inter-SemiBold.ttf\n\ + Noto Sans | Condensed SemiBold | fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf | Latn | OFL-1.1 | fonts/noto-sans-condensed/OFL.txt | b41ecd0838ecd17b706432a01c0d63f8bf977d851cc2cf37242324233edb9294 | https://github.com/notofonts/latin-greek-cyrillic/releases/download/NotoSans-v2.015/NotoSans-v2.015.zip#NotoSans/unhinted/ttf/NotoSans-CondensedSemiBold.ttf\n"; + assert_eq!(row(catalog), Ok(Some(("fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf", "Latn")))); + let rest = "OFL-1.1 | fonts/a/OFL.txt | 00 | https://example.com/a.zip"; + assert_eq!(row(&format!("Noto Sans | SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "another style"); + assert_eq!(row(&format!("# Noto Sans | Condensed SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "a comment"); + assert_eq!(row("Inter | Bold\n"), Ok(None), "a short row for another face"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | {rest}\n")).is_err(), "a row without its scripts"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | | {rest}\n")).is_err(), "a row with empty scripts"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2028639af4..d1e82be440 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -1068,6 +1068,9 @@ pub fn x_height(data: &[u8], index: u32) -> Option { m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) } +#[cfg(test)] +#[path = "../build/condensed_ui_face.rs"] +mod condensed_ui_face_build; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 1aff4fe1a9..782309a3f0 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_title_font(ui, title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -213,6 +213,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); + let title_font = theme::tab_title_font(ui, title_size); // The windows under the tabs, with the text each tab shows, its whole title and the text laid // out; `active` is the position of the highlighted one. An inactive tab shows the name alone, // without the zoom and the mode in parentheses (color mode and view, or the opacity mask being @@ -225,7 +226,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), title_font.clone(), color); (w, text, title, galley) }) .collect(); @@ -259,7 +260,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, title_font.clone(), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b78968442e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -29,27 +29,29 @@ fn the_tabs_after_the_leading_one_are_drawn_whole() { assert_eq!(super::tab_room(None, false, 120.0, 119.99), 119.99, "no leading tab"); } -/// A shortened title shows at every width that holds "…", fractional ones included (#8584). +/// A shortened title shows at every width that holds "…", fractional ones included (#8584), in the +/// semibold face and in the tab titles' face (the condensed one in a build with craft-fonts, #8583). #[test] fn a_shortened_title_fits_at_fractional_widths() { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let font = crate::theme::semibold(13.0); let title = "Untitled-12 @ 66.67 % (RGB/Preview)"; let mut too_wide = vec![]; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); - let mut width = ellipsis.size().x.ceil() + 1.0; - while width < 200.0 { - let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); - if !fits { - too_wide.push((width, galley.size().x)); + for font in [crate::theme::semibold(13.0), crate::theme::tab_title_font(ui, 13.0)] { + let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); + let mut width = ellipsis.size().x.ceil() + 1.0; + while width < 200.0 { + let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); + if !fits { + too_wide.push((font.family.clone(), width, galley.size().x)); + } + width += 0.25; } - width += 0.25; } }); output.textures_delta.clear(); - assert!(too_wide.is_empty(), "shortened titles wider than their room (room, width): {too_wide:?}"); + assert!(too_wide.is_empty(), "shortened titles wider than their room (family, room, width): {too_wide:?}"); } /// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7954785e30..6136913184 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1501,6 +1501,9 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; + // The tab family is bound only in builds with craft-fonts' condensed face. + let tab = egui::FontFamily::Name(crate::theme::FONT_TAB.into()); + let families: Vec = families.into_iter().filter(|f| *f != tab || fonts.definitions().families.contains_key(f)).collect(); for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let cjk_checked = japanese_ui_font && l.code == "ja"; diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index c9f9edec0a..7b389001d5 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -145,12 +145,87 @@ fn tab_titles_in_the_condensed_face_fit_more_tabs() { let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); // The height of an x, in the tab font and in semibold text. let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; - (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + let tab = if face.is_some() { crate::theme::tab_font(200.0) } else { crate::theme::semibold(200.0) }; + (whole, x(tab), x(crate::theme::semibold(200.0))) }; let (semibold, _, _) = whole_tabs(None); let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); - assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ by + // about 8 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + +/// The tab strip lays its titles out in the tab family's own face when it has one: the monospace +/// face stands in for craft-fonts' condensed face, which CI's craft-fonts checkout does not have +/// (#8583). +#[test] +fn tab_titles_draw_in_the_tab_familys_face() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "name": "Tab test"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(Some(&stand_in))); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 1, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_TAB.into()), "{title}"); + } +} + +/// The fonts the tab strip lays its "Tab test" titles out in. +fn title_fonts(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::FontId)> { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), ..Default::default() }, |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::FontId)>) { + match s { + egui::Shape::Text(t) if t.galley.text().starts_with("Tab test") => { + v.extend(t.galley.job.sections.first().map(|s| (t.galley.text().to_owned(), s.format.font_id.clone()))); + } + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut fonts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut fonts); + } + fonts +} + +/// Without the condensed face the tab family is not bound, and tab titles draw in the semibold +/// family as it is, with a face added to it later (#8583). +#[test] +fn tab_titles_draw_in_semibold_where_the_tab_family_is_not_bound() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..3 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Tab test {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + // A face put at the head of the semibold family after the interface's, as an embedder may. + let mut fonts = crate::theme::interface_fonts_with(None); + let added = "Added semibold".to_owned(); + fonts.font_data.insert( + added.clone(), + std::sync::Arc::new(egui::FontData::from_static(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"))), + ); + fonts.families.entry(egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into())).or_default().insert(0, added); + let ctx = egui::Context::default(); + ctx.set_fonts(fonts); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 3, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), "{title}"); + } } /// With the last document active, the tabs from it to the end leave room before the » button, and diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 11e8af8e22..2743922495 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -497,16 +497,23 @@ pub const FONT_MONO: &str = "mono"; /// The family document tab titles draw in. In a build with craft-fonts' condensed face /// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the /// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so -/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +/// more tabs fit in the strip (#8583). Without it the family is not bound, and tab titles draw in +/// [`FONT_UI_SEMIBOLD`] ([`tab_title_font`]). pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } -/// A document tab's title font ([`FONT_TAB`]). -pub fn tab_font(size: f32) -> FontId { +/// A font in [`FONT_TAB`], which is bound only with the condensed face: see [`tab_title_font`]. +pub(crate) fn tab_font(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_TAB.into())) } +/// The font document tab titles draw in on `ui`: the [`FONT_TAB`] family when `ui`'s fonts bind +/// it (with the condensed face), otherwise [`semibold`]. +pub fn tab_title_font(ui: &egui::Ui, size: f32) -> FontId { + let font = tab_font(size); + if ui.ctx().fonts(|f| f.definitions().families.contains_key(&font.family)) { font } else { semibold(size) } +} /// Whether `family` draws semibold text and takes the bold fallback faces. pub(crate) fn is_semibold(family: &FontFamily) -> bool { matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) @@ -516,7 +523,7 @@ pub fn mono(size: f32) -> FontId { } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`], and [`FONT_TAB`] with the condensed face). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -548,9 +555,10 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); let semi = family(semi, &fallback); - let tab = tab_faces(&mut fonts, &semi, condensed); + if let Some(tab) = tab_faces(&mut fonts, &semi, condensed) { + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); + } fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); - fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); @@ -559,28 +567,38 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon /// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first /// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its -/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. -fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { +/// baseline. egui's own faces are listed under their own names, uncopied, as in the semibold +/// family: egui skips some of their characters (the Ubuntu logo, for one) only under those names. +/// `None` without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Option> { let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); - let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); - let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; - let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data))?; + let f = condensed?; + let own = vectorcraft_text::x_height(f.bytes, 0)?; let name = craft_font_name(f); let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); - // `baseline_copies` reads the head of each family it is given: here only this one. + // `baseline_copies` reads the head of each family it is given. `row` also has egui's empty + // Proportional and Monospace families, whose copies are not this family's. + let tab = FontFamily::Name(FONT_TAB.into()); let mut row = FontDefinitions::empty(); row.font_data.insert(name.clone(), Arc::new(head.clone())); - row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + row.families.insert(tab.clone(), vec![name.clone()]); let mut faces = vec![name.clone()]; for face in semi { + if FontDefinitions::builtin_font_names().contains(&face.as_str()) { + faces.push(face.clone()); + continue; + } let Some(data) = fonts.font_data.get(face).cloned() else { continue }; - for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + for (copy, data, _) in + crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data).into_iter().filter(|(_, _, f)| f.contains(&tab)) + { fonts.font_data.insert(copy.clone(), Arc::new(data)); faces.push(copy); } } fonts.font_data.insert(name, Arc::new(head)); - faces + Some(faces) } /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace @@ -831,4 +849,57 @@ mod tests { assert_eq!(ctx.global_style().interaction.tooltip_delay, f32::INFINITY); assert_eq!(ctx.global_style().visuals.window_fill, Tokens::for_brightness(Brightness::Light).panel); } + + /// The face heading the tab family draws an x as tall as the semibold face does, and a + /// character it lacks falls back to the semibold face (drawn at its own 0.92 scale) on its + /// baseline (#8583). The monospace face stands in for craft-fonts' condensed face, which CI's + /// craft-fonts checkout does not have. + #[cfg(feature = "interface-fonts")] + #[test] + fn the_tab_family_keeps_the_semibold_x_height_and_baseline() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut defs = interface_fonts_with(Some(&stand_in)); + assert_eq!(defs.families[&FontFamily::Name(FONT_TAB.into())][0], craft_font_name(&stand_in)); + // The semibold face alone, as it draws a character in its own family. + defs.families.insert(FontFamily::Name("probe".into()), vec!["Inter-SemiBold".to_owned()]); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + ctx.set_fonts(defs); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, Color32::WHITE)).rows[0].glyphs.clone(); + let x = |font: FontId| glyphs("x", font)[0].uv_rect.size.y; + let (x_tab, x_semibold) = (x(tab_font(200.0)), x(semibold(200.0))); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ + // by about 10 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // egui skips some characters of its own faces (the Ubuntu logo, two symbols in its emoji + // face); a tab title draws them as semibold text does. + for c in ['\u{534D}', '\u{5350}', '\u{E0FF}', '\u{EFFD}', '\u{F0FF}', '\u{F200}'] { + let has = |font: FontId| ctx.fonts_mut(|f| f.has_glyph(&font, c)); + let name = format!("U+{:04X}", u32::from(c)); + assert_eq!(has(tab_font(13.0)), has(semibold(13.0)), "{name} has a glyph in a tab title as in semibold text"); + if has(semibold(13.0)) { + // Both families take it from the same fallback face, which draws it at one size. + let size = |font: FontId| glyphs(&c.to_string(), font).first().map(|g| g.uv_rect.size); + assert_eq!(size(tab_font(13.0)), size(semibold(13.0)), "{name} draws at the same size in a tab title as in semibold text"); + } + } + let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; + // U+0182, which Inter has and the monospace face lacks. + let c = 'Ƃ'; + for size in [13.0_f32, 24.0, 40.0, 100.0] { + let own = glyphs(&c.to_string(), FontId::new(size, FontFamily::Name("probe".into()))); + let row = glyphs(&format!("H{c}"), tab_font(size)); + assert_eq!((own.len(), row.len()), (1, 2), "{c} lays out as one glyph"); + // Half a point: one device pixel at 2 pixels per point, for each glyph's rounding. + let drift = (bottom(&row[1]) - row[0].pos.y) - (bottom(&own[0]) - own[0].pos.y); + assert!(drift.abs() <= 0.5, "at {size} pt, {c} ends {drift:.2} pt below the tab family's baseline"); + } + } } diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index cb419067e1..8e2d07ff5c 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -239,7 +239,7 @@ pub(crate) fn baseline_copies(defs: &FontDefinitions, name: &str, data: &FontDat let mut copies: Vec<(String, FontData, Vec)> = vec![]; for (family, stack) in &defs.families { let head = stack.first().and_then(|head| Some((head.as_str(), defs.font_data.get(head)?))); - let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, (*data.font).as_ref(), data.index)); + let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, data)); if let Some((_, _, families)) = copies.iter_mut().find(|(_, copy, _)| copy.tweak.y_offset_factor.to_bits() == shift.to_bits()) { families.push(family.clone()); continue; @@ -266,15 +266,19 @@ fn em_metrics(data: &[u8], index: u32) -> Option<(f32, f32)> { Some((ascent / upem, (ascent - descent + gap) / upem)) } -/// The `y_offset_factor` that puts the glyphs of the face at `index` of `face` on the baseline of -/// the row's first face, whose ascent, row height and offset in ems are `row`. egui draws a -/// fallback glyph's baseline at its face's ascent plus half the difference between the two row -/// heights, so a face with a taller ascent or descent sits off the baseline by the shift computed -/// here, in ems of the font size, limited to half an em either way. -fn baseline_shift(row: (f32, f32, f32), face: &[u8], index: u32) -> f32 { +/// The `y_offset_factor` that puts the glyphs of the fallback face `data` on the baseline of the +/// row's first face, whose ascent, row height and offset in ems are `row`. egui draws a fallback +/// glyph's baseline at its face's ascent plus half the difference between the two row heights, so a +/// face with a taller ascent or descent sits off the baseline by the shift computed here, in ems of +/// the font size, limited to half an em either way. egui scales the face's metrics and its +/// `y_offset_factor` by the face's own `FontTweak` scale, so both are measured at that scale. +fn baseline_shift(row: (f32, f32, f32), data: &FontData) -> f32 { let (row_ascent, row_height, row_offset) = row; - let shift = em_metrics(face, index).map_or(0.0, |(ascent, height)| row_ascent + row_offset - (ascent + 0.5 * (row_height - height))); - if shift.is_finite() { shift.clamp(-0.5, 0.5) } else { 0.0 } + let scale = data.tweak.scale; + let shift = em_metrics((*data.font).as_ref(), data.index) + .map_or(0.0, |(ascent, height)| row_ascent + row_offset - scale * ascent - 0.5 * (row_height - scale * height)); + let factor = if shift.is_finite() { shift.clamp(-0.5, 0.5) / scale } else { 0.0 }; + if factor.is_finite() { factor } else { 0.0 } } /// Call `f` with the text of `shape` and the shapes it holds. @@ -375,8 +379,10 @@ mod tests { fonts.finish(&ctx); frame(&ctx, &mut fonts, "日本語の文字 Layer 1"); if vectorcraft_text::CRAFT_FONTS.is_empty() { + // The condensed tab face is read from its own catalog, so a checkout can give it alone. + let condensed = vectorcraft_text::CONDENSED_UI_FONT.as_ref().map(crate::theme::craft_font_name); let names: Vec = ctx.fonts(|f| f.definitions().font_data.keys().cloned().collect()); - assert!(names.iter().all(|n| !n.starts_with("craft-fonts")), "{names:?}"); + assert!(names.iter().all(|n| !n.starts_with("craft-fonts") || Some(n) == condensed.as_ref()), "{names:?}"); } assert!(has_glyph(&ctx, 'L')); } diff --git a/crates/ui-egui/tests/install_fonts.rs b/crates/ui-egui/tests/install_fonts.rs index d7ebcaab27..56d49bc3bc 100644 --- a/crates/ui-egui/tests/install_fonts.rs +++ b/crates/ui-egui/tests/install_fonts.rs @@ -33,7 +33,8 @@ fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) { fn every_family_the_panels_draw_in_is_bound() { let ctx = context(); frame(&ctx, |ui| { - for font in [theme::semibold(12.0), theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { + let tab = theme::tab_title_font(ui, 12.0); + for font in [theme::semibold(12.0), tab, theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { ui.label(egui::RichText::new("Gaussian Blur").font(font)); } }); @@ -45,6 +46,17 @@ fn every_family_the_panels_draw_in_is_bound() { let installed: Vec<&str> = INTERFACE_FACES.into_iter().filter(|face| definitions.font_data.contains_key(*face)).collect(); let family = |family: FontFamily| definitions.families[&family].clone(); let named = |name: &str| family(FontFamily::Name(name.into())); + // The tab family is bound, headed by craft-fonts' condensed face and followed by the semibold + // faces, when the build has that face and both faces give an x-height to match. + let x_height = |name: &String| definitions.font_data.get(name).and_then(|d| vectorcraft_text::x_height((*d.font).as_ref(), d.index)); + let semibold_head = named(theme::FONT_UI_SEMIBOLD).first().and_then(x_height); + match vectorcraft_text::CONDENSED_UI_FONT.as_ref().filter(|f| vectorcraft_text::x_height(f.bytes, 0).is_some() && semibold_head.is_some()) { + None => assert!(!definitions.families.contains_key(&FontFamily::Name(theme::FONT_TAB.into()))), + Some(f) => { + assert_eq!(named(theme::FONT_TAB)[0], format!("craft-fonts {} {}", f.family, f.style)); + assert!(named(theme::FONT_TAB).len() > named(theme::FONT_UI_SEMIBOLD).len(), "the semibold faces follow the condensed one"); + } + } if cfg!(feature = "interface-fonts") { assert_eq!(installed, INTERFACE_FACES); assert_eq!(named(theme::FONT_UI)[0], "Inter"); diff --git a/docs/development.md b/docs/development.md index 66f925324e..950b996ed9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,8 +178,9 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the x-height of the interface's semibold face, so more tabs fit in the strip. Without - `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab - titles draw in the semibold face. + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), + `theme::FONT_TAB` is not bound and tab titles draw in the semibold family + (`theme::tab_title_font`). - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. @@ -205,7 +206,8 @@ font that has them to each of the families below (`ctx.add_font` with an `Insert family). The panels and dialogs draw in their own egui families (`theme::FONT_UI`, `FONT_UI_SEMIBOLD`, -`FONT_MONO`), and egui panics drawing text in a family no font is bound to. `VectorcraftApp::logic` +`FONT_MONO`, and `FONT_TAB` for document tab titles in builds with the condensed face), and egui +panics drawing text in a family no font is bound to. `VectorcraftApp::logic` binds them on its first frame; an embedder that draws the panels or dialogs without it calls `theme::install_fonts` once on its context, with or without `interface-fonts`. It replaces the context's font definitions, so the embedder's own fonts are added after it. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8b5a9f315a..b6fa3393c1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,7 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`, `theme::tests::the_tab_family_keeps_the_semibold_x_height_and_baseline`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From 1bf1001a90b73e0ce03a5c75aea77e2cc2769a2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:03:10 -0800 Subject: [PATCH 033/298] JavaScript: for-of loops and destructuring in ES2015 realms With Options::es2015, vectorcraft-js reads and runs for-of loops and array and object destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3) in var, let and const declarations, assignments, function and arrow parameters and catch clauses, with defaults, holes and rest elements. Object literals take shorthand and computed names. for-of, spread and array patterns use the iterator protocol and call the iterator's return method when a loop or pattern stops early. Destructuring undefined or null throws a TypeError. Object rest properties (ECMAScript 2018) stay syntax errors. A realm switched to ES2015 without Symbol.iterator walks arrays, arguments objects and strings by index. Each step takes fuel, a rest element or spread reserves the whole size of each new element against the heap limit, and nested patterns count against Options::max_depth. The test262 runner reads the for-of and dstr folders: 609 of 617 runs pass (529 before). --- crates/engine/src/tests/script_run.rs | 10 + crates/js/src/ast.rs | 71 ++++- crates/js/src/bytecode.rs | 36 ++- crates/js/src/compiler.rs | 222 +++++++++++----- crates/js/src/compiler/pattern.rs | 288 ++++++++++++++++++++ crates/js/src/es2015_tests.rs | 308 +++++++++++++++++++++- crates/js/src/heap.rs | 17 +- crates/js/src/interp.rs | 164 ++++++------ crates/js/src/interp_tests.rs | 1 + crates/js/src/iteration.rs | 274 +++++++++++++++++++ crates/js/src/lib.rs | 22 +- crates/js/src/parser.rs | 220 +++++++++++----- crates/js/src/parser/pattern.rs | 362 ++++++++++++++++++++++++++ crates/js/src/tests.rs | 20 +- crates/js/tests/test262.rs | 113 ++++++++ docs/mcp.md | 19 +- docs/target-app-parity.md | 5 +- 17 files changed, 1885 insertions(+), 267 deletions(-) create mode 100644 crates/js/src/compiler/pattern.rs create mode 100644 crates/js/src/iteration.rs create mode 100644 crates/js/src/parser/pattern.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..eb8f43cc41 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -328,6 +328,16 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); assert_eq!(legacy["log"], json!([3]), "{legacy}"); + // `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made. + let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);"; + let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap(); + assert_eq!(r["log"], json!([7, 9, "function"]), "{r}"); + let kept = s + .execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));"))) + .unwrap(); + assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); + let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..9dbf58f33e 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -80,15 +80,19 @@ pub enum PropertyKey { Ident(String), String(Vec), Number(f64), + /// `[expression]` with [`crate::Options::es2015`]: the key is the expression's value. + Computed(ExprId), } impl PropertyKey { - /// The key as the string a property is stored under (a number through ToString). + /// The key as the string a property is stored under (a number through ToString); empty for + /// a computed key, whose string is known only at run time. pub fn to_utf16(&self) -> Vec { match self { PropertyKey::Ident(name) => name.encode_utf16().collect(), PropertyKey::String(s) => s.clone(), PropertyKey::Number(n) => crate::number::to_string(*n).encode_utf16().collect(), + PropertyKey::Computed(_) => Vec::new(), } } } @@ -269,20 +273,33 @@ pub enum XmlNamePart { Computed(ExprId), } +/// What a declaration, a parameter or a catch clause binds: a name, or with +/// [`crate::Options::es2015`] a destructuring pattern (ECMA-262 11th edition, section 13.3.3). +/// +/// A pattern is an [`Expr::Array`] or an [`Expr::Object`] whose targets are [`Expr::Ident`] +/// names or nested patterns; an [`Expr::Assign`] with no operator gives a target its default +/// value, and an [`Expr::Spread`] as the last element of an array pattern is its rest element. +#[derive(Clone, Debug, PartialEq)] +pub enum Binding { + Name(Name), + Pattern(ExprId), +} + #[derive(Clone, Debug, PartialEq)] pub struct VarDecl { - pub name: Name, + pub target: Binding, pub init: Option, } -/// What a `for (… in …)` statement assigns each property name to. +/// What a `for (… in …)` or `for (… of …)` statement assigns each property name or value to. #[derive(Clone, Debug, PartialEq)] pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), + /// An assignment target, or with [`crate::Options::es2015`] an assignment pattern. Expr(ExprId), /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. - Lexical(LexKind, Name), + Lexical(LexKind, Binding), } #[derive(Clone, Debug, PartialEq)] @@ -304,7 +321,7 @@ pub struct SwitchCase { #[derive(Clone, Debug, PartialEq)] pub struct CatchClause { - pub param: Name, + pub param: Binding, pub body: Vec, } @@ -343,6 +360,12 @@ pub enum Stmt { body: StmtId, each: bool, }, + /// `for (… of …)` with [`crate::Options::es2015`] (ECMA-262 11th edition, section 13.7.5). + ForOf { + target: ForInTarget, + iterable: ExprId, + body: StmtId, + }, /// `default xml namespace = expression;`. DefaultXmlNamespace(ExprId), Continue(Option), @@ -384,11 +407,11 @@ pub struct Function { pub kind: FunctionKind, pub name: Option, /// The parameters before a rest parameter. - pub params: Vec, + pub params: Vec, /// Each parameter's default value, in the order of `params` (empty when none has one). pub defaults: Vec>, - /// The rest parameter (`...name`). - pub rest: Option, + /// The rest parameter (`...name` or `...[pattern]`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -397,9 +420,9 @@ pub struct Function { } impl Function { - /// The parameters are plain names: no default value and no rest parameter. + /// The parameters are plain names: no pattern, no default value and no rest parameter. pub fn simple_params(&self) -> bool { - self.rest.is_none() && self.defaults.iter().all(Option::is_none) + self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_))) } } @@ -432,6 +455,34 @@ impl Ast { self.functions.get(id.0 as usize) } + /// The names a binding binds, in source order. + pub fn bound_names(&self, binding: &Binding) -> Vec { + match binding { + Binding::Name(n) => vec![n.clone()], + Binding::Pattern(p) => self.pattern_names(*p), + } + } + + /// The names a destructuring pattern binds, in source order, walked without recursion. + pub fn pattern_names(&self, pattern: ExprId) -> Vec { + let mut out = Vec::new(); + let mut work = vec![pattern]; + while let Some(id) = work.pop() { + match self.expr(id) { + Some(Expr::Ident(n)) => out.push(Name { name: n.clone(), span: self.expr_span(id) }), + Some(Expr::Array(elements)) => work.extend(elements.iter().rev().flatten().copied()), + Some(Expr::Object(props)) => work.extend(props.iter().rev().filter_map(|p| match p.value { + PropertyValue::Init(e) => Some(e), + _ => None, + })), + Some(Expr::Assign { target, .. }) => work.push(*target), + Some(Expr::Spread(arg)) => work.push(*arg), + _ => {} + } + } + out + } + /// The expression with any parentheses around it removed. pub fn unparenthesized(&self, mut id: ExprId) -> ExprId { while let Some(Expr::Paren(inner)) = self.expr(id) { diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..a8d8471a4c 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -205,6 +205,26 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1). + GetIterator, + /// `record` → `record value`, or jumps with `record` when the iterator is done. + IterStep(u32), + /// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, `undefined` once it is done. + IterValue(u32), + /// `record x₁…xₙ` → `record x₁…xₙ array`: the values left, in an array. + IterRest(u32), + /// `record` → nothing: closes the iterator unless it is done (IteratorClose). + IterClose, + /// `record exception` → throws the exception after closing the iterator unless it is done. + IterCloseThrow, + /// `value` → `value`: a `TypeError` when it is `undefined` or `null`. + RequireObjectCoercible, + /// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`: an object pattern's property. + PatternGet(u32), + /// `object key value` → `object`: a property with a computed name. + InitIndex, + /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. + InitAccessorIndex(bool), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -296,9 +316,13 @@ pub(crate) struct Code { pub(crate) arrow: bool, /// The code reads `this` or calls `eval`, itself or in an arrow function inside it. pub(crate) uses_this: bool, - /// The function has default or rest parameters: its parameters start uninitialized, its - /// code initializes them and then enters its body with [`Op::BodyEnv`]. + /// The function has default, rest or destructured parameters: its parameters start + /// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The names the destructured parameters bind, which start uninitialized beside the + /// parameters. A destructured parameter's own entry in `params` is a name no script can + /// write. + pub(crate) pattern_names: Vec, } impl Code { @@ -380,7 +404,13 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::GetIterator | Op::RequireObjectCoercible => e(1, 1), + Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, + Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?), + Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?), + Op::IterClose => e(1, 0), + Op::IterCloseThrow => end(2), + Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..3321475da6 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -13,17 +13,20 @@ //! chains and labels are compiled with loops; every other kind of nesting is counted, and code //! nested deeper than [`MAX_DEPTH`] gives a `SyntaxError` instead of exhausting the stack. +mod pattern; + use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ - AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId, - TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyKey, PropertyValue, + Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; use crate::heap::Key; use crate::value::Str; +use pattern::Mode; /// How deeply the compiler may recurse: past the parser's default nesting limit, and shallow /// enough for a 1 MiB stack. @@ -61,6 +64,9 @@ enum Ctx { Jump { labels: Vec, is_loop: bool, plain_break: bool, brk: Label, cont: Option