From 03b5c9ce9247d8d2093e70f4abdc56d210cf731e Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 7 Nov 2026 17:44:19 +0300 Subject: [PATCH 001/198] Panels: the Artboards list fills the panel, so the panel resizes (#6085) The Artboards panel gave its list a fixed height: `ui.set_min_height(110.0)` and `ScrollArea::max_height(220.0)`. The panel therefore kept that content size whatever the window or the floating window's height, a long list scrolled inside a small clipped area, and the buttons sat part way down with empty space below them. The list now takes the panel's height less the bottom bar, as the Layers panel's list does: `list_height()` gives `available - 46.0`, but never less than one 24-point row, with `ScrollArea::auto_shrink([false, false])` and `min_scrolled_height(0.0)`. The 46 points hold the bar's divider, the spacing around it and its 24-point buttons, as the test measures them on the screen-reader tree; at the dock's minimum height one whole row stays in view and the dock panel scrolls to the bottom bar. The list grows and shrinks with the panel, and long lists scroll in it. Tests: the panel has 36 artboards, so the list overflows a 300-point panel. panels::artboards::tests::the_list_fills_the_panel_and_the_bottom_bar_follows_its_height renders the panel 300 and 700 points tall and checks the bottom bar's divider sits at the bottom of each, the New Artboard button's bounds end inside the panel at 300, 700 and 80 points, the bar moves with the height, and the 36th row lies below the bar's divider (the list scrolls instead of pushing the bar out); it fails with the old fixed list. panels::artboards::tests::a_panel_at_the_docks_minimum_height_shows_a_whole_row checks the list keeps one whole row at the minimum height and takes the rest otherwise. The panel's `show` has a docstring. Docs: roadmap, target-app-parity (revision row, status line, evidence bullet and the UI chrome area row) and ui-parity (revision row and an Artboards checklist row), all dated 2026-11-07. --- crates/ui-egui/src/panels/artboards.rs | 21 +++- crates/ui-egui/src/panels/artboards/tests.rs | 102 +++++++++++++++++++ docs/roadmap.md | 3 +- docs/target-app-parity.md | 6 +- docs/ui-parity.md | 4 +- 5 files changed, 130 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index d02f5f0280..6150ccd9f3 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -500,6 +500,20 @@ fn select_copies(app: &mut VectorcraftApp, all: &[usize], r: &Value) { } } +/// The height of one artboard row, its name and number drawn inside it. +const ROW_H: f32 = 24.0; + +/// The list's height in a panel whose body has `available` points: the panel less the bottom bar's +/// 46 points (its divider, the spacing around it and its 24-point buttons, which the test measures), +/// but never below one row, so a panel at the dock's minimum height still shows a whole row and the +/// dock panel scrolls to the bottom bar below it. +fn list_height(available: f32) -> f32 { + (available - 46.0).max(ROW_H) +} + +/// The Artboards panel: the artboard rows with their selection, rename, lock, reorder and double-click +/// rules, the list filling the panel above the bottom bar, and the panel's buttons (`Rearrange All +/// Artboards`, `Move Up`/`Move Down`, `New Artboard`, `Delete Artboard`) in that bar. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let abs: Vec = app.session.active().map(|d| d.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); @@ -514,10 +528,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut row_clicked = false; // A row dropped on another row: (from, to), the index it lands at. let mut dropped = None; + // The list grows and shrinks with the panel, taking the height the bottom bar leaves, as the + // Layers panel's list does (#6085). + let list_h = list_height(ui.available_height()); let list_rect = widgets::list_box(ui, |ui| { - ui.set_min_height(110.0); ui.spacing_mut().item_spacing.y = 0.0; - let scrolled = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(220.0).show(ui, |ui| { + let list = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(list_h).min_scrolled_height(0.0); + let scrolled = list.auto_shrink([false, false]).show(ui, |ui| { for (i, name) in abs.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); if resp.drag_started() { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index c01d82eb13..1a6b72c453 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -2,6 +2,108 @@ use super::*; use crate::widgets::accessibility_tests::{named, tree}; use vectorcraft_engine::Session; +/// The list fills the panel's height less the bottom bar, so the bar sits at the bottom of the +/// panel and follows the window's height, as the Layers panel's does (#6085). With 36 rows the +/// list overflows a short panel and scrolls instead of pushing the bar out. +#[test] +fn the_list_fills_the_panel_and_the_bottom_bar_follows_its_height() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 36})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let divider = crate::theme::Tokens::get(&ctx).divider; + // The bottom bar's divider across the panel, at the height of a panel `h` tall. + let bar_y = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.rect.height() == 1.0 && r.fill == divider => Some(r.rect.top()), + _ => None, + }) + .expect("the bottom bar draws its divider") + }; + // The bottom bar's buttons through the screen-reader tree, at the height of a panel `h` tall. + let buttons_end = |app: &mut VectorcraftApp, h: f32| { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut end = None; + for time in [0.0, 0.1] { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let nodes: Vec = + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(); + if let Some(b) = nodes.iter().find(|n| n.label() == Some("New Artboard")).and_then(|n| n.bounds()) { + end = Some((b.y1 as f32, h)); + } + } + end.expect("the bottom bar's New Artboard button is named") + }; + // The 36th row's name: in a 300-point panel it lies below the bar's divider, so the list + // scrolls inside the panel and does not move the bar down. + let last_row = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == "Artboard 36" => Some(t.visual_bounding_rect()), + _ => None, + }) + .expect("the 36th row is laid out") + }; + let (short_buttons, _) = buttons_end(&mut app, 300.0); + let short = bar_y(&mut app, 300.0); + let last = last_row(&mut app, 300.0); + assert!(last.top() > short, "the 36 rows overflow a 300 px panel: row 36 at {last:?}, the bar at {short}"); + let (tall_buttons, _) = buttons_end(&mut app, 700.0); + let tall = bar_y(&mut app, 700.0); + assert!(short_buttons <= 300.0 - 1.0, "the bar's buttons end inside a 300 px panel, not below it: {short_buttons}"); + assert!(tall_buttons <= 700.0 - 1.0, "and inside a 700 px one: {tall_buttons}"); + // A panel as short as the dock allows (80 points) still keeps its buttons inside. + let (tiny_buttons, _) = buttons_end(&mut app, 80.0); + assert!(tiny_buttons <= 80.0 - 1.0, "and inside an 80 px one: {tiny_buttons}"); + assert!(short > 300.0 - 40.0, "the bar sits at the bottom of a 300 px panel: {short}"); + assert!(tall - short > 350.0, "the bar follows the panel's height: {short} -> {tall}"); +} +/// A panel at the dock's minimum height keeps one whole 24-point row in view, with the dock panel +/// scrolling to the bottom bar below it; a roomier panel gives the list the rest of its height (#6085). +#[test] +fn a_panel_at_the_docks_minimum_height_shows_a_whole_row() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 36})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let border = crate::theme::Tokens::get(&ctx).input_border; + // The list box frame drawn by a panel `h` points tall. + let list = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.stroke.width == 1.0 && r.stroke.color == border && r.rect.width() > 200.0 => Some(r.rect), + _ => None, + }) + .expect("the list box's frame") + }; + assert_eq!(list_height(0.0), ROW_H, "never below one row"); + assert_eq!(list_height(60.0), ROW_H, "at the dock's minimum height one row still fits"); + assert_eq!(list_height(200.0), 154.0, "and otherwise the bottom bar's 46 points are left"); + assert!(list(&mut app, 60.0).height() >= ROW_H, "one whole row at the dock's minimum height"); + let roomy = list(&mut app, 300.0); + assert!(roomy.height() >= 200.0 && roomy.height() < 300.0, "a roomier panel gives the list its height: {roomy:?}"); +} /// Clicking a row makes its artboard the active one (the navigator's, Fit Artboard in Window's). #[test] fn clicking_a_row_makes_its_artboard_active() { diff --git a/docs/roadmap.md b/docs/roadmap.md index c4246c7114..2e1de3e722 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-07 · **Change:** minor (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-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -36,6 +36,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085); scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0af2f06708..0c171eb047 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-07 · **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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -31,6 +31,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel's height and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085); scores and estimates unchanged. | | 2026-11-07 | minor | The canvas keeps selection outlines, anchors and handles between frames, so an idle frame with a large selection redraws them as one mesh; scores and estimates unchanged | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-06 | minor | Stroke gradients: an arrowhead whose tip sits on the end of a long straight leg is painted by the gradient to the corners of its base. The slices that reach across a head now run to the end of its reach instead of narrowing towards the next corner (#5964). Test: `stroke::tests_gradient::slices_cover_an_arrowhead_on_a_long_straight_leg`. Scores and estimates unchanged. | @@ -211,7 +212,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% | print preview fidelity | 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, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, 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; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; 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 | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, 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; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; 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; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score 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 | | 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** | | @@ -555,6 +556,7 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. +- **The Artboards panel resizes with the window (#6085):** its list takes the panel's height less the bottom bar, as the Layers panel's list does, so a long artboard list scrolls in a panel that grows and shrinks with the window and the buttons stay at its bottom (`panels::artboards` test `the_list_fills_the_panel_and_the_bottom_bar_follows_its_height`, which fails with the old fixed 110/220 px list). - **Selected artboard deletion:** the Artboards panel menu, panel trash button and Properties use the same selected set; selecting all retains artboard 1. Pointer-event tests cover nonadjacent and single selections, the original first-board survivor, ordinary artwork, Undo/Redo and the single-board guard. Public reference: [Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). - **Delete Empty Artboards:** the Artboards panel menu item ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html)) runs `artboard.deleteEmpty`: every unlocked artboard with no artwork goes with its guides in one undo step, artboard 1 stays when every artboard is empty and none is locked, and the panel makes an artboard that is left active; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). Engine tests in `tests/panelcmds.rs` (`delete_empty_artboards_*`) and the panel test `delete_empty_artboards_deletes_the_empty_ones_and_selects_one_left`. The menu item's enabled check measures nothing in a document with one artboard, and Save Gradient Preset's check reads the proxy's paint without measuring the object; both give the same answer as before. An artboard that no path's control points, grown by the farthest its strokes reach, can meet is found empty without measuring the path. With an open path of 200,000 anchors selected, the checks take under 0.01 ms instead of 21.9 ms and 17.2 ms in a release build; with a second, empty artboard, Delete Empty Artboards' check takes 0.85 ms instead of 42.1 ms. Tests `delete_empty_artboards_is_enabled_exactly_when_it_deletes_something`, `delete_empty_artboards_enabled_state_matches_the_command_on_varied_documents`, `empty_artboard_checks_match_the_visual_bounds_on_varied_strokes`, `the_empty_artboard_check_matches_measuring_every_artboard`, `the_save_check_matches_saving_with_and_without_a_gradient`, `the_unmeasured_proxy_paint_is_the_measured_one` and `the_unmeasured_proxy_paint_is_the_measured_one_on_varied_objects`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4efbee4aa2..961cb7fef3 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-06 · **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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; 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 @@ -39,6 +39,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel and the buttons stay at its bottom, so the panel resizes with the window (#6085); scores and estimates unchanged | | 2026-10-30 | minor | Home screen: welcome, New / Open and Community are centred and the large Discord button uses the theme accent, part of #4684; scores and estimates unchanged (estimated) | | 2026-11-06 | minor | Snap to Grid: a straight segment dragged with Direct Selection lands its anchors on the grid, not the pressed point (#3835); scores and estimates unchanged | | 2026-11-06 | minor | Drop Shadow: a swatch beside Color follows the hex and a double-click opens the Color Picker over the dialog, whose OK fills Color (#5364); scores and estimates unchanged | @@ -291,6 +292,7 @@ tools, never checked side by side) isn't captured row by row. | Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | | Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | | Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | +| Artboards panel: the list fills the panel's height and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085) | done | the list takes ui.available_height() less the bottom bar with ScrollArea::auto_shrink([false, false]); panels::artboards test he_list_fills_the_panel_and_the_bottom_bar_follows_its_height | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | | Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | | Artboard navigator synchronizes the active tool selection before deletion | done | Actual status-bar Next → Delete/Backspace and Next → Properties Delete regressions in `chrome.rs` cover surviving board records, preserved artwork and Undo/Redo; other tools keep object selection and history. **Tab-switch follow-up:** document-tab changes align the Artboard tool with the displayed board. Actual A → B → A tab clicks followed by Properties Delete and controls for same-tab multiselection, Move/Scale Artwork options and other tools passed, along with historical full CI on `a0671777`. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). **Clean-tab close:** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. | From 47d6facb74b66fcc3055f936c8aa45c614e7c1e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:34:37 -0800 Subject: [PATCH 002/198] Part of #978: Show Hex Field in the Color Wheel panel takes hex with an alpha and CSS colors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Panel menu › Show Hex Field (ui.colorWheel {hexField}) adds a field under the wheel or the box. It shows the color's six hex digits, and two more while the opacity that Show Opacity sets is under 100 %. It takes a hex color of 3, 4, 6 or 8 digits and a CSS rgb(), hsl() or oklch() color. A typed color is applied in the same way as a wheel pick, in one undo step, and an alpha sets that opacity, whether or not the opacity row shows. Where the opacity row is gray (nothing selected, an object selected in a symbol instance, or a fill or stroke row on type characters or missing), only the color is applied. Text that gives the color and opacity already there records no undo step, unless the color is a tint of a global swatch. A click on the wheel that takes the focus from an edited field applies the text, then the click. An opacity edit of a gradient stop or point keeps the OKLCH values picked last for it, as it keeps the HSB. - crates/color/src/css.rs reads the hex, rgb(), rgba(), hsl(), hsla() and oklch() syntax of CSS Color 4, the comma-separated legacy form of rgb() and hsl() included, and clamps values where CSS clamps them when it parses them. VectorCraft's own rules on top of that: the # of a hex color may be left out, none reads as 0, an hsl() channel outside the sRGB range is clipped, an oklch() color outside sRGB takes the largest chroma that fits, and text over 48 characters is refused. - color.parse {text} answers {color, hex, opacity}; oklch() is an error while the working RGB space is not sRGB. - The Color panel's hex field and the color parameters of other commands still refuse #rrggbbaa and #rgba. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/color/src/css.rs | 417 ++++++++++++++++++ crates/color/src/lib.rs | 1 + crates/engine/src/cmd/colorcmds.rs | 25 ++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/colormgmt.rs | 42 ++ crates/engine/tests/color_settings.rs | 17 + crates/engine/tests/command_sweep.rs | 5 + crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 141 +++++- .../ui-egui/src/panels/tests_color_wheel.rs | 2 +- .../src/panels/tests_color_wheel_box.rs | 16 +- .../src/panels/tests_color_wheel_hex.rs | 329 ++++++++++++++ .../src/panels/tests_color_wheel_opacity.rs | 33 ++ docs/control-protocol.md | 7 +- docs/mcp.md | 26 +- docs/target-app-parity.md | 2 +- 46 files changed, 1151 insertions(+), 30 deletions(-) create mode 100644 crates/color/src/css.rs create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_hex.rs diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs new file mode 100644 index 0000000000..4d699854ce --- /dev/null +++ b/crates/color/src/css.rs @@ -0,0 +1,417 @@ +//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha +//! (), `rgb()` and `rgba()` +//! (), `hsl()` and `hsla()` +//! () and `oklch()` +//! (). The functions take the +//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also +//! take the comma-separated legacy form (). +//! Hues take the angle units of CSS Values 4 (). A hex +//! color may leave out its `#`. + +use crate::oklab::{self, CHROMA_FULL}; + +/// The most characters a color text may have, spaces around it not counted. +pub const MAX_CHARS: usize = 48; + +/// The space a parsed color's red, green and blue are in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Space { + /// The numbers as written: a hex color, `rgb()` or `hsl()`. + Srgb, + /// sRGB converted from `oklch()`. + Oklch, +} + +/// A color read from CSS text. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CssColor { + /// Red, green and blue from 0 to 1. + pub rgb: [f32; 3], + /// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1). + pub alpha: Option, + pub space: Space, +} + +/// The color `text` gives, or `None` when it is not one of the module's forms or has more than +/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green +/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness +/// to 0..=1 and chroma to 0 or more. `none` reads as 0. An `hsl()` color whose red, green or blue +/// falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its +/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such +/// colors into the gamut by its own rules instead. +pub fn parse(text: &str) -> Option { + let text = text.trim(); + if text.chars().nth(MAX_CHARS).is_some() { + return None; + } + match text.find('(') { + None => hex(text), + Some(open) => { + // CSS allows no space between a function's name and its `(`. + let name = text.get(..open)?.to_ascii_lowercase(); + let args = text.get(open + 1..)?.strip_suffix(')')?; + if args.contains(['(', ')']) { + return None; + } + match name.as_str() { + "rgb" | "rgba" => rgb(args), + "hsl" | "hsla" => hsl(args), + "oklch" => oklch(args), + _ => None, + } + } + } +} + +/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps. +pub fn hex_of(rgb: [f32; 3]) -> String { + let [r, g, b] = rgb.map(byte); + format!("#{r:02x}{g:02x}{b:02x}") +} + +/// `v` (0 to 1) as one of 256 steps. +fn byte(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// A hex color of 3, 4, 6 or 8 digits, with or without `#`. +fn hex(text: &str) -> Option { + let digits = text.strip_prefix('#').unwrap_or(text); + if !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let nibbles: Vec = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect(); + let values: Vec = match nibbles.len() { + 3 | 4 => nibbles.iter().map(|n| n * 17).collect(), + 6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(), + _ => return None, + }; + let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0); + Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb }) +} + +/// One argument of a color function. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Arg { + Number(f64), + Percent(f64), + /// An angle, in degrees. + Angle(f64), + None, +} + +/// The arguments of a color function, `args` being the text inside its parentheses: the three +/// components and the alpha, if any, and whether they were separated by commas (the legacy form). +fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, bool)> { + let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') { + if !legacy_allowed || args.contains('/') { + return None; + } + let mut parts: Vec<&str> = args.split(',').map(str::trim).collect(); + let alpha = if parts.len() == 4 { parts.pop() } else { None }; + (parts, alpha, true) + } else { + let mut halves = args.split('/'); + let colors = halves.next().unwrap_or_default(); + let alpha = halves.next(); + if halves.next().is_some() { + return None; + } + (colors.split_ascii_whitespace().collect(), alpha.map(str::trim), false) + }; + let [a, b, c] = parts.as_slice() else { return None }; + let one = |s: &str| { + let arg = arg(s)?; + // The legacy form has no `none`. + (!(legacy && arg == Arg::None)).then_some(arg) + }; + let alpha = match alpha { + Some(s) => Some(one(s)?), + None => None, + }; + Some(([one(a)?, one(b)?, one(c)?], alpha, legacy)) +} + +/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no +/// spaces inside it. +fn arg(s: &str) -> Option { + if s.eq_ignore_ascii_case("none") { + return Some(Arg::None); + } + let end = number_end(s)?; + let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?; + let unit = s.get(end..)?.to_ascii_lowercase(); + let arg = match unit.as_str() { + "" => Arg::Number(n), + "%" => Arg::Percent(n), + "deg" => Arg::Angle(n), + "grad" => Arg::Angle(n * 0.9), + "rad" => Arg::Angle(n.to_degrees()), + "turn" => Arg::Angle(n * 360.0), + _ => return None, + }; + match arg { + Arg::Angle(a) if !a.is_finite() => None, + _ => Some(arg), + } +} + +/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an +/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent. +fn number_end(s: &str) -> Option { + let b = s.as_bytes(); + let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count()); + let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-'))); + let whole = digits(i); + i += whole; + let mut fraction = 0; + if b.get(i) == Some(&b'.') { + fraction = digits(i + 1); + if fraction == 0 { + return None; + } + i += 1 + fraction; + } + if whole + fraction == 0 { + return None; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-'))); + let exp = digits(i + 1 + sign); + if exp > 0 { + i += 1 + sign + exp; + } + } + Some(i) +} + +/// The alpha argument from 0 to 1. +fn alpha(a: Option) -> Option> { + let v = match a { + None => return Some(None), + Some(Arg::Number(n)) => n, + Some(Arg::Percent(p)) => p / 100.0, + Some(Arg::None) => 0.0, + Some(Arg::Angle(_)) => return None, + }; + Some(Some(v.clamp(0.0, 1.0) as f32)) +} + +/// A hue argument in degrees from 0 to 360. +fn hue(a: Arg) -> Option { + match a { + Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()), + Arg::None => Some(0.0), + Arg::Percent(_) => None, + } +} + +fn rgb(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count(); + if legacy && percents != 0 && percents != 3 { + return None; + } + let unit = |c: Arg| match c { + Arg::Number(n) => Some(n / 255.0), + Arg::Percent(p) => Some(p / 100.0), + Arg::None => Some(0.0), + Arg::Angle(_) => None, + }; + let [r, g, b] = comps; + let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn hsl(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let [h, s, l] = comps; + let percent = |c: Arg| match c { + Arg::Percent(v) => Some(v), + Arg::Number(v) if !legacy => Some(v), + Arg::None => Some(0.0), + _ => None, + }; + // CSS clamps a negative saturation to 0 and nothing else. + let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0); + // CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside + // 0..=1 is clipped. + let f = |n: f64| { + let k = (n + h / 30.0) % 12.0; + let amount = s * l.min(1.0 - l); + l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + // Huge saturation and lightness values overflow to an infinity or NaN, which is refused. + let rgb = [f(0.0), f(8.0), f(4.0)]; + if rgb.iter().any(|v| !v.is_finite()) { + return None; + } + let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn oklch(args: &str) -> Option { + let (comps, a, _) = split(args, false)?; + let [l, c, h] = comps; + let l = match l { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let c = match c { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0 * CHROMA_FULL, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch }) +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + fn bytes(text: &str) -> ([u8; 3], Option) { + let c = parse(text).unwrap_or_else(|| panic!("{text} should parse")); + (c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8)) + } + + #[test] + fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() { + assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80))); + assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88))); + assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None)); + for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn rgb_reads_the_modern_and_the_legacy_forms() { + assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages"); + assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped"); + assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped"); + assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0))); + for bad in [ + "rgb(51, 102%, 153)", + "rgb(51, 102, none)", + "rgb(51 102)", + "rgb(51 102 153 0.5)", + "rgb(51, 102 153)", + "rgb(51, 102, 153 / 0.5)", + "rgb(51 102 153 / 0.5 / 1)", + "rgb(51 102 153deg)", + "rgb(1. 2 3)", + "rgb(1e999 0 0)", + "rgb(51 102 153", + "rgb(51 102 153))", + "rgb(51 102 153) x", + "rgb(calc(1) 2 3)", + "rgb(,,)", + "rgb (1 2 3)", + "rgb()", + "rgbx(1 2 3)", + ] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn hsl_reads_hues_in_every_angle_unit() { + assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None)); + assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64))); + assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized"); + assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0"); + assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped"); + assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None)); + assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None)); + for bad in + ["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"] + { + assert_eq!(parse(bad), None, "{bad:?}"); + } + // Saturation and lightness this large overflow to an infinity or NaN. + for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn oklch_converts_through_srgb_and_has_no_legacy_form() { + let c = parse("oklch(62.8% 0.2577 29.23)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch)); + let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5))); + assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255])); + assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped"); + let wide = parse("oklch(0.7 0.4 150)").unwrap(); + assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb); + let huge = parse("oklch(0.5 1e308 30)").unwrap(); + assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb); + for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn text_longer_than_the_limit_is_refused() { + let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15)); + assert_eq!(at_limit.chars().count(), MAX_CHARS); + assert!(parse(&at_limit).is_some()); + let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14)); + assert_eq!(parse(&over), None); + assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted"); + assert_eq!(parse(&"(".repeat(100_000)), None); + } + + #[test] + fn hex_of_rounds_each_component() { + assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699"); + assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); + } + + proptest! { + #[test] + fn random_text_never_panics(text in "\\PC{0,60}") { + // `contains` is false for NaN, so these also check that every channel is finite. + if let Some(c) = parse(&text) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a))); + } + } + + #[test] + fn function_shaped_text_never_panics( + name in "(rgb|rgba|hsl|hsla|oklch|RGB)", + args in "[-+0-9.eE%a-z ,/]{0,40}", + ) { + if let Some(c) = parse(&format!("{name}({args})")) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + } + } + + #[test] + fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) { + let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap(); + prop_assert_eq!(c.rgb.map(byte), [r, g, b]); + prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); + prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); + } + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 846dadb940..7c9b3a37e8 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -6,6 +6,7 @@ pub mod blend; pub mod cms; +pub mod css; pub mod freeform; pub mod gradient; pub mod harmony; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a9dee00af3..a68eca7e5c 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::cms::Model; +use vectorcraft_color::css; use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation}; use vectorcraft_color::{Color, Paint, keep_model}; use vectorcraft_doc::live::lerp_color; @@ -135,9 +136,33 @@ pub fn specs() -> Vec { always, harmony ), + cmd!( + query "color.parse", + "Parse Color", + [], + None, + "{text: a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa; the # may be left out) or a CSS color: rgb() or rgba(), hsl() or hsla() (space-separated with an optional / alpha, or the comma-separated legacy form), or oklch(), as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch); at most 48 characters, spaces around it not counted} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; any other text is an error, and so is oklch() while the working RGB space is not sRGB", + always, + parse_color + ), ] } +fn parse_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.parse"; + let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; + let parsed = css::parse(text).ok_or_else(|| { + bad(C, "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters") + })?; + if parsed.space == css::Space::Oklch && !vectorcraft_color::cms::active().rgb_is_srgb() { + return Err(bad(C, "OKLCH needs sRGB as the working RGB space")); + } + let [r, g, b] = parsed.rgb; + // As paint.proxies answers an opacity: a percentage to two places. + let opacity = parsed.alpha.map(|a| (f64::from(a) * 10_000.0).round() / 100.0); + Ok(json!({ "color": Color::rgb(r, g, b), "hex": css::hex_of(parsed.rgb), "opacity": opacity })) +} + /// The RGB inverse of `c`, expressed in `c`'s colour model. pub(crate) fn invert(c: Color) -> Color { c.invert_keep_model() diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c7c23e15c1..ff5734a4f6 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -142,6 +142,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.convert", "color.gamutCheck", "color.harmony", + "color.parse", "color.plates", "dataset.capture", "dataset.delete", diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 811b2e09af..2c76f2b0b6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -348,6 +348,48 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() { assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); } +/// `color.parse` reads each notation into an RGB color, its hex and the alpha as a percentage (null +/// when the text gives none), and answers an error for anything else. +#[test] +fn parse_reads_hex_with_alpha_and_css_colors() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut parse = |text: &str| s.execute("color.parse", &json!({ "text": text })); + for (text, opacity) in [ + ("#33669980", json!(50.2)), + ("33669980", json!(50.2)), + ("#3698", json!(53.33)), + ("#336699", Value::Null), + ("#369", Value::Null), + ("rgb(51 102 153 / 50%)", json!(50.0)), + ("rgba(51, 102, 153, 0.25)", json!(25.0)), + ("rgb(20% 40% 60%)", Value::Null), + ("hsl(210 50% 40%)", Value::Null), + ("hsla(210deg, 50%, 40%, 1)", json!(100.0)), + ] { + let r = parse(text).unwrap(); + assert_eq!(r["hex"], "#336699", "{text}: {r}"); + assert_eq!(r["opacity"], opacity, "{text}: {r}"); + let c: Color = serde_json::from_value(r["color"].clone()).unwrap(); + let Color::Rgb { r: red, g, b } = c else { panic!("{text}: {c:?}") }; + assert_eq!([red, g, b].map(|v| (v * 255.0).round() as u8), [0x33, 0x66, 0x99], "{text}"); + } + let red = parse("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap(); + assert_eq!((&red["hex"], &red["opacity"]), (&json!("#ff0000"), &json!(50.0)), "{red}"); + let message = "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters"; + let long = format!("rgb(1 2 3{})", " ".repeat(40)); + for bad in ["", "#12345", "#gggggg", "rgb(1, 2%, 3)", "rgb(1 2)", "oklch(0.5, 0.1, 30)", "cmyk 0 100 100 0", "red", long.as_str()] { + let e = parse(bad).unwrap_err().to_string(); + assert!(e.ends_with(message), "{bad:?}: {e}"); + } + assert!(parse_err(&mut s, json!({})).ends_with("missing `text`")); + assert!(parse_err(&mut s, json!({"text": 5})).ends_with("`text` must be a string")); +} + +fn parse_err(s: &mut Session, p: Value) -> String { + s.execute("color.parse", &p).unwrap_err().to_string() +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 8ea057cd12..81fc274743 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1031,3 +1031,20 @@ fn color_management_policies_are_checked_and_kept() { next.attach_color_settings(file); assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } + +/// `color.parse` takes `oklch()` only while the working RGB space is sRGB; a hex color still gives +/// its numbers as the document's RGB numbers in another working space. +#[test] +fn color_parse_takes_oklch_only_in_an_srgb_working_space() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let oklch = s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).map_err(|e| e.to_string()); + let hex = s.execute("color.parse", &json!({"text": "#33669980"})).map_err(|e| e.to_string()); + cms::set_active(&old).unwrap(); + assert!(oklch.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{oklch:?}"); + let hex = hex.unwrap(); + assert_eq!((&hex["hex"], &hex["opacity"]), (&json!("#336699"), &json!(50.2))); + assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b661478e0f..20660c672f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -841,6 +841,11 @@ fn structured_junk() { ("node.move", json!({"id": 1, "parent": null, "index": 1000})), ("layer.setProps", json!({"id": 1, "color": 1000})), ("layer.newSublayer", json!({"parent": 2})), + ("color.parse", json!({"text": "rgb(1e308 -1e308 1e-400 / 1e308)"})), + ("color.parse", json!({"text": "hsl(1e308turn 1e308% -1e308%)"})), + ("color.parse", json!({"text": "oklch(1e308 1e308 -1e308rad / -1)"})), + ("color.parse", json!({"text": "#\u{1F600}\u{0}\u{FFFF}"})), + ("color.parse", json!({"text": "rgb(((((((((((("})), ("text.create", json!({"x": 0, "y": 0, "text": "\u{0}\u{FFFF}\u{1F600}", "size": -1})), ("text.create", json!({"x": 0, "y": 0, "text": "a", "size": 1e308, "area": {"width": -1, "height": 0}})), ("text.setStyle", json!({"size": 0, "leading": -1, "tracking": 1e308})), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 40fb92d958..d456e8282f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1384,7 +1384,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 6b1cd1de3a..8d6a2c626f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2357,6 +2357,9 @@ font-technology Variable Променливи Only Web Colors Само уеб цветове Opacity Непрозрачност Show Opacity Показване на непрозрачността + Show Hex Field Показване на шестнадесетичното поле + Hex or CSS color Шестнадесетичен или CSS цвят + Parse Color Разчитане на цвят Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност @@ -4351,6 +4354,7 @@ axis Both И двете @msg `color` must be a colour `color` трябва да бъде цвят @msg `sliders` must be none or oklch `sliders` трябва да бъде none или oklch @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` трябва да бъде шестнадесетичен цвят (#rgb, #rgba, #rrggbb или #rrggbbaa) или CSS цвят rgb(), hsl() или oklch() с най-много 48 знака @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f7a338ceea..0120f0ce67 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -463,6 +463,9 @@ Fill Color Boja ispune Opacity Neprozirnost Show Opacity Prikaži neprozirnost + Show Hex Field Prikaži hex polje + Hex or CSS color Hex ili CSS boja + Parse Color Raščlani boju Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza @@ -4768,6 +4771,7 @@ imageTrace Outline Obris @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `sliders` must be none or oklch `sliders` mora biti none ili oklch @msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` mora biti hex boja (#rgb, #rgba, #rrggbb ili #rrggbbaa) ili CSS boja rgb(), hsl() ili oklch() od najviše 48 znakova @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a6c418346c..630106a28c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3003,6 +3003,9 @@ digits Malayalam Malaiàlam Only Web Colors Només colors web Opacity Opacitat Show Opacity Mostra l’opacitat + Show Hex Field Mostra el camp hex + Hex or CSS color Color hex o CSS + Parse Color Analitza el color Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió Opacity Mask Màscara d’opacitat Opacity Mask Info Informació de la màscara d’opacitat @@ -5452,6 +5455,7 @@ digits Malayalam Malaiàlam @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` ha de ser none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` ha de ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() o oklch() de 48 caràcters com a màxim @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8aa93b2912..f1203e3730 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -476,6 +476,9 @@ Fill Color Barva výplně Opacity Krytí Show Opacity Zobrazit krytí + Show Hex Field Zobrazit pole hex + Hex or CSS color Barva hex nebo CSS + Parse Color Analyzovat barvu Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -5027,6 +5030,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `sliders` must be none or oklch `sliders` musí být none nebo oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musí být barva hex (#rgb, #rgba, #rrggbb nebo #rrggbbaa) nebo barva CSS rgb(), hsl() nebo oklch() o nejvýše 48 znacích @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 60b81cd0b5..9e005f7f9b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3108,6 +3108,9 @@ liquify-list-end {0}, {1} {0} og {1} Fill Color Fyldfarve Opacity Opacitet Show Opacity Vis opacitet + Show Hex Field Vis hex-felt + Hex or CSS color Hex- eller CSS-farve + Parse Color Fortolk farve Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient @@ -8485,6 +8488,7 @@ mark-style Japanese Japansk @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` skal være none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` skal være en hex-farve (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-farve rgb(), hsl() eller oklch() på højst 48 tegn @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5d86acf7cf..82348d4849 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2395,6 +2395,9 @@ file-filter Templates Vorlagen Only Web Colors Nur Webfarben Opacity Deckkraft Show Opacity Deckkraft einblenden + Show Hex Field Hex-Feld einblenden + Hex or CSS color Hex- oder CSS-Farbe + Parse Color Farbe auswerten Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -4630,6 +4633,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `sliders` must be none or oklch `sliders` muss none oder oklch sein @msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` muss eine Hex-Farbe (#rgb, #rgba, #rrggbb oder #rrggbbaa) oder eine CSS-Farbe rgb(), hsl() oder oklch() mit höchstens 48 Zeichen sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 200133e4d6..40127f1383 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1975,6 +1975,9 @@ font-technology Variable Μεταβλητές Only Web Colors Μόνο χρώματα ιστού Opacity Αδιαφάνεια Show Opacity Εμφάνιση αδιαφάνειας + Show Hex Field Εμφάνιση πεδίου Hex + Hex or CSS color Χρώμα Hex ή CSS + Parse Color Ανάλυση χρώματος Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -6352,6 +6355,7 @@ effect Points Σημεία @msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `sliders` must be none or oklch Το `sliders` πρέπει να είναι none ή oklch @msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters Το `text` πρέπει να είναι χρώμα Hex (#rgb, #rgba, #rrggbb ή #rrggbbaa) ή χρώμα CSS rgb(), hsl() ή oklch() με έως 48 χαρακτήρες @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6a4d3f7218..0de22b4365 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2436,6 +2436,9 @@ font-technology Variable Variables Only Web Colors Solo colores web Opacity Opacidad Show Opacity Mostrar opacidad + Show Hex Field Mostrar campo hex + Hex or CSS color Color hex o CSS + Parse Color Analizar color Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión Opacity Mask Máscara de opacidad Opacity Mask Info Información de máscara de opacidad @@ -4732,6 +4735,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` debe ser none u oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` debe ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() u oklch() de 48 caracteres como máximo @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ccbd667cb5..2278d0a26f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -473,6 +473,9 @@ Fill Color Täyttöväri Opacity Peittävyys Show Opacity Näytä peittävyys + Show Hex Field Näytä heksakenttä + Hex or CSS color Heksa- tai CSS-väri + Parse Color Jäsennä väri Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -6362,6 +6365,7 @@ mark-style Japanese Japanilainen @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `sliders` must be none or oklch `sliders` on oltava none tai oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` on oltava heksaväri (#rgb, #rgba, #rrggbb tai #rrggbbaa) tai CSS-väri rgb(), hsl() tai oklch(), enintään 48 merkkiä @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 93c5965f9c..932b8ebe52 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2428,6 +2428,9 @@ font-technology Variable Variables Only Web Colors Couleurs Web uniquement Opacity Opacité Show Opacity Afficher l’opacité + Show Hex Field Afficher le champ hex + Hex or CSS color Couleur hex ou CSS + Parse Color Analyser la couleur Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage Opacity Mask Masque d’opacité Opacity Mask Info Infos sur le masque d’opacité @@ -4698,6 +4701,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` doit valoir none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` doit être une couleur hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou une couleur CSS rgb(), hsl() ou oklch() d’au plus 48 caractères @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f1d0066137..3b492b1cb0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2470,6 +2470,9 @@ Only Web Colors માત્ર વેબ રંગો Opacity અપારદર્શકતા Show Opacity અપારદર્શકતા બતાવો + Show Hex Field Hex ફીલ્ડ બતાવો + Hex or CSS color Hex અથવા CSS રંગ + Parse Color રંગ પાર્સ કરો Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 11a177f04f..7186778d0e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3277,6 +3277,9 @@ antiAlias Sharp शार्प Only Web Colors केवल वेब रंग Opacity ओपेसिटी Show Opacity ओपेसिटी दिखाएँ + Show Hex Field हेक्स फ़ील्ड दिखाएँ + Hex or CSS color हेक्स या CSS रंग + Parse Color रंग पार्स करें Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -6353,6 +6356,7 @@ antiAlias Sharp शार्प @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `sliders` must be none or oklch `sliders` none या oklch होना चाहिए @msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` एक हेक्स रंग (#rgb, #rgba, #rrggbb या #rrggbbaa) या अधिकतम 48 वर्णों का CSS rgb(), hsl() या oklch() रंग होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9b3584c128..1a8a386dbc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2915,6 +2915,9 @@ file-filter Templates Sablonok Only Web Colors Csak webes színek Opacity Átlátszatlanság Show Opacity Átlátszatlanság megjelenítése + Show Hex Field Hex mező megjelenítése + Hex or CSS color Hex vagy CSS szín + Parse Color Szín értelmezése Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját Opacity Mask Átlátszósági maszk Opacity Mask Info Átlátszósági maszk adatai @@ -5094,6 +5097,7 @@ imageTrace Outline Körvonal @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `sliders` must be none or oklch A `sliders` értéke none vagy oklch lehet @msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`: hex szín (#rgb, #rgba, #rrggbb vagy #rrggbbaa) vagy legfeljebb 48 karakteres CSS rgb(), hsl() vagy oklch() szín kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4c1b4916a2..0f274ff3aa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -431,6 +431,9 @@ Fill Color Warna isian Opacity Opasitas Show Opacity Tampilkan opasitas + Show Hex Field Tampilkan bidang hex + Hex or CSS color Warna hex atau CSS + Parse Color Urai warna Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke @@ -5752,6 +5755,7 @@ mark-style Japanese Jepang @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg `sliders` must be none or oklch `sliders` harus none atau oklch @msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` harus berupa warna hex (#rgb, #rgba, #rrggbb, atau #rrggbbaa) atau warna CSS rgb(), hsl(), atau oklch() dengan paling banyak 48 karakter @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c5774cd357..f71698cec5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2472,6 +2472,9 @@ file-filter Templates Modelli Only Web Colors Solo colori web Opacity Opacità Show Opacity Mostra opacità + Show Hex Field Mostra campo hex + Hex or CSS color Colore hex o CSS + Parse Color Analizza colore Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura Opacity Mask Maschera di opacità Opacity Mask Info Informazioni maschera di opacità @@ -4760,6 +4763,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` deve essere none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve essere un colore hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un colore CSS rgb(), hsl() o oklch() di al massimo 48 caratteri @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1b72c056b4..08c223a437 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -519,6 +519,9 @@ digits Malayalam マラヤーラム数字 Make Sides Equal 辺の長さをそろえる Opacity 不透明度 Show Opacity 不透明度を表示 + Show Hex Field 16 進フィールドを表示 + Hex or CSS color 16 進または CSS カラー + Parse Color カラーを解析 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -5176,6 +5179,7 @@ swatch Bright Violet ビビッドバイオレット @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `sliders` must be none or oklch `sliders` は none または oklch でなければなりません @msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` には 16 進カラー (#rgb、#rgba、#rrggbb、#rrggbbaa) または 48 文字以内の CSS の rgb()、hsl()、oklch() カラーを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 450dad2f58..b1af817bf2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2487,6 +2487,9 @@ Fill Color შევსების ფერი Opacity გაუმჭვირვალობა Show Opacity გაუმჭვირვალობის ჩვენება + Show Hex Field Hex ველის ჩვენება + Hex or CSS color Hex ან CSS ფერი + Parse Color ფერის გარჩევა Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -8098,6 +8101,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg `sliders` must be none or oklch `sliders` უნდა იყოს none ან oklch @msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` უნდა იყოს hex ფერი (#rgb, #rgba, #rrggbb ან #rrggbbaa) ან CSS ფერი rgb(), hsl() ან oklch(), არაუმეტეს 48 სიმბოლოსი @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bdf527bc42..be197ef35a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -512,6 +512,9 @@ digits Malayalam 말라얄람어 Make Sides Equal 변 길이 같게 Opacity 불투명도 Show Opacity 불투명도 표시 + Show Hex Field 16진수 필드 표시 + Hex or CSS color 16진수 또는 CSS 색상 + Parse Color 색상 구문 분석 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -5103,6 +5106,7 @@ theme Appearance 외관 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `sliders` must be none or oklch `sliders`는 none 또는 oklch여야 합니다 @msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`은(는) 16진수 색상(#rgb, #rgba, #rrggbb 또는 #rrggbbaa)이거나 최대 48자의 CSS rgb(), hsl() 또는 oklch() 색상이어야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4e7d0ffe9a..64ec429108 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1002,6 +1002,9 @@ liquify-list-end {0}, {1} {0} en {1} Fill Color Vulkleur Opacity Dekking Show Opacity Dekking tonen + Show Hex Field Hexveld tonen + Hex or CSS color Hex- of CSS-kleur + Parse Color Kleur ontleden Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop @@ -8262,6 +8265,7 @@ mark-style Japanese Japans @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg `sliders` must be none or oklch `sliders` moet none of oklch zijn @msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` moet een hexkleur (#rgb, #rgba, #rrggbb of #rrggbbaa) of een CSS-kleur rgb(), hsl() of oklch() van ten hoogste 48 tekens zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2f2d0758a8..156d2c6aba 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -435,6 +435,9 @@ Fill Color Kolor wypełnienia Opacity Krycie Show Opacity Pokaż krycie + Show Hex Field Pokaż pole hex + Hex or CSS color Kolor hex lub CSS + Parse Color Analizuj kolor Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -4850,6 +4853,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `sliders` must be none or oklch `sliders` musi mieć wartość none lub oklch @msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musi być kolorem hex (#rgb, #rgba, #rrggbb lub #rrggbbaa) albo kolorem CSS rgb(), hsl() lub oklch() o długości najwyżej 48 znaków @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index db5b532050..171f408e4f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1986,6 +1986,9 @@ antiAlias Sharp Nítido Only Web Colors Apenas Cores da Web Opacity Opacidade Show Opacity Mostrar Opacidade + Show Hex Field Mostrar Campo Hex + Hex or CSS color Cor hex ou CSS + Parse Color Interpretar Cor Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento Opacity Mask Máscara de Opacidade Opacity Mask Info Informações da Máscara de Opacidade @@ -6320,6 +6323,7 @@ mark-style Japanese Japonesas @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` deve ser none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve ser uma cor hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou uma cor CSS rgb(), hsl() ou oklch() de no máximo 48 caracteres @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 83a4012318..e49d353f62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2461,6 +2461,9 @@ file-filter Templates Шаблоны Only Web Colors Только web-цвета Opacity Непрозрачность Show Opacity Показать непрозрачность + Show Hex Field Показать поле hex + Hex or CSS color Цвет hex или CSS + Parse Color Разобрать цвет Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -4756,6 +4759,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `sliders` must be none or oklch `sliders` должен быть none или oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` должно быть цветом hex (#rgb, #rgba, #rrggbb или #rrggbbaa) или цветом CSS rgb(), hsl() или oklch() длиной не более 48 символов @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 362ca0a34e..6db42ffbfb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2373,6 +2373,9 @@ font-technology Variable Variabla Only Web Colors Endast webbfärger Opacity Opacitet Show Opacity Visa opacitet + Show Hex Field Visa hexfält + Hex or CSS color Hex- eller CSS-färg + Parse Color Tolka färg Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -6345,6 +6348,7 @@ theme Appearance Utseende @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` måste vara none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` måste vara en hexfärg (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-färg rgb(), hsl() eller oklch() på högst 48 tecken @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 120b30947f..dd3e771a76 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2212,6 +2212,9 @@ font-technology Variable Değişken Only Web Colors Yalnızca Web Renkleri Opacity Opaklık Show Opacity Opaklığı Göster + Show Hex Field Hex Alanını Göster + Hex or CSS color Hex veya CSS rengi + Parse Color Rengi Ayrıştır Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli Opacity Mask Opaklık Maskesi Opacity Mask Info Opaklık Maskesi Bilgisi @@ -4467,6 +4470,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `sliders` must be none or oklch `sliders` none veya oklch olmalıdır @msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` bir hex rengi (#rgb, #rgba, #rrggbb veya #rrggbbaa) ya da en fazla 48 karakterlik bir CSS rgb(), hsl() veya oklch() rengi olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a33e04e9ea..b84fe99f60 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2464,6 +2464,9 @@ file-filter Templates Шаблони Only Web Colors Тільки web-кольору Opacity Непрозорість Show Opacity Показати непрозорість + Show Hex Field Показати поле hex + Hex or CSS color Колір hex або CSS + Parse Color Розібрати колір Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -4744,6 +4747,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `sliders` must be none or oklch `sliders` має бути none або oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` має бути кольором hex (#rgb, #rgba, #rrggbb або #rrggbbaa) або кольором CSS rgb(), hsl() або oklch() довжиною не більше 48 символів @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cd405b95c6..34c0991600 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2736,6 +2736,9 @@ digits Hindi Hindi Only Web Colors Chỉ màu web Opacity Độ mờ Show Opacity Hiện độ mờ + Show Hex Field Hiện trường hex + Hex or CSS color Màu hex hoặc CSS + Parse Color Phân tích màu Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout Opacity Mask Mặt nạ độ mờ Opacity Mask Info Thông tin mặt nạ độ mờ @@ -4754,6 +4757,7 @@ theme Appearance Giao diện @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `sliders` must be none or oklch `sliders` phải là none hoặc oklch @msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` phải là màu hex (#rgb, #rgba, #rrggbb hoặc #rrggbbaa) hoặc màu CSS rgb(), hsl() hoặc oklch() dài tối đa 48 ký tự @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 14b5968bf3..dead5e5573 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2325,6 +2325,9 @@ file-filter Templates 模板 Only Web Colors 仅 Web 颜色 Opacity 不透明度 Show Opacity 显示不透明度 + Show Hex Field 显示十六进制字段 + Hex or CSS color 十六进制或 CSS 颜色 + Parse Color 解析颜色 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -4857,6 +4860,7 @@ imageTrace Outline 轮廓 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必须是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必须是十六进制颜色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超过 48 个字符的 CSS rgb()、hsl() 或 oklch() 颜色 @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6b98dfe118..6152ca7220 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2486,6 +2486,7 @@ file-filter Templates 範本 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必須是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必須是十六進位顏色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超過 48 個字元的 CSS rgb()、hsl() 或 oklch() 顏色 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -3597,6 +3598,9 @@ liquify-list-end {0}, {1} {0}和{1} Only Web Colors 僅限網頁色彩 Opacity 不透明度 Show Opacity 顯示不透明度 + Show Hex Field 顯示十六進位欄位 + Hex or CSS color 十六進位或 CSS 顏色 + Parse Color 剖析顏色 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index b90a7a7301..092efd23f5 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1385,7 +1385,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index acf7ab8865..267834ab4f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -784,6 +784,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_hex; +#[cfg(test)] mod tests_color_wheel_opacity; #[cfg(test)] mod tests_constrain; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 200636ba80..d2f787298b 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -23,6 +23,12 @@ //! by OKLCH lightness, chroma and hue (CSS Color 4: //! ), while the working RGB space is //! sRGB. The choice is kept with the preferences too. +//! +//! Panel menu › Show Hex Field adds a field under the wheel or the box that shows the color's six +//! hex digits, and two more while the opacity that Show Opacity sets is under 100 %. It takes a hex +//! color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (`color.parse`). A +//! typed color is applied in the same way as a pick, and an alpha sets the opacity that Show +//! Opacity sets, whether or not that row shows. Where that row is gray, only the color is applied. use egui::{Color32, Rect, Stroke, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; @@ -33,7 +39,7 @@ use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; -use super::{live_run, pstate, set_pstate}; +use super::{color_json, live_run, pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; use crate::theme::Tokens; @@ -86,6 +92,9 @@ pub struct Settings { /// Show Opacity: the opacity row under the wheel or the box. #[serde(deserialize_with = "deserialize_flag")] pub opacity: bool, + /// Show Hex Field: the field for a hex or CSS color under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub hex_field: bool, #[serde(deserialize_with = "deserialize_sliders")] pub sliders: Sliders, } @@ -147,11 +156,11 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { set(&mut app.ui.color_wheel, p, &cms::active())?; Ok(json!(app.ui.color_wheel)) @@ -160,7 +169,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result<(), String> { - const KEYS: [&str; 4] = ["view", "channel", "opacity", "sliders"]; + const KEYS: [&str; 5] = ["view", "channel", "opacity", "hexField", "sliders"]; match p { Value::Null => {} Value::Object(o) => { @@ -183,6 +192,10 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S None | Some(Value::Null) => {} Some(v) => set.opacity = v.as_bool().ok_or("`opacity` must be true or false")?, } + match p.get("hexField") { + None | Some(Value::Null) => {} + Some(v) => set.hex_field = v.as_bool().ok_or("`hexField` must be true or false")?, + } match p.get("sliders") { None | Some(Value::Null) => {} Some(v) => { @@ -197,8 +210,8 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S Ok(()) } -/// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, and -/// Show Opacity. +/// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, Show +/// Opacity and Show Hex Field. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let set = app.ui.color_wheel.clone(); for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { @@ -229,6 +242,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Show Opacity"), true, set.opacity) { command(app, &json!({ "opacity": !set.opacity })).ok(); } + if menu_item(ui, tl!("Show Hex Field"), true, set.hex_field) { + command(app, &json!({ "hexField": !set.hex_field })).ok(); + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -374,6 +390,81 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo } } +/// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits +/// (`None` when it has nothing to edit): six hex digits of the document's RGB numbers, and two more +/// for an opacity under 100 %. Empty without a solid color. +pub(crate) fn hex_text(color: Option<&Color>, o: Option) -> String { + let Some(c) = color else { return String::new() }; + let mut text = super::color::hex_digits(c); + let alpha = o.map(|o| (o.clamp(0.0, 1.0) * 255.0).round() as u8).filter(|a| *a < 255); + if let Some(a) = alpha { + text.push_str(&format!("{a:02X}")); + } + text +} + +/// Apply `c`, typed into the hex field, to `tgt` in one undo step, as a pick applies a color; the +/// alpha `alpha` (0 to 1) also sets the opacity of what the row of Show Opacity edits, when it has +/// something to edit. +fn apply_typed(app: &mut VectorcraftApp, tgt: &Target, c: Color, alpha: Option) { + let alpha = alpha.filter(|_| shown_opacity(app, tgt).1).map(|a| a.clamp(0.0, 1.0)); + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.set_color(c, None); + if let Some(a) = alpha { + s.opacity = a; + } + } + super::gradient::set_stops_keeping_models(app, &stops, None, Live::Released); + } + Target::Point { index, .. } => { + let mut p = json!({"index": index, "color": color_json(&c), "stroke": !app.session.fill_active, "keepModel": true}); + if let Some(a) = alpha { + p["opacity"] = json!(a); + } + live_run(app, "Color", "paint.freeform.setPoint", p, Live::Released); + } + _ => { + let cmd = super::proxy_cmd(app, false); + let mut p = json!({"color": color_json(&c), "focus": true, "keepModel": true}); + if let Some(a) = alpha { + p["opacity"] = json!(f64::from(a) * 100.0); + } + live_run(app, "Color", cmd, p, Live::Released); + } + } +} + +/// The Show Hex Field row: a `#` and a field as wide as the row. A committed text goes through +/// `color.parse`; a text it refuses shows its error in the status bar and changes nothing. True +/// when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option<&Color>) -> bool { + let (o, live) = shown_opacity(app, tgt); + let shown = hex_text(color, live.then_some(o)); + let mut typed = None; + ui.horizontal(|ui| { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new("#").size(15.0).color(t.text)); + let width = ui.available_width(); + typed = widgets::text_field_named(ui, "color-wheel-hex", Some(tl!("Hex or CSS color")), Some(&shown), width, 1); + }); + let Some(text) = typed else { return false }; + match app.run("color.parse", json!({ "text": text })) { + Ok(r) => { + let Ok(rgb) = serde_json::from_value::(r["color"].clone()) else { return true }; + // The document's RGB numbers, in the model a pick would store them in. + let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + let c = stored_rgb(&cms::active(), rgb, replaced(app, tgt, false).as_ref(), cmyk_doc); + let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32); + apply_typed(app, tgt, c, alpha); + } + Err(e) => app.status(e), + } + true +} + /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; /// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored @@ -445,7 +536,11 @@ pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bo /// [`stored`] for a pick of display sRGB `srgb`. pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { let [r, g, b] = cms.srgb_to_rgb(srgb); - let rgb = Color::rgb(r, g, b); + stored_rgb(cms, Color::rgb(r, g, b), was, cmyk_doc) +} + +/// [`stored`] for the RGB color `rgb` in the working RGB space. +fn stored_rgb(cms: &Cms, rgb: Color, was: Option<&Color>, cmyk_doc: bool) -> Color { let cmyk = || { let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); Color::cmyk(c, m, y, k) @@ -631,17 +726,31 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let owner = color.map(|c| Owner::of(app, &tgt, c)); opacity_row(app, ui, &tgt, &shown); // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the - // HSB picked last stays with the new gradient. - if let (Some(c), Some(was)) = (color, owner) - && let Some((remembered, rgb, hsb)) = pstate::>(ui.ctx(), MEMORY) - && remembered == was - { + // HSB and the OKLCH picked last stay with the new gradient. + if let (Some(c), Some(was)) = (color, owner) { let now = Owner::of(app, &tgt, c); if now != was { - set_pstate(ui.ctx(), MEMORY, Some((now, rgb, hsb))); + if let Some((remembered, rgb, hsb)) = pstate::>(ui.ctx(), MEMORY) + && remembered == was + { + set_pstate(ui.ctx(), MEMORY, Some((now.clone(), rgb, hsb))); + } + if let Some((remembered, rgb, lch)) = pstate::>(ui.ctx(), OKLCH_MEMORY) + && remembered == was + { + set_pstate(ui.ctx(), OKLCH_MEMORY, Some((now, rgb, lch))); + } } } } + if app.ui.color_wheel.hex_field { + ui.add_space(4.0); + // A pick or an OKLCH edit read in the frame that commits a text was made on the color + // before the text, so it is not applied. + if hex_row(app, ui, &tgt, color.as_ref()) { + return; + } + } let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); if let Some((lch, phase)) = picked_lch { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 7fdfe00862..e742e25d84 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -841,7 +841,7 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap_err(), "`sliders` must be none or oklch"); let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); - assert_eq!(got, json!({"view": "box", "channel": "red", "opacity": false, "sliders": "oklch"})); + assert_eq!(got, json!({"view": "box", "channel": "red", "opacity": false, "hexField": false, "sliders": "oklch"})); let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hsl"})).unwrap_err(); assert_eq!(e, "`sliders` must be none or oklch"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 95459c922e..a17bbc5be2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,11 +167,15 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "opacity": false, "sliders": "none"})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "opacity": false, "sliders": "none"})); + let defaults = json!({"view": "wheel", "channel": "hue", "opacity": false, "hexField": false, "sliders": "none"}); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), defaults); + assert_eq!( + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), + json!({"view": "box", "channel": "hue", "opacity": false, "hexField": false, "sliders": "none"}) + ); assert_eq!( app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), - json!({"view": "box", "channel": "green", "opacity": false, "sliders": "none"}) + json!({"view": "box", "channel": "green", "opacity": false, "hexField": false, "sliders": "none"}) ); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); @@ -179,7 +183,7 @@ fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing"); let ui = crate::control::inspect(&app, &egui::Context::default()); - assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "opacity": false, "sliders": "none"})); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "opacity": false, "hexField": false, "sliders": "none"})); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -214,9 +218,9 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, opacity, sliders"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, opacity, hexField, sliders"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, opacity, sliders"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, opacity, hexField, sliders"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs new file mode 100644 index 0000000000..ce4a1afbe6 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -0,0 +1,329 @@ +//! The Color Wheel panel's Show Hex Field drawn headless: the setting and `ui.colorWheel`, hex +//! with an alpha and CSS colors typed into the field, the opacity they set, nothing selected, a +//! selection mixing type and other art, gradient stops and freeform points, and refused text. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_engine::Session; + +use super::color_wheel::{hex_text, show}; +use crate::VectorcraftApp; + +/// An app with a selected red rectangle and Show Hex Field checked. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("ui.colorWheel", json!({"hexField": true})).unwrap(); + app +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// Types `text` over the field's text and presses Enter. +fn type_in(h: &mut Harness<'static, VectorcraftApp>, text: &str) { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text(text); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); +} + +fn shown(h: &Harness<'static, VectorcraftApp>) -> String { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").value().unwrap_or_default() +} + +fn rgb8(c: &Color) -> [u8; 3] { + let Color::Rgb { r, g, b } = *c else { panic!("an RGB color: {c:?}") }; + [r, g, b].map(|v| (v * 255.0).round() as u8) +} + +fn fill_color(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> Color { + app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().expect("a solid fill") +} + +fn selected(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().selection.objects.clone() +} + +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// The panel menu's Show Hex Field and `ui.colorWheel {hexField}` check and uncheck the field; a bad +/// value is an error and changes nothing. +#[test] +fn show_hex_field_is_a_setting_of_the_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["hexField"], json!(false)); + assert_eq!(app.run("ui.colorWheel", json!({"hexField": true})).unwrap()["hexField"], json!(true)); + let e = app.run("ui.colorWheel", json!({"hexField": "yes"})).unwrap_err(); + assert_eq!(e, "`hexField` must be true or false"); + assert!(app.ui.color_wheel.hex_field, "an error changes nothing"); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["hexField"], json!(true)); + let saved: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": true, "view": "box"})).unwrap(); + assert!(saved.hex_field); + let odd: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": "on"})).unwrap(); + assert!(!odd.hex_field, "a saved value this build does not know reads as off"); + let h = harness({ + let mut app = self::app(); + app.run("ui.colorWheel", json!({"hexField": false})).unwrap(); + app + }); + assert!(h.query_by_role_and_label(Role::TextInput, "Hex or CSS color").is_none(), "no field while unchecked"); +} + +/// The field shows six digits, and two more while the opacity is under 100 %. +#[test] +fn the_field_shows_the_alpha_only_under_full_opacity() { + let h = harness(app()); + assert_eq!(shown(&h), "FF0000"); + let mut app = app(); + app.run("paint.setFill", json!({"opacity": 50})).unwrap(); + let h = harness(app); + assert_eq!(shown(&h), "FF000080"); + assert_eq!(hex_text(None, Some(0.5)), ""); + assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), Some(0.999)), "336699", "an opacity that rounds to ff shows no alpha"); + assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), None), "336699"); +} + +/// With Show Opacity on, typing `#33669980` sets the fill to #336699 at 50.2 % (128 of 255) in one +/// undo step. +#[test] +fn typing_hex_with_an_alpha_sets_the_color_and_the_opacity() { + let mut app = app(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let id = selected(&app)[0]; + let before = undo_count(&app); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [0x33, 0x66, 0x99]); + let o = h.state().session.proxy_opacity(false).unwrap(); + assert!((o - 0.502).abs() < 1e-4, "{o}"); + assert_eq!(undo_count(h.state()), before + 1, "one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// A typed color keeps the model of the color it replaces, as a pick on the wheel does: a CMYK fill +/// stays CMYK, converted through the color settings. +#[test] +fn a_typed_color_keeps_a_cmyk_fill_cmyk() { + let mut app = app(); + app.run("paint.setFill", json!({"color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap(); + let id = selected(&app)[0]; + let mut h = harness(app); + type_in(&mut h, "#336699"); + let cms = vectorcraft_color::cms::active(); + let want = cms.to_cmyk(&Color::rgb8(0x33, 0x66, 0x99), cms.settings().intent); + let Color::Cmyk { c, m, y, k } = fill_color(h.state(), id) else { panic!("a CMYK color: {:?}", fill_color(h.state(), id)) }; + assert_eq!([c, m, y, k], want); +} + +/// The alpha sets the opacity while the opacity row is hidden too, and text without an alpha keeps +/// the opacity. +#[test] +fn the_alpha_applies_without_the_opacity_row_and_no_alpha_keeps_the_opacity() { + let app = app(); + let id = selected(&app)[0]; + let mut h = harness(app); + type_in(&mut h, "rgb(51 102 153 / 25%)"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [51, 102, 153]); + assert_eq!(h.state().session.proxy_opacity(false), Some(0.25)); + type_in(&mut h, "hsl(0 100% 50%)"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + assert_eq!(h.state().session.proxy_opacity(false), Some(0.25), "no alpha in the text: the opacity stays"); + type_in(&mut h, "oklch(62.8% 0.2577 29.23 / 1)"); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// With nothing selected, `#33669980` sets the default fill to #336699 and changes no opacity. +#[test] +fn with_nothing_selected_the_color_goes_to_the_defaults_without_the_alpha() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + assert_eq!(h.state().session.paint.fill.color().map(|c| rgb8(&c)), Some([0x33, 0x66, 0x99])); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "no object changed"); +} + +/// With a rectangle and a type object with no fill item selected, `#33669980` sets both fills to +/// #336699 and the rectangle's fill opacity to 50.2 %. +#[test] +fn a_selection_mixing_type_and_art_takes_the_color_and_the_alpha_where_it_can() { + let mut app = app(); + let rect = selected(&app)[0]; + let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [rect.0, text]})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let app = h.state(); + assert_eq!(rgb8(&fill_color(app, rect)), [0x33, 0x66, 0x99]); + let fill = app.session.doc().unwrap().doc.node(rect).unwrap().appearance.fill_at(None).map(|f| f.opacity); + assert!(fill.is_some_and(|o| (o - 0.502).abs() < 1e-4), "{fill:?}"); + let text_node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone(); + assert!(text_node.fill_at(None).is_none(), "the type object takes no fill item, so no alpha: {text_node:?}"); + h.state_mut().run("select.set", json!({"ids": [text]})).unwrap(); + let (fill, _) = h.state().session.proxy_paints(); + assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the type's characters take the color: {fill:?}"); +} + +/// Retyping the color and opacity the selection has, in another form, records no undo step; an +/// alpha that differs from the opacity by less than the field shows is still applied. +#[test] +fn retyping_the_shown_color_in_another_form_changes_nothing() { + let mut app = app(); + app.run("paint.setFill", json!({"opacity": 50})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + for same in ["rgb(255 0 0 / 50%)", "rgb(100% 0% 0% / 0.5)", "#f00", "hsl(0 100% 50%)"] { + type_in(&mut h, same); + assert_eq!(undo_count(h.state()), before, "{same}"); + assert!(h.state().ui.status.is_empty(), "{same}: {}", h.state().ui.status); + } + type_in(&mut h, "#00ff00"); + assert_eq!(undo_count(h.state()), before + 1, "another color is applied"); + h.state_mut().run("paint.setFill", json!({"opacity": 99.9})).unwrap(); + h.run_steps(2); + assert_eq!(shown(&h), "00FF00", "99.9 % shows no alpha"); + let before = undo_count(h.state()); + type_in(&mut h, "#00ff00ff"); + assert_eq!(undo_count(h.state()), before + 1, "the alpha ff sets 100 %"); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// Retyping a gradient stop's or a freeform point's color, with or without its alpha, records no +/// step. +#[test] +fn retyping_a_stop_color_changes_nothing() { + for gradient in [json!({}), json!({"kind": "freeform"})] { + let mut app = app(); + app.run("paint.setFill", json!({ "gradient": gradient })).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let before = undo_count(h.state()); + type_in(&mut h, "#33669980"); + type_in(&mut h, "#369"); + assert_eq!(undo_count(h.state()), before, "{gradient}"); + } +} + +/// Retyping the color of a global swatch's tint unlinks the fill from the swatch in one step. +#[test] +fn retyping_a_tint_color_unlinks_the_swatch() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": "#ff0000", "spot": true})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Ink", "tint": 100})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + assert_eq!(shown(&h), "FF0000"); + type_in(&mut h, "#ff0000"); + assert_eq!(undo_count(h.state()), before + 1); + let Paint::Solid { swatch, .. } = crate::panels::current_paints(h.state()).0 else { panic!("a solid fill") }; + assert_eq!(swatch, None); +} + +/// A click on the wheel that takes the focus from an edited field applies the text, then the +/// click's pick to the target the text left: a gradient stop keeps the typed alpha. +#[test] +fn a_wheel_click_after_typing_applies_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text("#33669980"); + h.run_steps(1); + h.get_by_label("Saturation and brightness").click(); + h.run_steps(2); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {}", stop.opacity); + let hex = stop.color.to_hex(); + assert_ne!(hex, "#336699", "the click picked a color"); + let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap(); + assert!(ch(5) >= ch(3) && ch(3) >= ch(1), "the pick keeps the typed hue: {hex}"); + assert_eq!(undo_count(h.state()), before + 2); +} + +/// A selected gradient stop takes the color and the alpha in one step. +#[test] +fn a_gradient_stop_takes_the_color_and_the_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert_eq!(stop.color.to_hex(), "#336699"); + assert!((stop.opacity - 0.502).abs() < 1e-4, "{}", stop.opacity); +} + +/// A selected freeform point takes the color and the alpha. +#[test] +fn a_freeform_point_takes_the_color_and_the_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {"kind": "freeform"}})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let f = super::gradient::shown_points(&g); + assert_eq!(f.points[0].color.to_hex(), "#336699"); + assert!((f.points[0].opacity - 0.502).abs() < 1e-4, "{}", f.points[0].opacity); +} + +/// Text `color.parse` refuses changes nothing and shows its error in the status bar. +#[test] +fn refused_text_changes_nothing_and_says_why() { + let app = app(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + for bad in ["#12345", "rgb(1, 2%, 3)", "not a color", "cmyk(0 0 0 0)"] { + type_in(&mut h, bad); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "{bad}"); + assert!(h.state().ui.status.contains("must be a hex color"), "{bad}: {}", h.state().ui.status); + } + assert_eq!(shown(&h), "FF0000", "the field shows the color again"); + h.state_mut().ui.status.clear(); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.key_press(egui::Key::Backspace); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "an emptied field"); + assert!(h.state().ui.status.contains("must be a hex color"), "an emptied field: {}", h.state().ui.status); +} + +/// The Color panel's hex field still takes only 3 or 6 digits. +#[test] +fn the_color_panels_hex_field_still_refuses_an_alpha() { + assert_eq!(super::color::parse_hex("336699").map(|c| c.to_hex()), Some("#336699".into())); + assert_eq!(super::color::parse_hex("33669980"), None); + assert_eq!(super::color::parse_hex("3698"), None); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index b794dc3c54..6f83219b72 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -216,6 +216,39 @@ fn an_opacity_edit_keeps_the_hue_picked_for_a_white_stop() { assert_eq!(ring(&h), Some(120.0), "the ring keeps the hue after the opacity edit"); } +/// The OKLCH hue picked last for a white gradient stop stays on the OKLCH Hue row after the row +/// sets the stop's opacity. +#[test] +fn an_opacity_edit_keeps_the_oklch_hue_picked_for_a_white_stop() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 480.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + let hue_row = |h: &Harness<'static, VectorcraftApp>| { + let node = h.query_all_by_label("Hue").find(|n| n.accesskit_node().role() == Role::Slider).expect("the OKLCH Hue row"); + (node.accesskit_node().locate(), node.accesskit_node().numeric_value()) + }; + let ((target_node, target_tree), _) = hue_row(&h); + let data = Some(ActionData::NumericValue(120.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(2); + assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row shows the hue picked for white"); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); + assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row keeps the hue after the opacity edit"); +} + /// A drag across the slider previews and ends as one undo step named Opacity. #[test] fn a_drag_is_one_undo_step() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 61112e0fa8..d0126ad9c4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,9 +265,10 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?, sliders?}` shows the -wheel or the box (a color field with a channel strip at its right), picks the box's channel, checks or unchecks Show -Opacity (an opacity row under the wheel or the box), and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?, hexField?, sliders?}` +shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, checks or +unchecks Show Opacity (an opacity row under the wheel or the box) and Show Hex Field (a field for a hex or CSS color), +and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ diff --git a/docs/mcp.md b/docs/mcp.md index ec6aba71ea..0ee7ffec55 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -656,13 +656,37 @@ selected gradient stop or the selected freeform point (the first stop or point w hides the row. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Keys left out keep their values. Params that are not an object, another key or a value off the list return an error and change nothing. The command -returns `{view, channel, opacity, sliders}`, and the settings are kept with the preferences. +returns `{view, channel, opacity, hexField, sliders}`, and the settings are kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. `color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB (a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. +`ui.colorWheel {"hexField": true}` checks Show Hex Field, as the panel menu does, and `false` unchecks it. The field +under the wheel or the box shows the color's six hex digits, and two more for the opacity while the opacity that Show +Opacity edits is under 100 %. A text typed into it is read as `color.parse` reads it. The color is applied as a pick +on the wheel is, and an alpha in the text sets the opacity that Show Opacity edits, whether or not that row shows. +Where that row is gray (nothing selected, an object selected in a symbol instance, or a fill or stroke row on type +characters or missing), only the color is applied. Text without an alpha keeps the opacity. Text that gives the +color and opacity already there records no undo step, unless the color is a tint of a global swatch. A text `color.parse` refuses changes nothing, and its +error shows in the status bar. + +`color.parse {"text": "#33669980"}` answers `{"color": {"model": "rgb", …}, "hex": "#336699", "opacity": 50.2}`. +The text is a [hex color](https://www.w3.org/TR/css-color-4/#hex-notation) of 3, 4, 6 or 8 digits, with or without +the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-functions), +[`hsl()` or `hsla()`](https://www.w3.org/TR/css-color-4/#the-hsl-notation) or +[`oklch()`](https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch) color. The functions take the +space-separated form with an optional `/ alpha`, and `rgb()` and `hsl()` also take the comma-separated legacy form. +Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting spaces around it. A hex +color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and +`oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH Sliders lower it; `oklch()` is an error +while the working RGB space is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green +and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH lightness to 0 to 1 and a negative +chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. `opacity` is the alpha +as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other +commands still refuse `#rrggbbaa` and `#rgba`. + In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index debd7721b1..a68ec54023 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1645,7 +1645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more for an opacity under 100 %; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. The item is gray, and `ui.colorWheel` answers an error, while the working RGB space is not sRGB. `color.convert {to: "oklch"}` answers the same L, C and H. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). From b7bef0a3086c11c3ac191b4a65a873e6c6544818 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:20:26 -0800 Subject: [PATCH 003/198] Color Wheel: the hex field keeps an opacity press, and color.parse takes only CSS whitespace - A text committed when a press on the opacity slider takes the focus is applied to the target read again, so it keeps the opacity the press set, and the field compares the text with what it showed before the press, so the text is not dropped. - color.parse takes only spaces, tabs and line breaks around the text and its arguments (https://www.w3.org/TR/css-syntax-3/#whitespace); a no-break or ideographic space makes the text an error. - The texts name the hsl() refusal for saturation and lightness so large that a channel overflows, and say the field shows the alpha when the opacity rounds to less than ff. - color.parse's params text keeps the forms of the text inside parentheses, so every_description_parses reads it as one key. - A test types a color with only a type object selected: the characters take the color and no fill item is added for the alpha. --- crates/color/src/css.rs | 30 ++++++++-- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 37 ++++++++---- .../src/panels/tests_color_wheel_hex.rs | 60 ++++++++++++++++++- docs/control-protocol.md | 3 +- docs/mcp.md | 22 +++---- docs/target-app-parity.md | 2 +- 9 files changed, 124 insertions(+), 36 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 4d699854ce..6fa17e0df1 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -35,12 +35,15 @@ pub struct CssColor { /// The color `text` gives, or `None` when it is not one of the module's forms or has more than /// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green /// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness -/// to 0..=1 and chroma to 0 or more. `none` reads as 0. An `hsl()` color whose red, green or blue -/// falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its +/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it +/// converts a color. Spaces, tabs and line breaks may surround the text and its arguments; other +/// whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or +/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its /// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such -/// colors into the gamut by its own rules instead. +/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness +/// are so large that a channel overflows to an infinity is refused. pub fn parse(text: &str) -> Option { - let text = text.trim(); + let text = css_trim(text); if text.chars().nth(MAX_CHARS).is_some() { return None; } @@ -63,6 +66,12 @@ pub fn parse(text: &str) -> Option { } } +/// `s` without the CSS whitespace (spaces, tabs and line breaks) around it +/// (). +fn css_trim(s: &str) -> &str { + s.trim_matches(|c: char| c.is_ascii_whitespace()) +} + /// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps. pub fn hex_of(rgb: [f32; 3]) -> String { let [r, g, b] = rgb.map(byte); @@ -107,7 +116,7 @@ fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, boo if !legacy_allowed || args.contains('/') { return None; } - let mut parts: Vec<&str> = args.split(',').map(str::trim).collect(); + let mut parts: Vec<&str> = args.split(',').map(css_trim).collect(); let alpha = if parts.len() == 4 { parts.pop() } else { None }; (parts, alpha, true) } else { @@ -117,7 +126,7 @@ fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, boo if halves.next().is_some() { return None; } - (colors.split_ascii_whitespace().collect(), alpha.map(str::trim), false) + (colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false) }; let [a, b, c] = parts.as_slice() else { return None }; let one = |s: &str| { @@ -328,6 +337,15 @@ mod tests { } } + #[test] + fn only_spaces_tabs_and_line_breaks_are_whitespace() { + assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128))); + for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + #[test] fn hsl_reads_hues_in_every_angle_unit() { assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None)); diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a68eca7e5c..071f2ed3f7 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Parse Color", [], None, - "{text: a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa; the # may be left out) or a CSS color: rgb() or rgba(), hsl() or hsla() (space-separated with an optional / alpha, or the comma-separated legacy form), or oklch(), as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch); at most 48 characters, spaces around it not counted} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; any other text is an error, and so is oklch() while the working RGB space is not sRGB", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; at most 48 characters, the spaces, tabs and line breaks around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d456e8282f..a63f637069 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1384,7 +1384,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 092efd23f5..bafb8c61cc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1385,7 +1385,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index d2f787298b..4843c19a63 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -25,10 +25,11 @@ //! sRGB. The choice is kept with the preferences too. //! //! Panel menu › Show Hex Field adds a field under the wheel or the box that shows the color's six -//! hex digits, and two more while the opacity that Show Opacity sets is under 100 %. It takes a hex -//! color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (`color.parse`). A -//! typed color is applied in the same way as a pick, and an alpha sets the opacity that Show -//! Opacity sets, whether or not that row shows. Where that row is gray, only the color is applied. +//! hex digits, and two more when the opacity that Show Opacity sets rounds to less than `ff`. It +//! takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color +//! (`color.parse`). A typed color is applied in the same way as a pick, and an alpha sets the +//! opacity that Show Opacity sets, whether or not that row shows. Where that row is gray, only the +//! color is applied. use egui::{Color32, Rect, Stroke, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; @@ -392,7 +393,7 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo /// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits /// (`None` when it has nothing to edit): six hex digits of the document's RGB numbers, and two more -/// for an opacity under 100 %. Empty without a solid color. +/// when the opacity rounds to less than `ff`. Empty without a solid color. pub(crate) fn hex_text(color: Option<&Color>, o: Option) -> String { let Some(c) = color else { return String::new() }; let mut text = super::color::hex_digits(c); @@ -437,23 +438,30 @@ fn apply_typed(app: &mut VectorcraftApp, tgt: &Target, c: Color, alpha: Option) -> bool { +/// The text the hex field shows for `tgt` and its color, as [`hex_text`] gives it. +fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> String { let (o, live) = shown_opacity(app, tgt); - let shown = hex_text(color, live.then_some(o)); + hex_text(color, live.then_some(o)) +} + +/// The Show Hex Field row: a `#` and a field as wide as the row, showing `shown`. A committed text +/// goes through `color.parse`; a text it refuses shows its error in the status bar and changes +/// nothing. True when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, shown: &str) -> bool { let mut typed = None; ui.horizontal(|ui| { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new("#").size(15.0).color(t.text)); let width = ui.available_width(); - typed = widgets::text_field_named(ui, "color-wheel-hex", Some(tl!("Hex or CSS color")), Some(&shown), width, 1); + typed = widgets::text_field_named(ui, "color-wheel-hex", Some(tl!("Hex or CSS color")), Some(shown), width, 1); }); let Some(text) = typed else { return false }; match app.run("color.parse", json!({ "text": text })) { Ok(r) => { let Ok(rgb) = serde_json::from_value::(r["color"].clone()) else { return true }; + // The target is read again, so a text committed when a press on the opacity row takes + // the focus keeps the opacity that press set. + let tgt = &wheel_target(app, ui); // The document's RGB numbers, in the model a pick would store them in. let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored_rgb(&cms::active(), rgb, replaced(app, tgt, false).as_ref(), cmyk_doc); @@ -721,6 +729,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); picked_lch = oklch_rows(app, ui, &tgt, color, &cms); } + // The hex field compares its text with what it showed before an opacity edit of this frame, so + // a text committed when a press on the opacity row takes the focus is not dropped. + let hex = app.ui.color_wheel.hex_field.then(|| hex_shown(app, &tgt, color.as_ref())); if app.ui.color_wheel.opacity { let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, &tgt, c)); @@ -743,11 +754,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } } - if app.ui.color_wheel.hex_field { + if let Some(hex) = hex { ui.add_space(4.0); // A pick or an OKLCH edit read in the frame that commits a text was made on the color // before the text, so it is not applied. - if hex_row(app, ui, &tgt, color.as_ref()) { + if hex_row(app, ui, &hex) { return; } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index ce4a1afbe6..7518cf6d2d 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -91,7 +91,7 @@ fn show_hex_field_is_a_setting_of_the_panel() { assert!(h.query_by_role_and_label(Role::TextInput, "Hex or CSS color").is_none(), "no field while unchecked"); } -/// The field shows six digits, and two more while the opacity is under 100 %. +/// The field shows six digits, and two more when the opacity rounds to less than `ff`. #[test] fn the_field_shows_the_alpha_only_under_full_opacity() { let h = harness(app()); @@ -189,6 +189,21 @@ fn a_selection_mixing_type_and_art_takes_the_color_and_the_alpha_where_it_can() assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the type's characters take the color: {fill:?}"); } +/// With only a type object selected, where the opacity row is gray, `#33669980` sets the +/// characters' color and adds no fill item for the alpha. +#[test] +fn with_only_type_selected_the_color_applies_without_the_alpha() { + let mut app = app(); + let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [text]})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let (fill, _) = h.state().session.proxy_paints(); + assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the characters take the color: {fill:?}"); + let node = h.state().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone(); + assert!(node.fill_at(None).is_none(), "no fill item for the alpha: {node:?}"); +} + /// Retyping the color and opacity the selection has, in another form, records no undo step; an /// alpha that differs from the opacity by less than the field shows is still applied. #[test] @@ -270,6 +285,49 @@ fn a_wheel_click_after_typing_applies_both() { assert_eq!(undo_count(h.state()), before + 2); } +/// A press on the opacity slider that takes the focus from an edited field applies the text and +/// keeps the opacity the press set: a gradient stop takes both. +#[test] +fn an_opacity_press_after_typing_keeps_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text("#336699"); + h.run_steps(1); + h.get_by_role_and_label(Role::Slider, "Opacity").click(); + h.run_steps(2); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert_eq!(stop.color.to_hex(), "#336699", "the text applies"); + assert!(stop.opacity < 0.9, "the press sets the opacity: {}", stop.opacity); +} + +/// The same for a solid fill: the rectangle takes the typed color and the opacity the press set. +#[test] +fn an_opacity_press_after_typing_keeps_both_on_a_solid_fill() { + let mut app = app(); + let rect = selected(&app)[0]; + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text("#336699"); + h.run_steps(1); + h.get_by_role_and_label(Role::Slider, "Opacity").click(); + h.run_steps(2); + let app = h.state(); + assert_eq!(rgb8(&fill_color(app, rect)), [0x33, 0x66, 0x99], "the text applies"); + let fill = app.session.doc().unwrap().doc.node(rect).unwrap().appearance.fill_at(None).map(|f| f.opacity); + assert!(fill.is_some_and(|o| o < 0.9), "the press sets the opacity: {fill:?}"); +} + /// A selected gradient stop takes the color and the alpha in one step. #[test] fn a_gradient_stop_takes_the_color_and_the_alpha() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d0126ad9c4..cd7811b8c3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -268,8 +268,7 @@ pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint. point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?, hexField?, sliders?}` shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, checks or unchecks Show Opacity (an opacity row under the wheel or the box) and Show Hex Field (a field for a hex or CSS color), -and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error -while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. +and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index 0ee7ffec55..80a887ab68 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -664,13 +664,13 @@ the box), and `"none"` hides them; `"oklch"` is an error while the working RGB s (a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. `ui.colorWheel {"hexField": true}` checks Show Hex Field, as the panel menu does, and `false` unchecks it. The field -under the wheel or the box shows the color's six hex digits, and two more for the opacity while the opacity that Show -Opacity edits is under 100 %. A text typed into it is read as `color.parse` reads it. The color is applied as a pick -on the wheel is, and an alpha in the text sets the opacity that Show Opacity edits, whether or not that row shows. -Where that row is gray (nothing selected, an object selected in a symbol instance, or a fill or stroke row on type -characters or missing), only the color is applied. Text without an alpha keeps the opacity. Text that gives the -color and opacity already there records no undo step, unless the color is a tint of a global swatch. A text `color.parse` refuses changes nothing, and its -error shows in the status bar. +under the wheel or the box shows the color's six hex digits, and two more for the opacity when the opacity that Show +Opacity edits rounds to less than `ff`. A text typed into it is read as `color.parse` reads it. The color is applied +as a pick on the wheel is, and an alpha in the text sets the opacity that Show Opacity edits, whether or not that row +shows. Where that row is gray (nothing selected, an object selected in a symbol instance, or a fill or stroke row on +type characters or missing), only the color is applied. Text without an alpha keeps the opacity. Text that gives the +color and opacity already there records no undo step, unless the color is a tint of a global swatch. When +`color.parse` refuses the text, the field does not change the color and the status bar shows the error. `color.parse {"text": "#33669980"}` answers `{"color": {"model": "rgb", …}, "hex": "#336699", "opacity": 50.2}`. The text is a [hex color](https://www.w3.org/TR/css-color-4/#hex-notation) of 3, 4, 6 or 8 digits, with or without @@ -678,12 +678,14 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f [`hsl()` or `hsla()`](https://www.w3.org/TR/css-color-4/#the-hsl-notation) or [`oklch()`](https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch) color. The functions take the space-separated form with an optional `/ alpha`, and `rgb()` and `hsl()` also take the comma-separated legacy form. -Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting spaces around it. A hex -color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and +Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting +the spaces, tabs and line breaks around it; other whitespace makes the text an error. A hex color, `rgb()` and +`hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and `oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH Sliders lower it; `oklch()` is an error while the working RGB space is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH lightness to 0 to 1 and a negative -chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. `opacity` is the alpha +chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. An `hsl()` color whose +saturation and lightness are so large that a channel overflows to an infinity is an error. `opacity` is the alpha as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a68ec54023..3ea05ecde0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1645,7 +1645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more for an opacity under 100 %; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. The item is gray, and `ui.colorWheel` answers an error, while the working RGB space is not sRGB. `color.convert {to: "oklch"}` answers the same L, C and H. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). From ca3d617531f7b1915657169aab9fb6da0d1196e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:50:05 -0800 Subject: [PATCH 004/198] Color Wheel: a pick in the frame of an opacity edit keeps the stop's opacity The wheel and the OKLCH rows applied a pick to the gradient stops read at the start of the frame, so an opacity edit of a stop in the same frame was written back to its old value. The panel now reads the stops again after the opacity row sets them. --- crates/ui-egui/src/panels/color_wheel.rs | 17 ++++-- .../src/panels/tests_color_wheel_opacity.rs | 55 +++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 4843c19a63..ff6b8a1b4d 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -365,8 +365,9 @@ fn apply_opacity(app: &mut VectorcraftApp, tgt: &Target, o: f32, phase: Live) { } /// The Show Opacity row: the Transparency panel's icon, a slider whose track shows `color` from -/// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. -fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) { +/// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. True when +/// it set the opacity. +fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) -> bool { let (o, live) = shown_opacity(app, tgt); let percent = f64::from(o) * 100.0; let mut edit: Option<(f32, Live)> = None; @@ -386,9 +387,9 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo } }); }); - if let Some((v, phase)) = edit.filter(|_| live) { - apply_opacity(app, tgt, v, phase); - } + let Some((v, phase)) = edit.filter(|_| live) else { return false }; + apply_opacity(app, tgt, v, phase); + true } /// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits @@ -732,10 +733,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The hex field compares its text with what it showed before an opacity edit of this frame, so // a text committed when a press on the opacity row takes the focus is not dropped. let hex = app.ui.color_wheel.hex_field.then(|| hex_shown(app, &tgt, color.as_ref())); + let mut opacity_set = false; if app.ui.color_wheel.opacity { let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, &tgt, c)); - opacity_row(app, ui, &tgt, &shown); + opacity_set = opacity_row(app, ui, &tgt, &shown); // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the // HSB and the OKLCH picked last stay with the new gradient. if let (Some(c), Some(was)) = (color, owner) { @@ -762,6 +764,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } } + // A pick or an OKLCH edit read in the frame of an opacity edit goes to the stops as that edit + // left them, so the stop keeps both. + let tgt = if opacity_set { wheel_target(app, ui) } else { tgt }; let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); if let Some((lch, phase)) = picked_lch { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 6f83219b72..f8d2d5550c 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -249,6 +249,61 @@ fn an_opacity_edit_keeps_the_oklch_hue_picked_for_a_white_stop() { assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row keeps the hue after the opacity edit"); } +/// Asks screen readers to set the opacity row to `opacity` and `label`'s slider to `value` in one +/// frame (`Harness::event` would give each request a frame of its own). +fn set_both(h: &mut Harness<'static, VectorcraftApp>, opacity: f64, (label, value): (&str, f64)) { + let (target_node, target_tree) = h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(opacity)); + let set_opacity = Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }); + let node = h.query_all_by_label(label).find(|n| n.accesskit_node().role() == Role::Slider).expect("the slider"); + let (target_node, target_tree) = node.accesskit_node().locate(); + let data = Some(ActionData::NumericValue(value)); + let set_value = Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }); + h.input_mut().events.extend([set_opacity, set_value]); + h.run_steps(2); +} + +/// A gradient stop with stops red and blue, the first selected. +fn stop_app() -> VectorcraftApp { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + app +} + +/// An opacity edit and a pick on the ring in one frame: the stop keeps both. +#[test] +fn an_opacity_edit_and_a_ring_pick_in_one_frame_keep_both() { + let mut h = harness(stop_app()); + set_both(&mut h, 30.0, ("Hue ring", 120.0)); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.3).abs() < 1e-6, "the stop keeps the opacity: {:?}", g.gradient.stops); + assert_ne!(super::color::hex_digits(&stop.color), "FF0000", "the stop takes the pick: {:?}", g.gradient.stops); +} + +/// An opacity edit and an OKLCH Hue edit in one frame: the stop keeps both. +#[test] +fn an_opacity_edit_and_an_oklch_edit_in_one_frame_keep_both() { + let mut app = stop_app(); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 480.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + set_both(&mut h, 30.0, ("Hue", 140.0)); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.3).abs() < 1e-6, "the stop keeps the opacity: {:?}", g.gradient.stops); + assert_ne!(super::color::hex_digits(&stop.color), "FF0000", "the stop takes the edit: {:?}", g.gradient.stops); +} + /// A drag across the slider previews and ends as one undo step named Opacity. #[test] fn a_drag_is_one_undo_step() { From 0941850e4959933887d58be2b5802a48151aa858 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:06:34 -0800 Subject: [PATCH 005/198] i18n: French row takes a no-break space before the colon --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a160e37f5e..acf19bb533 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6697,7 +6697,7 @@ axis Y Axis Axe Y @msg `opacity` must be a number `opacity` doit être un nombre @msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 @msg `opacity` must be true or false `opacity` doit valoir true ou false -@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect @msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre @msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" From 41ef92cfc0e92d7de51d9023c7c53510cae7402c Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:44:32 +0100 Subject: [PATCH 006/198] Stroke: Notched Arrow arrowhead (#8142) A slender filled head with concave sides and a V-shaped notch in its back, as used in mathematical diagrams, listed after Arrow in the Stroke panel's arrowhead menus and accepted by stroke.set as NotchedArrow. --- crates/doc/src/appearance/stroke_style.rs | 7 ++- crates/doc/src/appearance/tests.rs | 1 + crates/effects/src/stroke/arrow.rs | 5 ++ crates/effects/src/stroke/tests_arrows.rs | 63 +++++++++++++++++-- crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/tests/strokegeom.rs | 15 ++++- .../ui-egui/src/panels/tests_strokedepth.rs | 7 +++ docs/mcp.md | 15 ++--- docs/target-app-parity.md | 5 +- 9 files changed, 103 insertions(+), 17 deletions(-) diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 18b226c676..00eb4c9613 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -172,14 +172,18 @@ pub enum Arrowhead { /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as /// the other heads. LineArrow, + /// A slender filled head, a little over half as wide as it is long, whose sides bend in + /// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams. + NotchedArrow, /// A head the user drew, with its art. Custom(Arc), } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 41] = [ + pub const ALL: [Arrowhead; 42] = [ Arrowhead::Arrow, + Arrowhead::NotchedArrow, Arrowhead::ArrowOpen, Arrowhead::LineArrow, Arrowhead::Barbed, @@ -302,6 +306,7 @@ impl Arrowhead { Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", Arrowhead::LineArrow => "Line Arrow", + Arrowhead::NotchedArrow => "Notched Arrow", Arrowhead::Custom(_) => "Custom", } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index cb5f8fed66..c63c01ce12 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -356,6 +356,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "TriangleBar", "Oval", "LineArrow", + "NotchedArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index d188bcafd6..792cb0c441 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -288,6 +288,8 @@ fn local_stop(kind: &Arrowhead) -> Stop { Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), Arrowhead::HalfCircle => Stop::At(1.0), + // Between the bend in its sides and its notch, where it is wider than the line at 100 %. + Arrowhead::NotchedArrow => Stop::At(2.7), Arrowhead::Concave => Stop::At(2.6), Arrowhead::Hexagon => Stop::At(HEX / 2.0), _ => Stop::At(2.0), @@ -394,6 +396,9 @@ fn local(kind: &Arrowhead) -> BezPath { let t = FRAC_1_SQRT_2; poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); } + // Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at + // 100 %, so the sides are concave; the notch reaches 0.7 into the back. + Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]), Arrowhead::Custom(c) => p = c.path.to_bezpath(), // The first ten are drawn by `shape`. Arrowhead::Triangle diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index a32a70245b..3f2fa18bc9 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -4,20 +4,26 @@ use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer}; -use super::stroke_pieces; +use super::{line_outline, stroke_pieces}; /// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads /// of weight 2, so 8 long and 8 wide. fn head(kind: Arrowhead) -> super::Arrow { + head_and_line(kind, LineCap::Butt).0 +} + +/// [`head`] and the outline of the line under it, drawn with `cap`. +fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); - st.end_arrow = Some(kind); - st.arrow_align = ArrowAlign::Tip; + (st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap); let mut l = BezPath::new(); l.move_to((0.0, 0.0)); l.line_to((100.0, 0.0)); - stroke_pieces(&l, &st).heads.remove(0) + let mut p = stroke_pieces(&l, &st); + let line = line_outline(&p.line, &st, st.width, 1e-3); + (p.heads.remove(0), line) } /// The outline's closed contours as polygons (curves flattened). @@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { } } +#[test] +fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::NotchedArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // Six corners: the tip, a bend in each side, a barb on each side and the notch between them. + let pts: Vec = contours(&h.outline).concat(); + let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y)); + assert_eq!(pts.len(), corners.len(), "{pts:?}"); + for c in corners { + assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}"); + } + for side in [1.0, -1.0] { + // Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside. + assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}"); + // Slender: 2.4 units across at the barbs, not the 4 of the other arrows. + assert_eq!(h.outline.winding(at(3.9, side * 1.3)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(3.9, side * 1.0)), 0, "side {side}"); + } + // Open in the notch, solid in front of it. + assert_eq!(h.outline.winding(at(3.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(3.1, 0.0)), 0); + // The line stops between the bend and the notch, 2.7 units back from the tip. + assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset); +} + +#[test] +fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() { + // With every cap, no part of the 2 pt line between the notch and the tip shows beside the + // head, though the head is barely wider than the line at its bends. + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap); + let mut covered = 0; + for i in 0..=132 { + for j in -25..=25 { + let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04); + if line.winding(p) != 0 { + assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}"); + covered += 1; + } + } + } + assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)"); + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e8fb1349c3..b8a807cd5f 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index 524dabef3e..af3eb52936 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -2,7 +2,7 @@ //! the width-profile presets. use serde_json::json; -use vectorcraft_doc::{ArrowAlign, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer, WidthProfile}; use crate::*; @@ -58,6 +58,19 @@ fn profiles_come_from_the_preset_catalogue() { } } +#[test] +fn the_notched_arrow_survives_the_native_format() { + let (mut s, id) = session_with_line(); + s.execute("stroke.set", &json!({"startArrow": "NotchedArrow", "endArrow": "NotchedArrow"})).unwrap(); + let st = stroke(&s, id); + assert_eq!((st.start_arrow, st.end_arrow), (Some(Arrowhead::NotchedArrow), Some(Arrowhead::NotchedArrow))); + let doc = &s.doc().unwrap().doc; + let text = String::from_utf8(vectorcraft_format::save(doc, true)).unwrap(); + assert_eq!(text.matches("\"NotchedArrow\"").count(), 2, "saved by name"); + let back = vectorcraft_format::load(text.as_bytes()).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke().unwrap(), &stroke(&s, id)); +} + #[test] fn arrow_align_and_profiles_survive_the_native_format() { let (mut s, id) = session_with_line(); diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index 1d80cc1c66..f629fd4de8 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -160,4 +160,11 @@ fn arrowhead_dropdown_offers_the_new_heads() { let t = frame_events(&ctx, &mut app, vec![], stroke::show); click(&ctx, &mut app, text_rect(&t, "Barbed").center(), stroke::show); assert_eq!(current_stroke(&app).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::Barbed)); + // The notched arrow is listed under its name, right after Arrow. + click(&ctx, &mut app, egui::pos2(label.right() + 2.0 * sp + 64.0 + 32.0, label.center().y), stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + let (arrow, notched, open) = (text_rect(&t, "Arrow"), text_rect(&t, "Notched Arrow"), text_rect(&t, "Arrow (open)")); + assert!(arrow.center().y < notched.center().y && notched.center().y < open.center().y, "{arrow:?} {notched:?} {open:?}"); + click(&ctx, &mut app, notched.center(), stroke::show); + assert_eq!(current_stroke(&app).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::NotchedArrow)); } diff --git a/docs/mcp.md b/docs/mcp.md index b6d3cb64ce..46320497d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5586,13 +5586,14 @@ and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` ## Arrowheads -`stroke.set {startArrow, endArrow}` takes any of 41 generated heads by name (the params doc lists them; `null` for -none): arrows (`Arrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, -`Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, `Diamond`, `Hexagon`, `Star`, -the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, `Bracket`, `Fork`, `Cross`, -`Plus`). Each head fits a box about four times its weight long and wide. A head's weight is the stroke weight scaled by -`arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the line's weight at 100 % for lines of -0.25 pt or more) at right angles and spreads twice as wide. +`stroke.set {startArrow, endArrow}` takes any of 42 generated heads by name (the params doc lists them; `null` for +none): arrows (`Arrow`, `NotchedArrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, +`Chevron`, `Feather`, `Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, +`Diamond`, `Hexagon`, `Star`, the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, +`Bracket`, `Fork`, `Cross`, `Plus`). Each head fits a box about four times its weight long and wide. A head's weight +is the stroke weight scaled by `arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the +line's weight at 100 % for lines of 0.25 pt or more) at right angles and spreads twice as wide. `NotchedArrow` is +slender (2.4 weights across at its barbs), its sides bend in halfway back, and it has a V-shaped notch in its back. Custom arrowheads come from the arrowheads file, `Arrowheads.vectorcraft` next to the preferences (none on the web or in runs with `VECTORCRAFT_NO_PREFS`). `stroke.arrowheads.edit` (Stroke panel menu › Edit Arrowheads…) opens it, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e5e7943200..f8bcd1e33e 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-16 · **Change:** minor (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: #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-17 · **Change:** minor (Notched Arrow arrowhead (#8142); 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: #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). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Stroke panel: Notched Arrow, a 42nd generated arrowhead, listed after Arrow: a slender filled head 4 weights long and 2.4 across at its barbs, whose sides bend in halfway back and with a V-shaped notch 0.7 weights deep in its back; the line stops between the bend and the notch, inside the head with any cap (`stroke.set` `NotchedArrow`, #8142); scores and estimates unchanged | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | @@ -1747,7 +1748,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **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. + - **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-two 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 Notched Arrow: slender and filled, its sides bending in halfway back, with a V-shaped notch in its back, #8142), 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, 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). From aed3de0f4fdd7325c7df6400ea7621b184a5fd52 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:54:49 +0100 Subject: [PATCH 007/198] Stroke: the saved-names test lists 42 arrowheads --- crates/doc/src/appearance/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c63c01ce12..e78d6b3227 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -314,7 +314,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 41] = [ + const SAVED: [&str; 42] = [ "Triangle", "TriangleOpen", "Circle", From 90b53130ef20ff8ef14dfc71177013a6024284b8 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:12:41 +0100 Subject: [PATCH 008/198] Stroke: sample inside the notched arrow's barb, past the notch --- crates/effects/src/stroke/tests_arrows.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index 3f2fa18bc9..2a54ddb462 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -128,8 +128,8 @@ fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() { assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}"); assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}"); // Slender: 2.4 units across at the barbs, not the 4 of the other arrows. - assert_eq!(h.outline.winding(at(3.9, side * 1.3)), 0, "side {side}"); - assert_ne!(h.outline.winding(at(3.9, side * 1.0)), 0, "side {side}"); + assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}"); } // Open in the notch, solid in front of it. assert_eq!(h.outline.winding(at(3.5, 0.0)), 0); From fdf4f77a2d547f028be908b2c4f70ad55378597b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:26:01 -0800 Subject: [PATCH 009/198] Color Wheel: a typed hex text stays with the object it was typed for The hex field's id now names the document, the selection, the Type tool's characters, the appearance item, the proxy and the gradient stop or freeform point. A text typed for one object is dropped when another one is targeted, even one showing the same hex, so Enter no longer applies it there. color.parse's docs list form feeds with the whitespace it accepts around the text. --- crates/color/src/css.rs | 13 +++++---- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 21 ++++++++++---- .../src/panels/tests_color_wheel_hex.rs | 29 +++++++++++++++++++ docs/mcp.md | 18 ++++++------ 5 files changed, 62 insertions(+), 21 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 6fa17e0df1..c8b1e84ab2 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -36,8 +36,8 @@ pub struct CssColor { /// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green /// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness /// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it -/// converts a color. Spaces, tabs and line breaks may surround the text and its arguments; other -/// whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or +/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its +/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or /// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its /// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such /// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness @@ -66,8 +66,9 @@ pub fn parse(text: &str) -> Option { } } -/// `s` without the CSS whitespace (spaces, tabs and line breaks) around it -/// (). +/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line +/// breaks) around it (, +/// ). fn css_trim(s: &str) -> &str { s.trim_matches(|c: char| c.is_ascii_whitespace()) } @@ -341,7 +342,9 @@ mod tests { fn only_spaces_tabs_and_line_breaks_are_whitespace() { assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None)); assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128))); - for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)"] { + assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break"); + assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None)); + for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] { assert_eq!(parse(bad), None, "{bad:?}"); } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 071f2ed3f7..8890f9eec9 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Parse Color", [], None, - "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; at most 48 characters, the spaces, tabs and line breaks around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c6872ac689..a0f0584ef2 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -445,16 +445,25 @@ fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> Strin hex_text(color, live.then_some(o)) } -/// The Show Hex Field row: a `#` and a field as wide as the row, showing `shown`. A committed text -/// goes through `color.parse`; a text it refuses shows its error in the status bar and changes -/// nothing. True when a text was committed. -fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, shown: &str) -> bool { +/// The hex field's id for `tgt`: it names the document, the selected objects or text characters, +/// the appearance item, the proxy and the gradient stop or freeform point, but not the color, so a +/// text typed for one of them is dropped when another one is targeted, even one showing the same hex. +fn hex_field_id(app: &VectorcraftApp, tgt: &Target) -> impl std::hash::Hash + use<> { + let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0)); + ("color-wheel-hex", o.doc, o.selection, o.text_selection, o.appearance_item, o.fill, o.slot) +} + +/// The Show Hex Field row for `tgt`: a `#` and a field as wide as the row, showing `shown`. A +/// committed text goes through `color.parse`; a text it refuses shows its error in the status bar +/// and changes nothing. True when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> bool { let mut typed = None; + let id = hex_field_id(app, tgt); ui.horizontal(|ui| { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new("#").size(15.0).color(t.text)); let width = ui.available_width(); - typed = widgets::text_field_named(ui, "color-wheel-hex", Some(tl!("Hex or CSS color")), Some(shown), width, 1); + typed = widgets::text_field_named(ui, id, Some(tl!("Hex or CSS color")), Some(shown), width, 1); }); let Some(text) = typed else { return false }; match app.run("color.parse", json!({ "text": text })) { @@ -760,7 +769,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); // A pick or an OKLCH edit read in the frame that commits a text was made on the color // before the text, so it is not applied. - if hex_row(app, ui, &hex) { + if hex_row(app, ui, &tgt, &hex) { return; } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index 7518cf6d2d..e53a7d203e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -285,6 +285,35 @@ fn a_wheel_click_after_typing_applies_both() { assert_eq!(undo_count(h.state()), before + 2); } +/// A text typed for one rectangle is dropped when the selection changes to another showing the same +/// hex: Enter then changes neither of them. +#[test] +fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() { + let mut app = app(); + let a = selected(&app)[0]; + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let b = selected(&app)[0]; + app.run("select.set", json!({"ids": [a]})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text("#33669980"); + h.run_steps(1); + h.state_mut().run("select.set", json!({"ids": [b]})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + for id in [a, b] { + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + } + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); + assert_eq!(undo_count(h.state()), before, "nothing was applied"); +} + /// A press on the opacity slider that takes the focus from an edited field applies the text and /// keeps the opacity the press set: a gradient stop takes both. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 258f173cd8..b383cff868 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -701,15 +701,15 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f [`oklch()`](https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch) color. The functions take the space-separated form with an optional `/ alpha`, and `rgb()` and `hsl()` also take the comma-separated legacy form. Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting -the spaces, tabs and line breaks around it; other whitespace makes the text an error. A hex color, `rgb()` and -`hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and -`oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH Sliders lower it; `oklch()` is an error -while the working RGB space is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green -and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH lightness to 0 to 1 and a negative -chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. An `hsl()` color whose -saturation and lightness are so large that a channel overflows to an infinity is an error. `opacity` is the alpha -as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other -commands still refuse `#rrggbbaa` and `#rgba`. +the spaces, tabs, line breaks and form feeds around it; other whitespace, such as a vertical tab or a no-break space, +makes the text an error. A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as +`#rrggbb` does in every command, and `oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH +Sliders lower it; `oklch()` is an error while the working RGB space is not sRGB. Values are clamped where CSS clamps +them when it parses them (red, green and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH +lightness to 0 to 1 and a negative chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is +clipped. An `hsl()` color whose saturation and lightness are so large that a channel overflows to an infinity is an +error. `opacity` is the alpha as a percentage, or `null` when the text gives none. Any other text is an error. The +color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop From 29a379ad5eaba6b20513eb83ccda1ea23818bcd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:17:19 -0800 Subject: [PATCH 010/198] Color Wheel: a click that commits a typed hex keeps both edits - A click on the wheel, the box or an OKLCH row whose press and release come in the frame that commits the hex field's text is applied after the text, at the components the text gave; a text that leaves the color as it was keeps the remembered hue. - A click on the opacity row that commits a text with an alpha keeps the opacity the click set. - The field passes its text to color.parse as typed, so a no-break space is refused as color.parse refuses it. - A text typed for one object of a symbol instance is dropped when another object of the same instance is selected. - Tests cover explicit null for every ui.colorWheel key and check that a gray OKLCH row returns no edit. --- crates/ui-egui/src/panels/color_wheel.rs | 107 ++++++++++++----- .../ui-egui/src/panels/tests_color_wheel.rs | 24 +++- .../src/panels/tests_color_wheel_hex.rs | 111 ++++++++++++++++++ 3 files changed, 207 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 126f5abfec..95847e2c51 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -307,9 +307,9 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { } /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with -/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// markers when `marked`. Returns what a click, a drag, a key or a screen reader's action picks, /// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<(Picked, Live)> { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; ui.horizontal_top(|ui| { @@ -317,21 +317,50 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { - pick = Some((box_pick(ch, z, x, y, hsb), phase)); + pick = Some((Picked::Field(ch, x, y), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); let (v, suffix, max) = strip_number(ch, hsb); let shown = SliderValue::field(v, 0.0..=max, suffix, 0); match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { - (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), - (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + (Some(z), phase, _) => pick = Some((Picked::Strip(ch, z), phase)), + (None, _, Some(v)) => pick = Some((Picked::Strip(ch, (v / max) as f32), Live::Released)), _ => {} } }); pick } +/// What a press, a drag, a key or a screen reader's action sets on the wheel or the box: the +/// components it gives, the others coming from the HSB it is applied to ([`Picked::hsb`]). +#[derive(Clone, Copy)] +enum Picked { + /// The hue ring's hue. + Hue(f32), + /// The square's saturation and brightness. + Square(f32, f32), + /// The box's field point (x across, y down) in channel `ch`. + Field(Channel, f32, f32), + /// The box's strip value in channel `ch`. + Strip(Channel, f32), +} + +impl Picked { + /// The HSB this pick gives on a color showing HSB `was`. + fn hsb(self, was: [f32; 3]) -> [f32; 3] { + match self { + Picked::Hue(h) => [h, was[1], was[2]], + Picked::Square(s, b) => [was[0], s, b], + Picked::Field(ch, x, y) => box_pick(ch, box_pos(ch, was).0, x, y, was), + Picked::Strip(ch, z) => { + let (_, x, y) = box_pos(ch, was); + box_pick(ch, z, x, y, was) + } + } + } +} + /// The opacity (0 to 1) the row shows for `tgt` and whether the row can set it: the selected /// gradient stop's or freeform point's (the first when none is selected, as [`wheel_target`] /// picks it), else that of the fill or stroke item @@ -461,24 +490,28 @@ fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> Strin } /// The hex field's id for `tgt`: it names the document, the selected objects or text characters, -/// the appearance item, the proxy and the gradient stop or freeform point, but not the color, so a -/// text typed for one of them is dropped when another one is targeted, even one showing the same hex. +/// the object selected in a symbol instance, the appearance item, the proxy and the gradient stop or +/// freeform point, but not the color, so a text typed for one of them is dropped when another one is +/// targeted, even one showing the same hex. fn hex_field_id(app: &VectorcraftApp, tgt: &Target) -> impl std::hash::Hash + use<> { let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0)); - ("color-wheel-hex", o.doc, o.selection, o.text_selection, o.appearance_item, o.fill, o.slot) + let part = app.session.active().and_then(|d| d.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone()))); + ("color-wheel-hex", o.doc, o.selection, part, o.text_selection, o.appearance_item, o.fill, o.slot) } /// The Show Hex Field row for `tgt`: a `#` and a field as wide as the row, showing `shown`. A -/// committed text goes through `color.parse`; a text it refuses shows its error in the status bar -/// and changes nothing. True when a text was committed. -fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> bool { +/// committed text goes through `color.parse` as typed; a text it refuses shows its error in the +/// status bar and changes nothing. The text's alpha is not applied when `opacity_set` (the opacity +/// row set the opacity in this frame), so a press on that row that commits the text keeps the +/// opacity it set. True when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str, opacity_set: bool) -> bool { let mut typed = None; let id = hex_field_id(app, tgt); ui.horizontal(|ui| { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new("#").size(15.0).color(t.text)); let width = ui.available_width(); - typed = widgets::text_field_named(ui, id, Some(tl!("Hex or CSS color")), Some(shown), width, 1); + typed = widgets::exact_text_field_named(ui, id, Some(tl!("Hex or CSS color")), shown, width); }); let Some(text) = typed else { return false }; match app.run("color.parse", json!({ "text": text })) { @@ -490,7 +523,7 @@ fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> // The document's RGB numbers, in the model a pick would store them in. let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored_rgb(&cms::active(), rgb, replaced(app, tgt, false).as_ref(), cmyk_doc); - let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32); + let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32).filter(|_| !opacity_set); apply_typed(app, tgt, c, alpha); } Err(e) => app.status(e), @@ -701,8 +734,9 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { /// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the /// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no /// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow -/// key, a screen reader or a field asks for, and its phase. -pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { +/// key, a screen reader or a field asks for, the index of the row that set it (0 for L, 1 for C, 2 +/// for H) and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], usize, Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { @@ -749,13 +783,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); } if let Some(x) = dragged { - out = Some((at(x), phase)); + out = Some((at(x), i, phase)); } if let Some(k) = keyed { - out = Some((with(i, k), Live::Released)); + out = Some((with(i, k), i, Live::Released)); } if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { - out = Some((with(i, f), Live::Released)); + out = Some((with(i, f), i, Live::Released)); } }); } @@ -774,7 +808,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); - let mut pick: Option<([f32; 3], Live)> = None; + let mut pick: Option<(Picked, Live)> = None; ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(44.0); @@ -794,7 +828,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let name = tl!("Saturation and brightness"); let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at); if let Some((h, phase)) = ring.hue { - pick = Some(([h, hsb[1], hsb[2]], phase)); + pick = Some((Picked::Hue(h), phase)); } // A press between the square and the ring picks the closest point of the square, which // takes the keyboard focus. @@ -802,10 +836,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let field_id = widgets::id_with(field_ui.scope_id(), "field"); field_ui.memory_mut(|m| m.request_focus(field_id)); let f = |v: f32, lo: f32, len: f32| ((v - lo) / len).clamp(0.0, 1.0); - pick = Some(([hsb[0], f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())], phase)); + pick = Some((Picked::Square(f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())), phase)); } if let Some((x, y)) = field { - pick = Some(([hsb[0], x, 1.0 - y], field_phase)); + pick = Some((Picked::Square(x, 1.0 - y), field_phase)); } }); if app.ui.color_wheel.vision { @@ -843,20 +877,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } } + let mut committed = false; if let Some(hex) = hex { ui.add_space(4.0); - // A pick or an OKLCH edit read in the frame that commits a text was made on the color - // before the text, so it is not applied. - if hex_row(app, ui, &tgt, &hex) { - return; - } + committed = hex_row(app, ui, &tgt, &hex, opacity_set); } - // A pick or an OKLCH edit read in the frame of an opacity edit goes to the stops as that edit - // left them, so the stop keeps both. - let tgt = if opacity_set { wheel_target(app, ui) } else { tgt }; + // A pick or an OKLCH edit read in the frame of an opacity edit or of a text commit goes to the + // target as that edit or text left it, so a stop keeps both. After a text commit that changed + // the color, the components the pick or the row does not set come from the color the text + // applied; a text that left the color as it was keeps the remembered hue. + let tgt = if opacity_set || committed { wheel_target(app, ui) } else { tgt }; + let now = tgt.color().filter(|c| committed && Some(*c) != color); let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); - if let Some((lch, phase)) = picked_lch { + if let Some((asked, row, phase)) = picked_lch { + let lch = match now { + Some(c) => { + let mut lch = oklab::to_oklch(cms.display_rgb(&c)); + lch[row] = asked[row]; + lch + } + None => asked, + }; let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); @@ -865,7 +907,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } return; } - let Some((hsb, phase)) = pick else { return }; + let Some((picked, phase)) = pick else { return }; + let hsb = picked.hsb(now.map_or(hsb, |c| display_hsb(&cms, &c))); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index bae909218f..d820aab5e9 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -803,20 +803,23 @@ fn oklch_sliders_need_srgb_as_the_working_space() { assert_eq!(settings.sliders, Sliders::Oklch); set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = asked.clone(); let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { let tgt = super::color::wheel_target(app, ui); let color = tgt.color(); - let _ = oklch_rows(app, ui, &tgt, color, &p3); + if oklch_rows(app, ui, &tgt, color, &p3).is_some() { + seen.store(true, std::sync::atomic::Ordering::Relaxed); + } }, app(json!("#ff0000")), ); h.run_steps(2); assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); - let undo = undo_len(h.state()); let rail = oklch_slider(&h, "Lightness").rect(); click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); - assert_eq!(undo_len(h.state()), undo, "a gray row picks nothing"); + assert!(!asked.load(std::sync::atomic::Ordering::Relaxed), "a gray row asks for no OKLCH"); } /// The rows show what they asked for while the color displays as it did, and the color's own @@ -861,3 +864,18 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(e, "`sliders` must be none or oklch"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); } + +/// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does, +/// and the other keys of the same call still apply. +#[test] +fn ui_color_wheel_keeps_a_key_given_as_null() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let set = json!({"view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch", "vision": true}); + let all = app.run("ui.colorWheel", set.clone()).unwrap(); + assert_eq!(all, set); + for key in ["view", "channel", "opacity", "hexField", "sliders", "vision"] { + assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null"); + } + let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap(); + assert_eq!(got, json!({"view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch", "vision": true})); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e53a7d203e..cef02c5e23 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -314,6 +314,117 @@ fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() { assert_eq!(undo_count(h.state()), before, "nothing was applied"); } +/// Selects the field's text and types `text` over it, without committing it. +fn type_pending(h: &mut Harness<'static, VectorcraftApp>, text: &str) { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text(text); + h.run_steps(1); +} + +/// A click at `pos` whose press and release come in one frame. +fn quick_click(h: &mut Harness<'static, VectorcraftApp>, pos: egui::Pos2) { + h.event(egui::Event::PointerMoved(pos)); + h.run_steps(1); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.input_mut().events.extend([button(true), button(false)]); + h.run_steps(2); +} + +/// A click on the square in one frame that takes the focus from an edited field applies the text, +/// then the click's saturation and brightness at the hue the text gave: a gradient stop keeps the +/// typed alpha. +#[test] +fn a_wheel_click_in_one_frame_after_typing_applies_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + type_pending(&mut h, "#33669980"); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {}", stop.opacity); + let hex = stop.color.to_hex(); + assert_ne!(hex, "#336699", "the click picked a color"); + let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap(); + assert!(ch(5) > 0xf0 && ch(1) < 0x10 && ch(3) > 0x60 && ch(3) < 0xa0, "the pick keeps the typed hue: {hex}"); + assert_eq!(undo_count(h.state()), before + 2); +} + +/// A text that leaves a white as it was, committed by a click on the square in one frame, keeps the +/// hue the white was picked from: the click's saturation brings that hue back. +#[test] +fn a_click_that_commits_the_same_white_keeps_the_remembered_hue() { + let mut app = app(); + let rect = selected(&app)[0]; + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let mut h = harness(app); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.left_top()); + assert_eq!(rgb8(&fill_color(h.state(), rect)), [255, 255, 255], "the square picks white"); + type_pending(&mut h, "#ffffff"); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + let [r, g, b] = rgb8(&fill_color(h.state(), rect)); + assert!(g > 0xf0 && r < 0x10 && b < 0x10, "the green comes back: {r:02x}{g:02x}{b:02x}"); +} + +/// A press on the opacity slider in one frame that takes the focus from a field holding hex with an +/// alpha applies the typed color and keeps the opacity the press set, not the typed alpha. +#[test] +fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let mut h = harness(app); + type_pending(&mut h, "#33669900"); + let rail = h.get_by_role_and_label(Role::Slider, "Opacity").rect(); + quick_click(&mut h, rail.center()); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert_eq!(stop.color.to_hex(), "#336699", "the text applies"); + assert!(stop.opacity > 0.2 && stop.opacity < 0.8, "the press sets the opacity: {}", stop.opacity); +} + +/// A text typed for one object of a dynamic symbol instance is dropped when another object of the +/// same instance showing the same hex is selected: Enter then changes neither of them. +#[test] +fn a_text_typed_for_one_object_of_a_symbol_instance_does_not_go_to_another() { + let mut app = app(); + let a = selected(&app)[0]; + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let b = selected(&app)[0]; + let inst = app.run("symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.selectPart", json!({"id": inst, "path": [0]})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + type_pending(&mut h, "#336699"); + h.state_mut().run("symbol.instance.selectPart", json!({"id": inst, "path": [1]})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + let Paint::Solid { color, .. } = crate::panels::current_paints(h.state()).0 else { panic!("a solid fill") }; + assert_eq!(rgb8(&color), [255, 0, 0], "the second object keeps its color"); + assert_eq!(undo_count(h.state()), before, "nothing was applied"); +} + +/// A text with a character `color.parse` does not read as whitespace (a no-break space) is refused, +/// as `color.parse` refuses it, and changes nothing. +#[test] +fn a_no_break_space_in_the_text_is_refused() { + let app = app(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + type_in(&mut h, "\u{a0}#336699"); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc); + assert!(!h.state().ui.status.is_empty(), "the status bar says why"); + assert!(h.state_mut().run("color.parse", json!({"text": "\u{a0}#336699"})).is_err()); +} + /// A press on the opacity slider that takes the focus from an edited field applies the text and /// keeps the opacity the press set: a gradient stop takes both. #[test] From 7533a81e226c40bab844488d28a0ee3bc9aa45b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:46:34 -0800 Subject: [PATCH 011/198] Color Wheel: opacity edits target and count what the command changes - A null `id` or `ids` names no object, so while the Type tool has characters selected the paint still goes to those characters. - An opacity for selected characters is refused before the typing session ends, so the session and its undo step stay as they are. - With an opacity alone, `objects` counts only the objects that took it. - `paint.proxies` reads a targeted layer's visible, unlocked art, as the commands do, so a locked object's fill no longer enables the control. - A field commit on one OKLCH row keeps a value clicked or dragged on another row in the same frame, and a drag in progress stays in progress. --- crates/engine/src/cmd/paint.rs | 40 ++++++--- crates/engine/src/tests/paintopacity.rs | 83 +++++++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 39 +++++++-- .../ui-egui/src/panels/tests_color_wheel.rs | 37 ++++++++- docs/mcp.md | 5 +- 5 files changed, 179 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index e5ca789aec..16cd564668 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no item, and no ids or id other than null, are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -257,7 +257,8 @@ impl Session { let targets = super::graph::series_group_marks_where(&st.doc, subjects, |n| n.extras().series_index.is_some()); return targets.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); } - let leaves = super::leaf_targets(self, subjects).ok()?; + // The command's targets: a targeted layer stands for its visible, unlocked art. + let leaves = super::paint_targets(self, &Value::Null).ok()?; leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) } @@ -537,6 +538,11 @@ fn opacity_param(p: &Value, cmd: &str) -> Result> { } } +/// Whether `p` gives `key` a value other than null. +fn names(p: &Value, key: &str) -> bool { + p.get(key).is_some_and(|v| !v.is_null()) +} + /// The error for an `opacity` that would go to type characters, which have no opacity of their own. fn characters_have_no_opacity(cmd: &str) -> EngineError { bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke") @@ -565,10 +571,15 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; - // Characters selected with the Type tool take the paint, not the whole type object (#1063). - if p.get("ids").is_none() - && p.get("id").is_none() - && p.get("item").is_none() + // Characters selected with the Type tool take the paint, not the whole type object (#1063). A + // null `ids` or `id` names no object, as the targets read it. + let on_characters = !names(p, "ids") && !names(p, "id") && p.get("item").is_none(); + // An opacity for the characters is refused before their typing session ends, so the session + // and its undo step stay as they are. + if on_characters && opacity.is_some() && super::textedit::selected_range(s).is_some_and(|(_, a, b)| a != b) { + return Err(characters_have_no_opacity(cmd)); + } + if on_characters && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { @@ -687,8 +698,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); - // Whether a target took the opacity, and whether one would have given it to its characters. - let (took_opacity, characters_skipped) = (std::cell::Cell::new(false), std::cell::Cell::new(false)); + // The targets that took the opacity, and whether one would have given it to its characters. + let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false)); let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { characters.borrow_mut().push(n.id); @@ -764,7 +775,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity for i in points { if let Some(q) = m.points.get_mut(*i) { q.opacity = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } } return; @@ -773,7 +784,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) }; if let Some(item) = item { *item = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } }; // The objects counted: with a design's art, those with a row equal to the art's. @@ -796,7 +807,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity }, |before, d, changed| { // An opacity that no target took is an error, which also takes back the paint given with it. - if opacity.is_some() && !took_opacity.get() { + if opacity.is_some() && took_opacity.borrow().is_empty() { if characters_skipped.get() { return Err(characters_have_no_opacity(cmd)); } @@ -829,14 +840,17 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity paint_new_art(s, paint, fill); s.remember_paint(paint); } - Ok(json!({"objects": ids.iter().collect::>().len()})) + // An opacity alone counts only the objects that took it. + let took = took_opacity.into_inner(); + let counted: std::collections::BTreeSet<_> = ids.iter().filter(|id| paint.is_some() || took.contains(*id)).collect(); + Ok(json!({"objects": counted.len()})) } /// The instance whose object is selected with Direct Selection, and that object's path /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result)>> { - if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() { + if names(p, "ids") || names(p, "id") || p.get("item").is_some() { return Ok(None); } let part = super::brushsym::selected_part(s)?; diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index e733bbab1c..41874ddfc3 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -234,6 +234,89 @@ fn with_characters_selected_an_id_takes_the_opacity() { assert_eq!(node(&s, t), before, "the characters keep their paint"); } +/// While the Type tool has characters selected, a null `id` or `ids` names no object: the paint goes +/// to the selected characters only, as without the key. +#[test] +fn with_characters_selected_a_null_id_paints_the_characters() { + let runs = |key: Option<&str>| { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hello"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + select(&mut s, &[t]); + select_characters(&mut s, t); + let mut p = json!({"color": "#ff0000"}); + if let Some(key) = key { + p[key] = Value::Null; + } + s.execute("paint.setFill", &p).unwrap(); + match &node(&s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + } + }; + let characters = runs(None); + assert!(characters.len() > 1, "only the selected characters take the paint"); + for key in ["id", "ids"] { + assert_eq!(runs(Some(key)), characters, "{key}: null"); + } +} + +/// An opacity for characters selected while the Type tool is typing is refused before the typing +/// session ends: the session goes on, and no undo step is recorded. +#[test] +fn an_opacity_for_characters_leaves_the_typing_session_running() { + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Hello", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 2})); + assert!(crate::cmd::typing_in_progress(&s)); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert!(crate::cmd::typing_in_progress(&s), "the typing session goes on"); + assert_eq!(undo_labels(&s).len(), undo, "no undo step"); +} + +/// With an opacity alone, the reply counts only the objects that took it: a selected object without +/// that fill item is left out, and one already at that opacity still counts. With a paint, every +/// target counts. +#[test] +fn an_opacity_alone_counts_the_objects_that_took_it() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + select(&mut s, &[a, b]); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1, "already at 40%"); + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap()["objects"], 2); +} + +/// With a layer targeted, `paint.proxies` reads the art the command edits: a locked object's fill +/// row does not count, so the proxy answers null when the edit finds no fill to take the opacity. +#[test] +fn a_targeted_layers_proxy_leaves_out_locked_art() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[b]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + select(&mut s, &[a]); + s.execute("object.lock", &json!({})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + s.execute("object.unlockAll", &json!({})).unwrap(); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the unlocked fill counts"); +} + /// A type object whose characters take the paint is left alone beside a rectangle that takes the /// opacity, with no error; alone, it answers the characters error. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 95847e2c51..663e802c9f 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -729,14 +729,32 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { (max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32 } +/// The OKLCH rows' edits of one frame with row `i`'s edit added: row `i` takes its value from +/// `asked`, on top of `out` (the other rows' edits so far, or none on top of `lch`). A drag on one +/// row stays in progress when another row's field commits in the same frame. +pub(crate) fn oklch_row_edit( + out: Option<([f64; 3], [bool; 3], Live)>, + lch: [f64; 3], + asked: [f64; 3], + i: usize, + phase: Live, +) -> ([f64; 3], [bool; 3], Live) { + let (mut base, mut rows, was) = out.unwrap_or((lch, [false; 3], phase)); + base[i] = asked[i]; + rows[i] = true; + let phase = if matches!(was, Live::Dragging) { Live::Dragging } else { phase }; + (base, rows, phase) +} + /// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to /// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°. /// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the /// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no /// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow -/// key, a screen reader or a field asks for, the index of the row that set it (0 for L, 1 for C, 2 -/// for H) and its phase. -pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], usize, Live)> { +/// key, a screen reader or a field asks for, which rows set it (L, C and H in that order) and the +/// phase of the last edit. A field that commits when a click on another row takes its focus keeps +/// its value along with the click's. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], [bool; 3], Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { @@ -757,7 +775,8 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: } out }; - let mut out = None; + let mut out: Option<([f64; 3], [bool; 3], Live)> = None; + let mut set = |asked: [f64; 3], i: usize, phase: Live| out = Some(oklch_row_edit(out, lch, asked, i, phase)); ui.add_enabled_ui(enabled, |ui| { let field_w = 48.0; let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); @@ -783,13 +802,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); } if let Some(x) = dragged { - out = Some((at(x), i, phase)); + set(at(x), i, phase); } if let Some(k) = keyed { - out = Some((with(i, k), i, Live::Released)); + set(with(i, k), i, Live::Released); } if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { - out = Some((with(i, f), i, Live::Released)); + set(with(i, f), i, Live::Released); } }); } @@ -890,11 +909,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let now = tgt.color().filter(|c| committed && Some(*c) != color); let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); - if let Some((asked, row, phase)) = picked_lch { + if let Some((asked, rows, phase)) = picked_lch { let lch = match now { Some(c) => { let mut lch = oklab::to_oklch(cms.display_rgb(&c)); - lch[row] = asked[row]; + for row in (0..3).filter(|r| rows[*r]) { + lch[row] = asked[row]; + } lch } None => asked, diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index d820aab5e9..8124aa5ded 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -12,9 +12,10 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; use super::color_wheel::{ - ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_row_edit, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, }; use crate::VectorcraftApp; +use crate::widgets::Live; /// An app with a selected rectangle filled with `fill`. fn app(fill: serde_json::Value) -> VectorcraftApp { @@ -646,6 +647,40 @@ fn a_drag_on_lightness_keeps_the_chroma_asked_for() { assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]); } +/// A lightness typed in the L field and committed by a click on the C rail in one frame keeps both +/// edits: the color takes the typed L and the clicked C. +#[test] +fn a_typed_lightness_committed_by_a_click_on_chroma_keeps_both() { + let mut h = oklch_harness(app(json!("#ff0000"))); + let h0 = fill_oklch(h.state())[2]; + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Lightness").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Lightness").type_text("50"); + h.run_steps(1); + let rail = oklch_slider(&h, "Chroma").rect(); + quick_click(&mut h, on_rail(rail, 0.2)); + let [l, c, hue] = fill_oklch(h.state()); + assert!((l - 0.5).abs() < 0.01, "the typed lightness stays: {l}"); + assert!((c - 0.08).abs() < 0.01, "the click sets the chroma: {c}"); + assert!((hue - h0).abs() < 1.0, "the hue stays: {h0} → {hue}"); +} + +/// When a drag on one OKLCH row and a field commit on another come in one frame, the frame's edit +/// keeps both values and the drag stays in progress, in either order. +#[test] +fn a_field_commit_beside_a_drag_keeps_the_drag_going() { + let lch = [0.6, 0.2, 30.0]; + let drag = |out| oklch_row_edit(out, lch, [0.8, 0.0, 0.0], 0, Live::Dragging); + let field = |out| oklch_row_edit(out, lch, [0.0, 0.0, 200.0], 2, Live::Released); + for (out, order) in [(field(Some(drag(None))), "drag first"), (drag(Some(field(None))), "field first")] { + assert_eq!(out.0, [0.8, 0.2, 200.0], "{order}"); + assert_eq!(out.1, [true, false, true], "{order}"); + assert!(matches!(out.2, Live::Dragging), "{order}"); + } +} + /// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step. /// Each row reports its range and the adjust actions to screen readers. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 58f96d804a..3f1c509728 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -888,8 +888,9 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint -undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool +undone. With an opacity alone, the reply's `objects` counts only the objects that took it. `paint.proxies` answers +it as `fillOpacity` and `strokeOpacity`, from the first selected object that has that row. With a layer targeted, +it reads the layer's visible, unlocked art, as the commands do. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and From f47ebd9887fcaa64e58c55a78efb2d09fd041ca6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:31:19 -0800 Subject: [PATCH 012/198] Color: a bad target is refused for a picked object with a null id With an object of a dynamic symbol instance selected, `id: null` or `ids: null` reached the item check, which stops at those keys before it reads `target`, so a bad `target` changed the object. The target is now read first. --- crates/engine/src/cmd/paint.rs | 2 ++ crates/engine/src/tests/paintopacity.rs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 16cd564668..f0fbb91ff1 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -855,6 +855,8 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result Date: Thu, 19 Nov 2026 17:38:15 -0800 Subject: [PATCH 013/198] Rerun CI From 97599b5a50a086b8c4f1a860a8b2ad41649e28ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:32:24 -0800 Subject: [PATCH 014/198] Color: color.parse says it reads a subset of CSS without calc() The help, the color module docs and docs/mcp.md state that a function's arguments are literal numbers, percentages, angles and none, and that calc(), var(), color-mix(), other nested functions, named colors and the other color functions and spaces are errors. --- crates/color/src/css.rs | 5 +++++ crates/engine/src/cmd/colorcmds.rs | 2 +- docs/mcp.md | 5 ++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index c8b1e84ab2..24c274846b 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -7,6 +7,11 @@ //! take the comma-separated legacy form (). //! Hues take the angle units of CSS Values 4 (). A hex //! color may leave out its `#`. +//! +//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages, +//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`, +//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are +//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`). use crate::oklab::{self, CHROMA_FULL}; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 8890f9eec9..0a68310ecd 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Parse Color", [], None, - "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; this is a subset of CSS: a function's arguments are literal numbers, percentages, angles (deg, grad, rad or turn) and none, so calc(), var(), color-mix() and every other function, named colors and the other color spaces are errors; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/docs/mcp.md b/docs/mcp.md index af8b76524b..11aece8afe 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -739,7 +739,10 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f space-separated form with an optional `/ alpha`, and `rgb()` and `hsl()` also take the comma-separated legacy form. Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting the spaces, tabs, line breaks and form feeds around it; other whitespace, such as a vertical tab or a no-break space, -makes the text an error. A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as +makes the text an error. The command reads a subset of CSS: a function's arguments are literal numbers, percentages, +angles and `none`, so `calc()`, `var()`, `color-mix()`, relative color syntax and every other nested function are +errors, as are named colors and the functions and color spaces not listed above (`hwb()`, `lab()`, `oklab()` and +`color()`). A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and `oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH Sliders lower it; `oklch()` is an error while the working RGB space is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH From 6898eed99f232ff3410c10625aef6f0d33c5d296 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:35:13 -0800 Subject: [PATCH 015/198] Color: paint.setFill refuses a bad target when an id names the object paint.setFill and paint.setStroke read `target` and `aligned` before choosing their targets, so a bad value is refused when `id` or `ids` names an object and while the Type tool has characters selected, as it already was for other selections. --- crates/engine/src/cmd/paint.rs | 4 +++ crates/engine/src/tests/paintopacity.rs | 33 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 4b20947a86..f5c4983b62 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -636,6 +636,10 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let bucket = bucket_color_params(s, p, cmd)?; let p = bucket.as_ref().unwrap_or(p); + // A bad `target` or `aligned` is refused for every kind of target: `item_target` reads no + // `target` once `id` or `ids` names an object, and selected characters read neither. + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 53d72b0e5d..5b980f9803 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -427,6 +427,39 @@ fn an_object_in_a_symbol_instance_refuses_a_bad_target() { assert_ne!(*s.doc().unwrap().doc, *doc); } +/// A bad `target` is refused when `id` or `ids` names an object, and a bad `target` or `aligned` +/// while the Type tool has characters selected; each leaves the document alone. A good `target` +/// with an `id` still paints the object. +#[test] +fn a_bad_target_is_refused_with_an_id_or_selected_characters() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for p in [ + json!({"color": "#ff0000", "target": "content", "id": r.0}), + json!({"color": "#ff0000", "target": "content", "ids": [r.0]}), + json!({"opacity": 40, "target": "content", "id": r.0}), + json!({"opacity": 40, "target": "content", "ids": [r.0]}), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{cmd} {p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{cmd} {p}"); + } + } + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": r.0})).unwrap()["objects"], 1); + assert_ne!(*s.doc().unwrap().doc, *doc); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"color": "#ff0000", "target": "content"}), json!({"color": "#ff0000", "aligned": "yes"})] { + assert!(s.execute("paint.setFill", &p).is_err(), "{p}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } +} + /// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows /// it; the object's fill item and the other points stay as they were. #[test] From 2f868a6ab4fdf7c6361a9a29d85881d05893cac0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:24:51 -0800 Subject: [PATCH 016/198] Brushes: Pattern Brush Options' Scale follows the pen's pressure, tilt, bearing, rotation and wheel A pattern brush's scale can now follow Pressure, Tilt, Bearing, Rotation or Stylus Wheel, with a second scale beside the first, as an Art brush's Width does. Pattern Brush Options and Options of Selected Object show the mode menu and the second scale on the Scale row, and brush.new, brush.options and brush.objectOptions take `scale_mode` and `scale_max`. Each side, start and end tile is as tall as the scale at each point of the stroke and as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit, Add Space to Fit and Approximate Path fit the tiles of each run as they are measured where they land. A stroke without the input draws at the scale half way between the two. A brush with a fixed scale draws as before, and brushes without the new fields save without them. Options of Selected Object keeps each path's own second scale when only the scale or the mode changes, for pattern scales and art widths. Docs: docs/mcp.md, docs/target-app-parity.md, docs/hardware-parity.md. --- crates/brush/src/lib.rs | 37 ++- crates/brush/src/tests.rs | 180 ++++++++++++ crates/brush/src/warp.rs | 266 +++++++++++++++++- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/brushes.rs | 33 ++- crates/engine/src/tests/brushsym.rs | 64 +++++ crates/mcp/src/ui_catalog.rs | 4 +- .../ui-egui/src/dialogs/brush_art_options.rs | 75 +++-- .../src/dialogs/brush_options/tests.rs | 88 ++++++ crates/ui-egui/src/menus/ui_commands.rs | 4 +- docs/hardware-parity.md | 2 +- docs/mcp.md | 15 +- docs/target-app-parity.md | 3 +- 13 files changed, 722 insertions(+), 53 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index d3dd3b6b38..30f5d6667e 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -549,6 +549,15 @@ pub struct PatternBrush { pub end_swatch: Option, /// Scale in percent. pub scale: f64, + /// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the + /// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art + /// brush's width does ([`ArtBrush::width_mode`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_mode: Option, + /// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`scale` without one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_max: Option, /// Space between tiles in percent of the tile width. pub spacing: f64, pub fit: PatternFit, @@ -561,6 +570,15 @@ impl PatternBrush { /// The ranges of the scale and of the spacing (%). pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0); pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0); + + /// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the + /// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen. + pub fn scale_range(&self) -> (f64, f64) { + match self.scale_mode { + Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)), + _ => (self.scale, self.scale), + } + } } impl Default for PatternBrush { @@ -584,6 +602,8 @@ impl Default for PatternBrush { end_frame: None, end_swatch: None, scale: 100.0, + scale_mode: None, + scale_max: None, spacing: 0.0, fit: PatternFit::Stretch, flip_along: false, @@ -767,6 +787,11 @@ impl Brush { } BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); + // The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. + if !p.scale_mode.is_some_and(Variation::follows_pen) { + p.scale_mode = None; + } + p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale)); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { if frame.is_some_and(|f| !valid_tile_frame(f)) { @@ -819,6 +844,8 @@ struct ArtOptions { #[derive(Serialize, Deserialize)] struct PatternOptions { scale: f64, + scale_mode: Option, + scale_max: Option, spacing: f64, fit: PatternFit, flip_along: bool, @@ -835,7 +862,7 @@ impl BrushKind { BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], - BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"], BrushKind::Bristle(_) => &[], } } @@ -870,6 +897,8 @@ impl BrushKind { }), BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { scale: p.scale, + scale_mode: p.scale_mode, + scale_max: p.scale_max, spacing: p.spacing, fit: p.fit, flip_along: p.flip_along, @@ -898,8 +927,8 @@ impl BrushKind { } BrushKind::Pattern(p) => { let o: PatternOptions = serde_json::from_value(v)?; - (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = - (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + (p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing); + (p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization); } BrushKind::Bristle(_) => {} } @@ -1123,7 +1152,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), - BrushKind::Pattern(p) => warp::pattern(p, bp, w), + BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke), }; let colorization = brush.kind.colorization(); for n in &mut out { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2b1449eddf..cec39f9477 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2015,6 +2015,186 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() { assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]); } +/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`. +fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option, max: Option) -> Brush { + let mut b = pattern_brush(fit, corners); + if let BrushKind::Pattern(p) = &mut b.kind { + (p.scale, p.scale_mode, p.scale_max) = (scale, mode, max); + } + b +} + +/// The bounds of each piece, left to right. +fn piece_spans(out: &[Node]) -> Vec { + let mut spans: Vec = out.iter().filter_map(Node::geometric_bounds).collect(); + spans.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + spans +} + +/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen +/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen +/// pressed harder, and each Fit still fits them to the path. +#[test] +fn pattern_brush_scale_follows_the_pressure() { + let bp = line(0.0, 0.0, 200.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + // 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0)); + assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0)); + // Stretch to Fit fills the path, and the tiles grow longer along it. + let spans = piece_spans(&out); + assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out)); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}"); + assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}"); + // The stroke weight scales it. + let out = + draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() }); + assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0)); + // Without recorded pressure, half way between the two scales. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0)); + assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out)); + // With an even pressure, Add Space with spacing places as many tiles as the one scale that + // pressure gives: the spacing counts when the tiles are counted again. + let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]); + let spaced = |mode: Option, max: Option| { + let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 100.0; + } + piece_spans(&draw(&b, &even)).len() + }; + assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None)); + // With spacing, Stretch to Fit still fills the path and Approximate Path still centers the + // tiles, with the gaps between them counted and none after the last. + for fit in [PatternFit::Stretch, PatternFit::Approximate] { + let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 50.0; + } + let spans = piece_spans(&draw(&b, &ramp)); + let (first, last) = (spans[0], spans[spans.len() - 1]); + assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}"); + if fit == PatternFit::Stretch { + assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}"); + } + } + // Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it. + for fit in [PatternFit::AddSpace, PatternFit::Approximate] { + let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + let spans = piece_spans(&out); + assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}"); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}"); + let (first, last) = (spans[0], spans[spans.len() - 1]); + if fit == PatternFit::AddSpace { + assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}"); + } else { + assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}"); + } + } +} + +/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own +/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a +/// brush without the setting does. +#[test] +fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() { + let bp = line(0.0, 0.0, 100.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0)); + let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) }; + // 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %. + for (mode, st, height) in [ + (Variation::Tilt, posed(Some(0.0), None, None), 12.0), + (Variation::Tilt, posed(Some(1.0), None, None), 2.0), + (Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5), + (Variation::Rotation, posed(None, None, Some(-90.0)), 4.5), + (Variation::StylusWheel, wheel(1.0), 12.0), + (Variation::StylusWheel, wheel(0.0), 2.0), + // Without its own input, half way. + (Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0), + (Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0), + (Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0), + (Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0), + (Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0), + ] { + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, height, 1e-6), "{mode:?}: {h}"); + } + // Fixed, a mode without a second scale, and a second scale equal to the first draw what the + // brush draws without them. + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp); + for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] { + assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}"); + } + let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap(); + assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}"); + // A mode the scale does not take is read as Fixed, and the second scale is kept within range. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308}, + {"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0}, + ])); + let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") }; + assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0))); + // A stroke sets its own mode and second scale. + let mut own = serde_json::Map::new(); + own.insert("scale_mode".into(), serde_json::json!("pressure")); + own.insert("scale_max".into(), serde_json::json!(300.0)); + let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap(); + assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}"); +} + +/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale +/// where they are, on open and closed paths, and stays finite at the ends of the scale's range. +#[test] +fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() { + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let doc = Document::new(1.0, 1.0); + // Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile. + let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut ends.kind { + (p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0))); + } + let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp); + let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap()); + assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}"); + assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}"); + // A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends. + let mut rect = BezPath::new(); + rect.move_to((0.0, 0.0)); + rect.line_to((100.0, 0.0)); + rect.line_to((100.0, 60.0)); + rect.line_to((0.0, 60.0)); + rect.close_path(); + for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] { + for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] { + for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] { + let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max)); + let out = stroke_pieces(&doc, &b, bp, &ramp); + assert!(!out.is_empty(), "{fit:?} {scale} {max}"); + let r = bounds(&out); + assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}"); + } + } + } + // On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller + // than the last one's. + let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0)); + let out = stroke_pieces(&doc, &b, &rect, &ramp); + let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp); + assert_ne!(out, fixed); + let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height())); + let corners: Vec = out.iter().take(4).map(corner).collect(); + assert!(corners[0] < corners[3], "{corners:?}"); + // The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the + // first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile. + let first_side = out.get(4).and_then(Node::geometric_bounds); + assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index edf0ac0567..240a5e14eb 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -646,6 +646,227 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross) } +/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies +/// (`marks`: the arc lengths of the recorded pen samples, between which the scale runs in a +/// straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it is +/// too when the scale is the same at both ends of the span and at every sample within it. +fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { + let mid = k((s0 + s1) / 2.0); + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && marks.iter().filter(|&&s| s > s0 && s < s1).all(|&s| k(s) == mid); + if mid <= 0.0 || marks.is_none_or(even) { + return tile_on(t, tile, s0, s1, mid); + } + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid) +} + +/// The most side tiles a run of a pattern brush places. +const MAX_TILES: usize = 20000; + +/// How many times a pattern brush whose scale varies measures its side tiles again where the fit +/// puts them. +const REFITS: usize = 3; + +/// How many times a pattern brush whose scale varies halves the range a start or end tile's +/// length lies in. +const END_SOLVE_STEPS: usize = 48; + +/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along +/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and +/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include +/// that next one when there is room for part of it. +fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) { + let mut tiles = vec![]; + let mut pos = 0.0; + while tiles.len() < MAX_TILES { + let (w, g) = natural(a + pos); + if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) { + break; + } + tiles.push((w, g)); + if pos + w > avail { + let whole = (tiles.len() - 1) as f64; + return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0)); + } + pos += w + g; + } + let whole = tiles.len() as f64; + (tiles, whole) +} + +/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p` +/// (0 at the first scale, 1 at the second). +fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 { + let (light, heavy) = pb.scale_range(); + weight * (light + (heavy - light) * p).max(1.0) / 100.0 +} + +/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke. +/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that +/// input's missing value gives. +fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) { + let (light, heavy) = pb.scale_range(); + match pb.scale_mode { + Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true), + Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false), + _ => (weight * pb.scale.max(1.0) / 100.0, false), + } +} + +/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at +/// the middle of the tile when it is `w` long: the length that is as long as the scale at its own +/// middle, found by halving the range from 0 to `room`. A tile that needs more than `room` gets +/// the length it needs at `room`, longer than `room`. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64) -> f64 { + let length = |w: f64| width * k_mid(w); + let first = length(0.0); + if length(first) == first || room.is_nan() || room <= 0.0 { + return first; + } + if length(room) > room { + return length(room); + } + let (mut short, mut long) = (0.0, room); + for _ in 0..END_SOLVE_STEPS { + let mid = (short + long) / 2.0; + if length(mid) > mid { + short = mid; + } else { + long = mid; + } + } + long +} + +/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its +/// arc length, and again a track's length on, for runs of a closed track that wrap round. +fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { + let points = match mode { + Variation::Fixed | Variation::Random => None, + Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points), + Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points), + Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points), + Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), + Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), + }; + points.into_iter().flatten().flat_map(|&(f, _)| [f * l, f * l + l]).collect() +} + +/// Whether `stroke` recorded the pen input `mode` follows. +fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool { + match mode { + Variation::Fixed | Variation::Random => false, + Variation::Pressure => stroke.pressure.is_some(), + Variation::Tilt => stroke.tilt.is_some(), + Variation::Bearing => stroke.bearing.is_some(), + Variation::Rotation => stroke.rotation.is_some(), + Variation::StylusWheel => stroke.wheel.is_some(), + } +} + +/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they +/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between +/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to +/// `avail`. An added tile is +/// `natural(s)` long at `s` from the run's start. +fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) { + let mut length: f64 = tiles.iter().map(|t| t.0).sum(); + let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + // How much of the run the tiles and the spacing between them take. + let run = |length: f64, gaps: f64| length + gaps; + while let [.., (_, before), (w, _)] = tiles.as_slice() { + let (w, before) = (*w, *before); + let (now, without) = (run(length, gaps), run(length - w, gaps - before)); + let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() }; + if !drop { + break; + } + tiles.pop(); + length -= w; + gaps -= before; + } + while tiles.len() < MAX_TILES { + let last_gap = tiles.last().map_or(0.0, |t| t.1); + let now = run(length, gaps); + let (w, g) = natural(run(length, gaps + last_gap)); + if w.is_nan() || w <= 1e-9 { + break; + } + let with = run(length + w, gaps + last_gap); + let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() }; + if !add { + break; + } + tiles.push((w, g)); + length += w; + gaps += last_gap; + } +} + +/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as +/// [`tile_scaled`] takes them), at the scale `k(s)` at +/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps +/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles +/// (around a lone tile), and Approximate keeps both and centers the tiles on the run. +fn varied_side_tiles( + out: &mut Budget, + t: &Track, + pb: &PatternBrush, + side: &(Node, Rect), + (a, avail): (f64, f64), + k: &dyn Fn(f64) -> f64, + marks: &[f64], +) { + let tw = side.1.width(); + // Each side tile and the gap after it as long as the scale at the tile's middle. + let natural = |s: f64| { + let w = tw * k(s + tw * k(s) / 2.0); + (w, w * pb.spacing.max(0.0) / 100.0) + }; + let (tiles, count) = varied_tiles(a, avail, &natural); + let n = match pb.fit { + PatternFit::AddSpace => count.floor(), + PatternFit::Stretch | PatternFit::Approximate => count.round(), + } + .max(1.0) as usize; + let mut tiles = tiles[..n.min(tiles.len())].to_vec(); + // How far the fit stretches the tiles and gaps, where the first tile starts, and the space + // between tiles when the fit sets it. + let fitted = |tiles: &[(f64, f64)]| { + let length: f64 = tiles.iter().map(|t| t.0).sum(); + // The gaps between the tiles: after every tile but the last. + let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + match pb.fit { + PatternFit::Stretch => (avail / (length + gaps), 0.0, None), + PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))), + PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None), + PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None), + } + }; + // The fit moves the tiles from where they were measured, so each is measured again at the + // middle of where the fit puts it, and the fit worked out again, a few times over. + for _ in 0..REFITS { + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for tile in &mut tiles { + let placed = tile.0 * stretch; + let w = tw * k(s0 + placed / 2.0); + s0 += placed + space.unwrap_or(tile.1 * stretch); + *tile = (w, w * pb.spacing.max(0.0) / 100.0); + } + recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s)); + } + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for &(w, g) in &tiles { + let w = w * stretch; + out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks))); + if out.full() { + break; + } + s0 += w + space.unwrap_or(g * stretch); + } +} + /// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what /// [`CornerSource`] gives. #[derive(Clone, Copy)] @@ -800,10 +1021,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true })) } -pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { +/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt, +/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives +/// (half way without a recording), each tile and the gap after it as long as the scale at its +/// middle, and each corner tile at the scale at its corner. +pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec { let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; - let k = weight * pb.scale.max(1.0) / 100.0; + let scale_at = |p: f64| pattern_scale_at(pb, weight, p); + let (k, varies) = pattern_scale(pb, weight, stroke); let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); @@ -822,6 +1048,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if l <= 1e-9 { continue; } + // The scale at arc length `s` of the track; a run past the start of a closed track wraps + // round to it, and on an open track a point past either end takes the scale at that end. + let ks = |s: f64| { + if !varies { + return k; + } + let at = (if t.closed && s > l { s - l } else { s }).clamp(0.0, l); + scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5)) + }; + let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l)); let corners = t.corner_positions(); // Corner tiles, centred on the corner and turned to the bisector. The path on each side of // a corner is shortened by `trims` (`None`: half the widest corner tile art). @@ -845,17 +1081,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec }; before.min(after) }; - for (ci, &(i, _)) in corners.iter().enumerate() { + for (ci, &(i, at)) in corners.iter().enumerate() { if out.full() { break; } + let kc = ks(at); let (a, b) = t.in_out(i); // Turning towards the left normal puts the tile's +y side on the inside. let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) }; let (art, bb) = match tile { Some(Corner::Art(tile)) => tile, Some(Corner::Source(source)) => { - let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci)); + let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci)); for n in pieces { out.take(Some(n)); } @@ -867,8 +1104,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec continue; } }; - trims.push(None); - corner_half = corner_half.max(bb.width() * k / 2.0); + // With a scale that varies, each corner's tile is its own size, so the path beside it + // is shortened by half of that tile. + trims.push(varies.then_some(bb.width() * kc / 2.0)); + corner_half = corner_half.max(bb.width() * kc / 2.0); // Inner and outer corner art is the corner that joins a side tile on its right to one // below it, so its arms point along +x and +y (as the flips leave them). The tile is // turned so that the line halving its arms lies on the line halving the sides at the @@ -878,7 +1117,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 }); let sides = b - a; let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x); - let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2()); + let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2()); let mut n = art.clone(); n.transform(xf, true); out.take(Some(n)); @@ -911,9 +1150,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri == 0 && let Some(st) = &start { - let w = st.1.width() * k; + // As long as the scale at its middle. + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0)); if b - a > w { - out.take(tile_on(&t, st, a, a + w, k)); + out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; } } @@ -921,9 +1161,9 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri + 1 == nruns && let Some(en) = &end { - let w = en.1.width() * k; + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0)); if b - a > w { - out.take(tile_on(&t, en, b - w, b, k)); + out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; } } @@ -931,6 +1171,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if avail <= 1e-6 { continue; } + if let Some(marks) = &marks { + varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks); + continue; + } let unit = tw + gap; match pb.fit { PatternFit::Stretch => { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..5653b42bb6 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..cb5ac44c40 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -580,7 +580,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result merged.insert(k.clone(), next); } keep_drawn_modes(b, &was, ¶ms, &mut merged); - keep_largest_width(b, &was, ¶ms, &mut merged); + keep_second_value(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -643,27 +643,34 @@ fn keep_drawn_modes( merged.insert("modes".into(), Value::Array(kept)); } -/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when -/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is -/// the width, so without this a changed width would also change the largest width. -fn keep_largest_width( +/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when +/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern +/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the +/// first, so without this a changed first value would also change the second. +fn keep_second_value( b: &Brush, was: &serde_json::Map, params: &serde_json::Map, merged: &mut serde_json::Map, ) { - if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + let (first, second) = match b.kind { + BrushKind::Art(_) => ("width", "width_max"), + BrushKind::Pattern(_) => ("scale", "scale_max"), + _ => return, + }; + if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) { return; } - let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { - Some(BrushKind::Art(a)) => Some(a), + // The first value, the second value of its own, and whether the value follows the pen. + let values = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))), + Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))), _ => None, }; - let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; - let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); - // Only a width that followed the pen has a largest width, and only one that still does uses it. - if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { - merged.insert("width_max".into(), json!(before.width)); + let (Some(before), Some(after)) = (values(was), values(merged)) else { return }; + // Only a value that followed the pen has a second value, and only one that still does uses it. + if before.1.is_none() && before.2 && after.2 && after.0 != before.0 { + merged.insert(second.into(), json!(before.0)); } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 1d53214ec9..9a1039405a 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); } +/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0 +/// and 1. +fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Stitches").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(), + k => panic!("not a pattern brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap(); + // Both scales follow the pressure; the first path's second scale is its scale, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The scale the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new first scale leaves each path's second scale as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A second scale the params give is set on each path, and the brush keeps its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); + let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + // A mode that is not one is refused, and nothing changes. + let steps = undo_steps(&s); + assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err()); + assert_eq!(undo_steps(&s), steps); +} + +/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options` +/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out. +#[test] +fn pattern_brush_scale_mode_goes_through_the_brush_commands() { + let mut s = session(); + let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0); + let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300}); + s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap(); + let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap(); + let def = get(&mut s); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err()); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..ed77fbb415 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1115,13 +1115,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8054553d22..8b9f577ad8 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -14,7 +14,9 @@ //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, //! `overlap` (bend on each run between sharp corners). -//! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, +//! Pattern: `scale`, `scaleMax` (the scale at the heaviest pen pressure, upright, at 180° or at +//! the wheel's far end, %), `scaleMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation` | +//! `stylusWheel`), `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, //! `flipAcross`, `outerCornerTile` and `innerCornerTile` (`original`: the corner art the brush //! draws there | `none` | `autoCentered` | `autoBetween` | `autoSliced` | `autoOverlap`: a tile //! made from the side tile), @@ -208,6 +210,8 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { } BrushKind::Pattern(p) => { f.insert("scale".into(), json!(p.scale)); + f.insert("scaleMode".into(), json!(p.scale_mode.unwrap_or_default().id())); + f.insert("scaleMax".into(), json!(p.scale_range().1)); f.insert("spacing".into(), json!(p.spacing)); f.insert("fit".into(), json!(id_of(&p.fit))); f.insert("flipAlong".into(), json!(p.flip_along)); @@ -261,6 +265,47 @@ fn art_width_mode(d: &Dialog) -> Variation { Variation::parse(&d.str("widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } +/// How a pattern brush's scale varies: Fixed, or with the pen's pressure, tilt, bearing, rotation +/// or wheel. +fn pattern_scale_mode(d: &Dialog) -> Variation { + Variation::parse(&d.str("scaleMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) +} + +/// The second value (`max_key`, the definition's `def_max`) of a value that follows the pen (`key`, +/// the same in the definition), for `brush.options` params. `null` in Options of Selected Object +/// when the path it opened with has no second value and the second value has not been changed from +/// the value it opened with, so each selected path keeps its own. +fn second_value(d: &Dialog, (key, max_key, def_max): (&str, &str, &str), range: (f64, f64)) -> Value { + let v = clamped(d, max_key, range); + let def = d.fields.get("__def"); + let opened = def.and_then(|def| def.get(key)).and_then(Value::as_f64); + let unset = def.and_then(|def| def.get(def_max)).is_none_or(Value::is_null); + if d.bool(super::brush_options::OBJECT) && unset && opened == Some(v) { Value::Null } else { json!(v) } +} + +/// The second value field `max_key` (enabled only for a mode that follows the pen) and the +/// [`PEN_SIZE_MODES`] menu `mode_key` of a row labeled `label` (an art brush's Width, a pattern +/// brush's Scale), at `mode`. Screen readers call them `label` and Maximum, and `label` and Mode. +fn pen_mode_controls(ui: &mut egui::Ui, d: &mut Dialog, label: &str, (max_key, mode_key): (&str, &str), range: (f64, f64), mode: Variation) { + let max_name = format!("{label} {}", tl!("Maximum")); + ui.add_enabled_ui(mode.follows_pen(), |ui| { + let v = clamped(d, max_key, range); + if let Some(v) = widgets::range_field_named(ui, ("brush-art-value", max_key), Some(&max_name), v, range.0..=range.1, "%", 0, 72.0) { + d.fields.insert(max_key.into(), json!(v)); + } + }); + let mode_name = format!("{label} {}", tl!("Mode")); + let labels = PEN_SIZE_MODES.map(Variation::label); + let picked = widgets::dropdown_named(ui, ("brush-pen-mode", mode_key), Some(&mode_name), mode.label(), &labels, 104.0); + if let Some(m) = picked.and_then(|i| PEN_SIZE_MODES.get(i)) { + d.fields.insert(mode_key.into(), json!(m.id())); + } +} + +/// The modes an art brush's width and a pattern brush's scale offer, in menu order. +const PEN_SIZE_MODES: [Variation; 6] = + [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + /// `brush.options` params from the fields. pub(super) fn params(d: &Dialog) -> Value { let mut p = match d.str("__type").as_str() { @@ -287,7 +332,7 @@ pub(super) fn params(d: &Dialog) -> Value { json!({ "width": clamped(d, "width", ArtBrush::WIDTH_RANGE), "width_mode": if pen { json!(mode.id()) } else { Value::Null }, - "width_max": if pen { json!(clamped(d, "widthMax", ArtBrush::WIDTH_RANGE)) } else { Value::Null }, + "width_max": if pen { second_value(d, ("width", "widthMax", "width_max"), ArtBrush::WIDTH_RANGE) } else { Value::Null }, "scale": serde_json::to_value(scale).unwrap_or_default(), "direction": id_of(&parse_field::(d, "direction")), "flip_along": d.bool("flipAlong"), @@ -296,8 +341,12 @@ pub(super) fn params(d: &Dialog) -> Value { }) } _ => { + let mode = pattern_scale_mode(d); + let pen = mode.follows_pen(); let mut p = json!({ "scale": clamped(d, "scale", PatternBrush::SCALE_RANGE), + "scale_mode": if pen { json!(mode.id()) } else { Value::Null }, + "scale_max": if pen { second_value(d, ("scale", "scaleMax", "scale_max"), PatternBrush::SCALE_RANGE) } else { Value::Null }, "spacing": clamped(d, "spacing", PatternBrush::SPACING_RANGE), "fit": id_of(&parse_field::(d, "fit")), "flip_along": d.bool("flipAlong"), @@ -410,13 +459,6 @@ fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, range: (f64, f64), suffi }); } -/// A row labeled `label` with a slider and a whole-number field (%) bound to `d.fields[key]`, both -/// kept within `range`; screen readers call the slider `label`. -fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, range: (f64, f64)) { - let rail = Tokens::get(ui.ctx()).input_border; - widgets::label_row(ui, label, LABEL_W, |ui| super::form::slider_field_named(ui, d, key, label, range.0..=range.1, "%", &|_| rail)); -} - /// A row of radio buttons bound to the string field `key`: (value, label). fn radios(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]) { let cur = d.str(key); @@ -472,12 +514,7 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { let range = ArtBrush::WIDTH_RANGE; widgets::label_row(ui, tl!("Width:"), LABEL_W, |ui| { super::form::slider_field_named(ui, d, "width", tl!("Width:"), range.0..=range.1, "%", &|_| rail); - let mode = art_width_mode(d); - number(ui, d, "widthMax", range, "%", mode.follows_pen()); - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; - if let Some(m) = widgets::dropdown(ui, "brush-art-width-mode", mode.label(), &modes.map(Variation::label), 104.0).and_then(|i| modes.get(i)) { - d.fields.insert("widthMode".into(), json!(m.id())); - } + pen_mode_controls(ui, d, tl!("Width:"), ("widthMax", "widthMode"), range, art_width_mode(d)); }); // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. if d.bool(super::brush_options::OBJECT) { @@ -543,7 +580,13 @@ fn arrow_button(ui: &mut egui::Ui, dir: Direction, selected: bool, tip: &str) -> } fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { - slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); + // Scale, then the second scale (only when the scale follows the pen) and how it varies. + let rail = Tokens::get(ui.ctx()).input_border; + let range = PatternBrush::SCALE_RANGE; + widgets::label_row(ui, tl!("Scale:"), LABEL_W, |ui| { + super::form::slider_field_named(ui, d, "scale", tl!("Scale:"), range.0..=range.1, "%", &|_| rail); + pen_mode_controls(ui, d, tl!("Scale:"), ("scaleMax", "scaleMode"), range, pattern_scale_mode(d)); + }); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index de59668708..e57008e2c4 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -323,6 +323,53 @@ fn art_options_width_follows_tilt_bearing_and_rotation() { } } +/// Pattern Brush Options' Scale menu: Pressure, Tilt, Bearing, Rotation and Stylus Wheel each take +/// a second scale, a stroke drawn without the pen's input is half way between the two, and the +/// dialog shows the mode set when it opens again; Fixed drops the second scale. +#[test] +fn pattern_options_scale_follows_the_pen() { + let mut app = app(); + let (id, before) = brushed(&mut app, "Diamonds"); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), ("fixed".into(), 100.0)); + assert!(shown(&mut app).contains("Fixed")); + // Screen readers name the second scale and the menu after the Scale row. + let nodes = crate::widgets::accessibility_tests::tree(|ui| super::super::show(&mut app, ui.ctx())); + assert!(nodes.iter().any(|n| n.label() == Some("Scale: Mode") && n.role() == egui::accesskit::Role::ComboBox), "a menu named Scale: Mode"); + assert!(nodes.iter().any(|n| n.label() == Some("Scale: Maximum")), "a field named Scale: Maximum"); + super::super::cancel(&mut app); + for (mode, label) in + [("pressure", "Pressure"), ("tilt", "Tilt"), ("bearing", "Bearing"), ("rotation", "Rotation"), ("stylusWheel", "Stylus Wheel")] + { + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": mode, "scaleMax": 300})); + assert!(shown(&mut app).contains(label), "{mode}"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(100.0), &json!(mode), &json!(300.0)), "{mode}"); + // A stroke drawn without the pen's input is half way: 200 %. + let after = drawn_height(&app, id); + assert!((after - 2.0 * before).abs() < 0.01 * before, "{mode}: {before} then {after}"); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), (mode.into(), 300.0), "{mode}"); + super::super::cancel(&mut app); + } + // A second scale past the range is kept within it. + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": "pressure", "scaleMax": 1e9})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale_max"], json!(10000.0)); + // Fixed drops the second scale, and the stroke draws as it did. + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": "fixed"})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!((drawn_height(&app, id) - before).abs() < 1e-6); +} + /// A context with the app's fonts and theme, for [`frame`]. fn ctx() -> egui::Context { let ctx = egui::Context::default(); @@ -933,6 +980,47 @@ fn options_of_selected_object_set_one_paths_art_brush_settings() { assert_eq!(own_options(&app, a), json!({"width": 50.0})); } +/// Options of Selected Object for a pattern brush sets one path's Scale mode and second scale; the +/// brush and the other path keep theirs. +#[test] +fn options_of_selected_object_set_one_paths_pattern_scale_mode() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Diamonds"); + let b = brushed_line(&mut app, 100.0, "Diamonds"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert!(shown(&mut app).contains("Scale:")); + set(&mut app, json!({"scaleMode": "tilt", "scaleMax": 250})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale_mode": "tilt", "scale_max": 250.0})); + assert_eq!(own_options(&app, b), json!({})); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none(), "{def}"); + // Opened again, it shows the path's own mode and second scale. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), ("tilt".into(), 250.0)); + super::super::cancel(&mut app); + // With paths of different scales selected, choosing a mode alone leaves each path's scale and + // second scale its own: the first path's scale is not given to the second path as its second + // scale. + app.run("brush.objectOptions", json!({"ids": [a], "params": {"scale": 50, "scale_mode": null, "scale_max": null}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"scale": 80}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scaleMode": "pressure"})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 50.0, "scale_mode": "pressure"})); + assert_eq!(own_options(&app, b), json!({"scale": 80.0, "scale_mode": "pressure"})); + // A changed Scale alone keeps each path's own second scale: its old scale. + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scale": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 50.0})); + assert_eq!(own_options(&app, b), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 80.0})); +} + #[test] fn options_of_selected_object_change_only_the_values_edited_on_each_path() { let mut app = app(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..ff59d0accc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1116,13 +1116,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 37eae066c5..0c3a73b8cc 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -22,7 +22,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | | Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | -| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Pattern and Bristle brushes do not use them (an Art brush's Width follows them); 3–6 h (#372) | +| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | | Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..695528aed5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4127,13 +4127,15 @@ already walks Image Trace. Short agent entry points: level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` (counter-clockwise), `modes`, `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, - `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + `overlap` and `colorization`; pattern `scale`, `scale_mode`, `scale_max`, `spacing`, `fit`, `flip_along`, + `flip_across` and `colorization`. Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + a pattern `scale` without a `scale_max` (omitted or `null`) keeps the second scale of each path whose scale follows the pen, and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different @@ -4169,6 +4171,17 @@ already walks Image Trace. Short agent entry points: desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation code 3. +- Pattern brush scale from the pen: a pattern brush's `scale_mode` (`brush.new`, `brush.options`, + `brush.objectOptions`; left out or `null` for Fixed) takes `pressure`, `tilt`, `bearing`, `rotation` and + `stylusWheel`, and `scale_max` (1..10000%) is the second scale. The tiles go from `scale` where the pen reads 0 to + `scale_max` where it reads 1, over the ranges an Art brush's `width_mode` uses, and half way on a stroke drawn + without that input; without a `scale_max` both ends are `scale`. Each side, start and end tile is as tall as the + scale at each point of the stroke, and the tile and the gap after it are as long as the scale at the tile's + middle. A corner tile takes the scale at its corner. Stretch to Fit then stretches the tiles and gaps of each run + to fill it, Add Space to Fit shares the space left between the tiles, and Approximate Path centers the tiles on + the run. Another mode, such as `random`, is read as Fixed. A brush with a fixed scale draws as before, and a + brush or stroke without the new fields saves without them. `.ai` files do not read or write the pattern scale's + mode. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..13a9b41558 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2053,7 +2053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **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 on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for 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). @@ -2061,6 +2061,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). + Pattern Brush Options' Scale has a menu of Fixed, Pressure, Tilt, Bearing, Rotation and Stylus Wheel with a second scale beside it, in the library brush's dialog and in Options of Selected Object, from the pen tablet options the Pattern brush options section of the help page (, archived copy) lists for Scale (`brush.options` and `brush.objectOptions` `scale_mode` and `scale_max`). The tiles go from Scale where the pen reads 0 to the second scale where it reads 1, over the same ranges as Art Brush Options' Width, and half way on a stroke without that input. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile is as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit stretches the tiles and gaps of each run to fill it, Add Space to Fit shares out what is left between the tiles, and Approximate Path centers them on the run. The help page does not say how the pen maps to the scale or how the tiles are measured along the stroke, so those rules are VectorCraft's own. A brush with a fixed scale draws as before. `.ai` files do not read or write the pattern scale's mode, and the Width tool does not turn the pen's data into width points. Evidence: `tests::pattern_brush_scale_follows_the_pressure`, `tests::pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel`, `tests::pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles` (vectorcraft-brush), `tests::brushsym::options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes`, `tests::brushsym::pattern_brush_scale_mode_goes_through_the_brush_commands` (vectorcraft-engine), `dialogs::brush_options::tests::pattern_options_scale_follows_the_pen`, `dialogs::brush_options::tests::options_of_selected_object_set_one_paths_pattern_scale_mode` (vectorcraft-ui-egui). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; 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). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From c1cdd03b5ce67c1f6a5c06ba5e4c2bc5199c9e1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:24:06 -0800 Subject: [PATCH 017/198] Docs: macOS pen pressure is read; only a check on a Mac with a tablet remains --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 13a9b41558..d47ad77c98 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2053,7 +2053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **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 on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for 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 on Windows and the web, a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation for 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). From 1d12fa1d5fc6dcf08a2a0b2d74e93d737e7216cb Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:13:17 +0100 Subject: [PATCH 018/198] fix(ui): fit translated PDF import labels --- crates/ui-egui/src/dialogs/import_pdf.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index b14cba49cd..db4b8546e4 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -456,7 +456,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.add_space(14.0); ui.vertical(|ui| { - widgets::label_row(ui, tl!("Crop To"), LABEL_WIDTH, |ui| { + let label_width = LABEL_WIDTH.max(widgets::dim_label_width(ui, "Crop To")).max(widgets::dim_label_width(ui, "Text")); + widgets::label_row(ui, tl!("Crop To"), label_width, |ui| { if let Some(i) = widgets::dropdown(ui, "pdf-crop", crop(d).label(), CropTo::LABELS, 130.0) && let Some(id) = CropTo::IDS.get(i) { @@ -465,7 +466,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.add_space(4.0); let linked = places_linked(d); - widgets::label_row(ui, tl!("Text"), LABEL_WIDTH, |ui| { + widgets::label_row(ui, tl!("Text"), label_width, |ui| { let current = TextAs::ALL.iter().position(|t| *t == text_as(d)).and_then(|i| TEXT_AS_LABELS.get(i)).copied().unwrap_or_default(); let picked = ui.add_enabled_ui(!linked, |ui| widgets::dropdown(ui, "pdf-text-as", current, &TEXT_AS_LABELS, 130.0)).inner; if let Some(t) = picked.and_then(|i| TextAs::ALL.get(i)) { From c3ea4e2f9cca7a2250b47c428ec93a25e5629b24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:14:17 -0800 Subject: [PATCH 019/198] Scripts: build and show ScriptUI dialogs with new Window("dialog") A script can now build a modal dialog with new Window("dialog", title) and add() groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars. The engine checks the description and lays it out without recursion, within VectorCraft's own limits (512 controls 16 deep, 1024 list items, 16 KiB a text, sizes clamped to 8192 px). Other control types, palettes and resource strings throw that they are not available yet. - show() waits like alert, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button or 2 for the cancel button, or 0 for the close box. A show() inside a handler throws. - In the app the dialog draws the controls where the engine placed them, gives text still typed in a field before a click or a close, and keeps its state while a handler runs. Enter clicks the default button, Escape the cancel button, and Stop ends the run and puts the documents back. - A run over MCP or the command line takes a window answer: the steps of one show(), each a click, a change or a close. - The report lists each dialog with its controls, events and result; vc.api.has("scriptui") is true. Docs: docs/mcp.md (script.run), docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 165 ++- crates/engine/src/script/mod.rs | 22 +- crates/engine/src/script/scriptui.rs | 666 +++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_scriptui.rs | 365 ++++++ .../tests/it/script_host_vs_scriptcheck.rs | 8 +- crates/js/src/file_classes.rs | 1 + crates/js/src/interp.rs | 80 +- crates/js/src/lib.rs | 3 + crates/js/src/realm.rs | 14 + crates/js/src/scriptui.rs | 1026 +++++++++++++++++ crates/js/src/scriptui_tests.rs | 309 +++++ crates/ui-egui/src/dialogs.rs | 12 +- crates/ui-egui/src/dialogs/script_run.rs | 6 +- crates/ui-egui/src/dialogs/script_window.rs | 360 ++++++ crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 13 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/script_runs.rs | 30 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_window.rs | 273 +++++ docs/mcp.md | 71 +- docs/target-app-parity.md | 1 + 47 files changed, 3455 insertions(+), 74 deletions(-) create mode 100644 crates/engine/src/script/scriptui.rs create mode 100644 crates/engine/src/tests/script_scriptui.rs create mode 100644 crates/js/src/scriptui.rs create mode 100644 crates/js/src/scriptui_tests.rs create mode 100644 crates/ui-egui/src/dialogs/script_window.rs create mode 100644 crates/ui-egui/src/tests/script_window.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..fd02b3a9a1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..4c0ce4a39b 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -23,6 +23,7 @@ use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; /// The most bytes (UTF-8) of a dialog's message. @@ -48,6 +49,8 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// A ScriptUI dialog's `show()` ([`super::scriptui`]). + Window, } impl DialogKind { @@ -57,6 +60,7 @@ impl DialogKind { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::Window => "window", } } } @@ -85,6 +89,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. + Window(Vec), } impl DialogAnswer { @@ -93,13 +99,14 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::Window(_) => DialogKind::Window, } } /// What the function returns. fn data(&self) -> Data { match self { - Self::Ok => Data::Undefined, + Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, @@ -112,6 +119,7 @@ impl DialogAnswer { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::Window(steps) => json!(steps.len()), } } } @@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter -/// took before dialogs existed, is an empty list. +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an +/// empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result, Stri list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() } -fn answer(a: &Value) -> Result { - let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) }; if o.len() != 2 || !o.contains_key("value") { - return Err("must have exactly `kind` and `value`"); + return Err("must have exactly `kind` and `value`".into()); } + if o.get("kind").and_then(Value::as_str) == Some("window") { + return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window); + } + known_answer(o).map_err(String::from) +} + +fn known_answer(o: &Map) -> Result { match (o.get("kind").and_then(Value::as_str), &o["value"]) { (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), @@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + _ => Err("must have `kind` alert, confirm, prompt or window"), } } @@ -199,6 +215,12 @@ pub(crate) struct Dialogs { record_bytes: Cell, count: Cell, truncated: Cell, + /// The ScriptUI dialog whose `show()` is running. + window: RefCell>, + /// That dialog waits for what the person does. + window_waiting: Cell, + /// The `show()` calls the run has made. + shows: Cell, } impl Dialogs { @@ -213,6 +235,9 @@ impl Dialogs { record_bytes: Cell::new(0), count: Cell::new(0), truncated: Cell::new(false), + window: RefCell::default(), + window_waiting: Cell::new(false), + shows: Cell::new(0), } } @@ -222,7 +247,118 @@ impl Dialogs { } pub(crate) fn is_waiting(&self) -> bool { - self.waiting.borrow().is_some() + self.waiting.borrow().is_some() || self.window_waiting.get() + } + + /// The ScriptUI dialog that waits for what the person does. + pub(crate) fn waiting_window(&self) -> Option { + if !self.window_waiting.get() { + return None; + } + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. + pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { + if !self.window_waiting.get() { + return Err("no script dialog waits".into()); + } + let event = { + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) }; + let event = scriptui::check_event(&showing.dialog, event)?; + showing.events = showing.events.saturating_add(1); + event + }; + self.window_waiting.set(false); + if let Err(e) = realm.answer(event.data()) { + *self.failed.borrow_mut() = Some(e); + } + Ok(()) + } + + fn cannot_wait(&self) -> Result<(), HostError> { + if self.framed && !self.can_wait.get() { + return Err(HostError::Error( + "show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + .into(), + )); + } + Ok(()) + } + + /// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a + /// `window` answer. + pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> { + self.cannot_wait()?; + self.shows.set(self.shows.get().saturating_add(1)); + dialog.shown = self.shows.get(); + let mut showing = Showing { dialog, steps: None, events: 0 }; + if !self.framed { + let next = self.answers.borrow_mut().pop_front(); + match next { + Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()), + Some(a) => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id()))); + } + None => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into())); + } + } + } + *self.window.borrow_mut() = Some(showing); + Ok(()) + } + + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the + /// next step of its answer. + pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { + self.cannot_wait()?; + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) }; + dialog.shown = showing.dialog.shown; + showing.dialog = dialog; + let Some(steps) = showing.steps.as_mut() else { + drop(window); + self.window_waiting.set(true); + return Err(HostError::Wait); + }; + let failure = match steps.pop_front() { + None => "show: the dialog's answer in `answers` has no step left".to_string(), + Some(step) => match scriptui::step_event(&showing.dialog, &step) { + Ok(event) => { + showing.events = showing.events.saturating_add(1); + return Ok(event.data()); + } + Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"), + }, + }; + if let Some(showing) = window.take() { + self.push_record(showing.record(json!("missing"))); + } + Err(HostError::Abort(failure)) + } + + /// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask + /// must have used every step of the dialog's answer. + pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> { + self.window_waiting.set(false); + let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; + let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + if normal && left > 0 { + self.push_record(showing.record(json!("missing"))); + let steps = if left == 1 { "step" } else { "steps" }; + return Err(HostError::Abort(format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"))); + } + let answer = match result { + _ if !normal => json!("error"), + r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), + r => json!(r), + }; + self.push_record(showing.record(answer)); + Ok(()) } /// The error that ended the run when its answer could not reach the script. @@ -257,10 +393,13 @@ impl Dialogs { if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } + self.window_waiting.set(false); + if let Some(showing) = self.window.borrow_mut().take() { + self.push_record(showing.record(json!("stop"))); + } } fn record(&self, d: &ScriptDialog, answer: Value) { - self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); r.insert("message".into(), json!(d.message)); @@ -269,9 +408,14 @@ impl Dialogs { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::Window => None, }; r.insert("answer".into(), answer); - let r = Value::Object(r); + self.push_record(Value::Object(r)); + } + + fn push_record(&self, r: Value) { + self.count.set(self.count.get().saturating_add(1)); let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); let mut records = self.records.borrow_mut(); if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { @@ -325,6 +469,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; (text(args, 2), false, false, preset) } + DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())), }; if message.len() > MAX_MESSAGE_BYTES { return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..293d77c716 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -52,8 +52,10 @@ pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -133,7 +135,7 @@ impl Written { /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -1822,6 +1824,23 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run + /// asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_window(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() + } + + /// Gives the ScriptUI dialog the running script waits at `event`; the next + /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still + /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). + pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) }; + with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into())) + } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no /// longer waits. @@ -2076,6 +2095,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs new file mode 100644 index 0000000000..62cfaade79 --- /dev/null +++ b/crates/engine/src/script/scriptui.rs @@ -0,0 +1,666 @@ +//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run +//! gives when it shows one, checked and laid out here before the app draws it, and the events the +//! person or `script.run`'s `answers` give back. +//! +//! A description lists the dialog first and each control after the container that holds it. It is +//! refused with an error thrown at `show()` when a control's container comes after it or is not a +//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than +//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`], +//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its +//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's +//! or progress bar's value to its range. +//! +//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` and `bounds` (left, top, right +//! and bottom in its container). A control's size comes from its text, items and kind, by +//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out +//! with loops over the list, from the last control to the first for sizes and from the first to the +//! last for places, so a description's nesting takes no native stack. +//! +//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window", +//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change", +//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an +//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog +//! waits it takes the next step; a dialog that waits with no step left, a step for a control the +//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run. +//! +//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`], +//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`]. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; + +use super::Host; + +/// The largest size or place, in pixels, of a dialog or a control in it. +pub const MAX_EXTENT: f32 = 8192.0; +/// A character's width and a line's height in VectorCraft's size estimates, in pixels. +const CHAR: f32 = 7.0; +const LINE: f32 = 16.0; + +/// A dialog's element. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UiKind { + Dialog, + Group, + Panel, + StaticText, + EditText, + Button, + CheckBox, + RadioButton, + DropDownList, + ListBox, + Slider, + ProgressBar, +} + +impl UiKind { + fn parse(s: &str) -> Option { + Some(match s { + "dialog" => Self::Dialog, + "group" => Self::Group, + "panel" => Self::Panel, + "statictext" => Self::StaticText, + "edittext" => Self::EditText, + "button" => Self::Button, + "checkbox" => Self::CheckBox, + "radiobutton" => Self::RadioButton, + "dropdownlist" => Self::DropDownList, + "listbox" => Self::ListBox, + "slider" => Self::Slider, + "progressbar" => Self::ProgressBar, + _ => return None, + }) + } + + /// Does it hold controls? + pub fn container(self) -> bool { + matches!(self, Self::Dialog | Self::Group | Self::Panel) + } + + /// Does a click reach it? + pub fn clicks(self) -> bool { + matches!(self, Self::Button | Self::CheckBox | Self::RadioButton) + } +} + +/// How a container places its controls. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Orientation { + Row, + Column, + Stack, +} + +/// Where a control goes across its container: left or top, right or bottom, the middle, or the +/// whole width or height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Align { + Start, + End, + Center, + Fill, +} + +/// A control's place and size in the dialog, from its top left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct UiRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +/// One element of a [`ScriptUiDialog`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UiNode { + pub kind: UiKind, + /// The index of its container; the dialog's own is 0. + pub parent: usize, + pub name: String, + pub text: String, + /// It and every container around it are enabled. + pub enabled: bool, + /// It and every container around it are visible. + pub visible: bool, + /// A check box's or radio button's value. + pub checked: bool, + /// A slider's or progress bar's value, within `min` to `max`. + pub value: f64, + pub min: f64, + pub max: f64, + pub items: Vec, + pub selection: Option, + pub multiline: bool, + pub readonly: bool, + pub rect: UiRect, + orientation: Orientation, + align_children: (Option, Option), + alignment: (Option, Option), + spacing: f32, + margins: [f32; 4], + size: [Option; 2], + bounds: Option, +} + +/// A dialog a run shows, checked and laid out. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptUiDialog { + /// The dialog first, then each control after the container that holds it. + pub nodes: Vec, + /// The button Enter clicks and the one Escape clicks. + pub default_element: Option, + pub cancel_element: Option, + /// Which `show()` of the run this is, counted from 1; 0 before it shows. + pub shown: u64, +} + +impl ScriptUiDialog { + /// The dialog's title. + pub fn title(&self) -> &str { + self.nodes.first().map_or("", |n| n.text.as_str()) + } + + /// The size of the dialog's content. + pub fn size(&self) -> (f32, f32) { + self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) + } + + /// The first control whose name, or else whose text, is `control`. + pub fn find(&self, control: &str) -> Option { + let by = |name: bool| { + self.nodes.iter().enumerate().skip(1).find(|(_, n)| if name { n.name == control } else { n.text == control }).map(|(i, _)| i) + }; + by(true).or_else(|| by(false)) + } +} + +/// A value a control takes in a change. +#[derive(Clone, Debug, PartialEq)] +pub enum UiValue { + Text(String), + Number(f64), + Index(Option), +} + +/// What the person did with a dialog. +#[derive(Clone, Debug, PartialEq)] +pub enum UiEvent { + /// A click on a button, check box or radio button. + Click(usize), + /// A new value for an edit field, a slider or a list. + Change(usize, UiValue), + /// The dialog's close box. + Close, +} + +impl UiEvent { + /// The event as `show()` takes it. + pub(crate) fn data(&self) -> Data { + let event = |e: &str| ("event".to_string(), Data::String(e.into())); + let id = |i: usize| ("id".to_string(), Data::Number(i as f64)); + match self { + Self::Click(i) => Data::Object(vec![event("click"), id(*i)]), + Self::Change(i, v) => { + let value = match v { + UiValue::Text(t) => Data::String(t.clone()), + UiValue::Number(n) => Data::Number(*n), + UiValue::Index(Some(k)) => Data::Number(*k as f64), + UiValue::Index(None) => Data::Null, + }; + Data::Object(vec![event("change"), id(*i), ("value".into(), value)]) + } + Self::Close => Data::Object(vec![event("close")]), + } + } +} + +/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped +/// to its range. +pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result { + let id = match &event { + UiEvent::Close => return Ok(event), + UiEvent::Click(i) | UiEvent::Change(i, _) => *i, + }; + let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) }; + if !n.enabled || !n.visible { + return Err(format!("the control {} is disabled or hidden", label(n))); + } + match event { + UiEvent::Click(_) if n.kind.clicks() => Ok(event), + UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))), + UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => { + if t.len() > MAX_TEXT_BYTES { + return Err("the text is longer than 16 KiB".into()); + } + Ok(UiEvent::Change(id, UiValue::Text(t))) + } + UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => { + Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max)))) + } + UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k { + Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))), + k => Ok(UiEvent::Change(id, UiValue::Index(k))), + }, + UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))), + UiEvent::Close => Ok(UiEvent::Close), + } +} + +fn label(n: &UiNode) -> String { + let shown = if n.name.is_empty() { &n.text } else { &n.name }; + super::dialogs::cut_to(shown, 64).to_string() +} + +/// A step of a `window` answer in `script.run`'s `answers`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UiStep { + /// The control's name or text; none for a close. + pub control: Option, + pub event: String, + pub value: Option, +} + +/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value} +/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a +/// number or null. +pub(crate) fn parse_steps(v: &Value) -> Result, String> { + let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) }; + list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect() +} + +fn step(s: &Value) -> Option { + let o = s.as_object()?; + if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) { + return None; + } + let control = match o.get("control") { + None => None, + Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()), + Some(_) => return None, + }; + let value = o.get("value").cloned(); + let event = o.get("event").and_then(Value::as_str)?; + let fits = match event { + "close" => control.is_none() && value.is_none(), + "click" => control.is_some() && value.is_none(), + "change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)), + _ => false, + }; + fits.then(|| UiStep { control, event: event.to_string(), value }) +} + +/// The event `step` is for `dialog`. +pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result { + let Some(control) = &step.control else { return Ok(UiEvent::Close) }; + let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) }; + let event = match (step.event.as_str(), &step.value) { + ("click", _) => UiEvent::Click(id), + (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match n.as_u64() { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), + (_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)), + _ => return Err("a change's `value` must be a string, a number or null".into()), + }; + check_event(dialog, event) +} + +fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { + fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) +} + +fn bad(what: &str) -> HostError { + HostError::Type(format!("show: the dialog's description {what}")) +} + +/// A finite number. +fn number(d: &Data) -> Option { + match d { + Data::Number(n) if n.is_finite() => Some(*n), + _ => None, + } +} + +fn text(d: &Data, what: &str) -> Result { + match d { + Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()), + Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))), + _ => Err(bad(&format!("has no {what}"))), + } +} + +fn extent(n: f64) -> f32 { + (n as f32).clamp(-MAX_EXTENT, MAX_EXTENT) +} + +fn align_name(s: &str, horizontal: Option) -> Result<(Option, Option), HostError> { + let a = match (s, horizontal) { + ("left", Some(true) | None) => (Some(Align::Start), None), + ("right", Some(true) | None) => (Some(Align::End), None), + ("top", Some(false) | None) => (None, Some(Align::Start)), + ("bottom", Some(false) | None) => (None, Some(Align::End)), + ("center", _) => (Some(Align::Center), Some(Align::Center)), + ("fill", _) => (Some(Align::Fill), Some(Align::Fill)), + _ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))), + }; + Ok(match horizontal { + Some(true) => (a.0, None), + Some(false) => (None, a.1), + None => a, + }) +} + +fn alignment(d: &Data) -> Result<(Option, Option), HostError> { + match d { + Data::Null | Data::Undefined => Ok((None, None)), + Data::String(s) => align_name(s, None), + Data::Array(a) if a.len() == 2 => { + let part = |d: &Data, h: bool| match d { + Data::String(s) => align_name(s, Some(h)), + _ => Err(bad("has an alignment that is not a name")), + }; + Ok((part(&a[0], true)?.0, part(&a[1], false)?.1)) + } + _ => Err(bad("has an alignment that is not a name or a pair of names")), + } +} + +fn numbers(d: &Data) -> Result, HostError> { + match d { + Data::Null | Data::Undefined => Ok(None), + Data::Array(a) if a.len() == N => { + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = number(v).ok_or_else(|| bad("has a size that is not a number"))?; + } + Ok(Some(out)) + } + _ => Err(bad("has a size with the wrong count of numbers")), + } +} + +/// Reads, checks and lays out a dialog's description. +pub fn parse(d: &Data) -> Result { + let Data::Object(top) = d else { return Err(bad("is not an object")) }; + let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) }; + if list.is_empty() { + return Err(bad("has no dialog")); + } + if list.len() > MAX_CONTROLS + 1 { + return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let mut nodes: Vec = Vec::with_capacity(list.len()); + let mut depth: Vec = Vec::with_capacity(list.len()); + let mut items_total = 0usize; + for (i, n) in list.iter().enumerate() { + let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) }; + let kind = match field(f, "kind") { + Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?, + _ => return Err(bad("has a control without a kind")), + }; + let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?; + let parent = if i == 0 { + if kind != UiKind::Dialog || parent != -1.0 { + return Err(bad("does not start with the dialog")); + } + 0 + } else { + let p = parent as usize; + if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog { + return Err(bad("has a control before its container")); + } + if !nodes[p].kind.container() { + return Err(bad("has a control inside a control that holds none")); + } + p + }; + let level = if i == 0 { 0 } else { depth[parent] + 1 }; + if level > MAX_DEPTH { + return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + depth.push(level); + let flag = |name: &str| matches!(field(f, name), Data::Bool(true)); + let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) }; + let items = match field(f, "items") { + Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::, _>>()?, + _ => Vec::new(), + }; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len()); + let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0)); + if min > max { + return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into())); + } + let orientation = match field(f, "orientation") { + Data::String(s) if s == "row" => Orientation::Row, + Data::String(s) if s == "column" => Orientation::Column, + Data::String(s) if s == "stack" => Orientation::Stack, + Data::Undefined => Orientation::Column, + _ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())), + }; + let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| { + let (l, t) = (extent(l), extent(t)); + UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } + }); + let size = numbers::<2>(field(f, "size"))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]); + let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); + nodes.push(UiNode { + kind, + parent, + name: text(field(f, "name"), "a control's name")?, + text: text(field(f, "text"), "a control's text")?, + enabled: flag("enabled") && parent_enabled, + visible: flag("visible") && parent_visible, + checked: flag("value"), + value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max), + min, + max, + items, + selection, + multiline: flag("multiline"), + readonly: flag("readonly"), + rect: UiRect::default(), + orientation, + align_children: alignment(field(f, "alignChildren"))?, + alignment: alignment(field(f, "alignment"))?, + spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), + margins, + size, + bounds, + }); + } + let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); + let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement")); + let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 }; + layout(&mut dialog); + Ok(dialog) +} + +/// A control's own size, by VectorCraft's estimates. +fn own_size(n: &UiNode) -> [f32; 2] { + let chars = |s: &str| s.chars().count() as f32; + let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); + let lines = |s: &str| s.lines().count().max(1) as f32; + let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + match n.kind { + UiKind::StaticText => [widest(&mut n.text.lines()) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], + UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], + UiKind::EditText if n.multiline => [(widest(&mut n.text.lines()) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0], + UiKind::EditText => [(chars(&n.text) * CHAR + 12.0).max(80.0), 24.0], + UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], + UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], + UiKind::Slider => [160.0, 20.0], + UiKind::ProgressBar => [160.0, 12.0], + UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0], + } +} + +/// Lays the dialog out: each control's size from the last to the first, then each place from the +/// first to the last. +fn layout(d: &mut ScriptUiDialog) { + let n = d.nodes.len(); + let mut kids: Vec> = vec![Vec::new(); n]; + for (i, node) in d.nodes.iter().enumerate().skip(1) { + kids[node.parent].push(i); + } + let mut size = vec![[0.0f32; 2]; n]; + for i in (0..n).rev() { + let node = &d.nodes[i]; + let mut s = if node.kind.container() { + let [l, t, r, b] = node.margins; + let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); + for &k in &kids[i] { + if let Some(bounds) = d.nodes[k].bounds { + reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; + continue; + } + let [w, h] = size[k]; + count += 1; + match node.orientation { + Orientation::Row => (main, cross) = (main + w, cross.max(h)), + Orientation::Column => (main, cross) = (main + h, cross.max(w)), + Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)), + } + } + if node.orientation != Orientation::Stack { + main += node.spacing * count.saturating_sub(1) as f32; + } + let (w, h) = match node.orientation { + Orientation::Row | Orientation::Stack => (main, cross), + Orientation::Column => (cross, main), + }; + [(w + l + r).max(reach[0]), (h + t + b).max(reach[1])] + } else { + own_size(node) + }; + for axis in 0..2 { + if let Some(v) = node.size[axis] { + s[axis] = v; + } + } + if let Some(b) = node.bounds { + s = [b.w, b.h]; + } + size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)]; + } + d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] }; + for i in 0..n { + if !d.nodes[i].kind.container() { + continue; + } + let node = d.nodes[i].clone(); + let [l, t, r, b] = node.margins; + let (x, y) = (node.rect.x + l, node.rect.y + t); + let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0)); + let mut cursor = 0.0f32; + for &k in &kids[i] { + let kid = &d.nodes[k]; + let rect = if let Some(bounds) = kid.bounds { + UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } + } else { + let [w, h] = size[k]; + let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); + let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); + let place = |align: Align, own: f32, room: f32| match align { + Align::Start => (0.0, own), + Align::End => ((room - own).max(0.0), own), + Align::Center => (((room - own) / 2.0).max(0.0), own), + Align::Fill => (0.0, room.max(own)), + }; + match node.orientation { + Orientation::Row => { + let (dy, kh) = place(v_align, h, ch); + let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; + cursor += w + node.spacing; + r + } + Orientation::Column => { + let (dx, kw) = place(h_align, w, cw); + let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; + cursor += h + node.spacing; + r + } + Orientation::Stack => { + let (dx, kw) = place(h_align, w, cw); + let (dy, kh) = place(v_align, h, ch); + UiRect { x: x + dx, y: y + dy, w: kw, h: kh } + } + } + }; + d.nodes[k].rect = UiRect { + x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT), + y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT), + w: rect.w.clamp(0.0, MAX_EXTENT), + h: rect.h.clamp(0.0, MAX_EXTENT), + }; + } + } +} + +/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it +/// took. +pub(crate) struct Showing { + pub(crate) dialog: ScriptUiDialog, + pub(crate) steps: Option>, + pub(crate) events: u64, +} + +impl Showing { + /// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`, + /// `"missing"` or `"error"`. + pub(crate) fn record(&self, answer: Value) -> Value { + let mut r = Map::new(); + r.insert("kind".into(), json!("window")); + r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES))); + r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1))); + r.insert("events".into(), json!(self.events)); + r.insert("answer".into(), answer); + Value::Object(r) + } +} + +/// The host function `name` of `Window`, for the run `link` holds. +fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a))) +} + +/// Adds `Window` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) +} + +fn described(host: &Host, args: &[Data]) -> Result { + host.charge_call(args.iter().map(super::data_size).sum())?; + parse(args.first().unwrap_or(&Data::Undefined)) +} + +fn open(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_open(dialog)?; + Ok(Data::Undefined) +} + +fn wait(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_wait(dialog) +} + +fn end(host: &Host, args: &[Data]) -> Result { + let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0); + let normal = matches!(args.get(1), Some(Data::Bool(true))); + host.dialogs.window_end(result, normal)?; + Ok(Data::Undefined) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..58addcd9fe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_scriptui; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs new file mode 100644 index 0000000000..24a6052154 --- /dev/null +++ b/crates/engine/src/tests/script_scriptui.rs @@ -0,0 +1,365 @@ +//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window` +//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the +//! report's `dialogs`. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostError}; + +use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES}; +use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn window(steps: Value) -> Value { + json!([{"kind": "window", "value": steps}]) +} + +const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + +/// A dialog with a field, a check box, a slider, a list and OK and Cancel. +const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \ + g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \ + var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \ + var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = format!( + "{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);" + ); + let steps = json!([ + {"control": "Bold", "event": "click"}, + {"control": "size", "event": "change", "value": 99}, + {"control": "pick", "event": "change", "value": 2}, + {"control": "OK", "event": "click"}, + ]); + let r = headless(&mut s, &source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}"); + assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}])); + let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap(); + assert_eq!(cancel["log"], json!([2])); + let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap(); + assert_eq!(closed["log"], json!([0])); +} + +#[test] +fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"); + for (given, says) in [ + (json!([]), "`answers` has no answer left for this dialog"), + (json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"), + (window(json!([])), "has no step left"), + (window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"), + (window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"), + (window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"), + (window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"), + ] { + let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string(); + assert!(e.contains(says), "{given}: {e}"); + assert_eq!(art(&s), before, "{given}"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } +} + +#[test] +fn window_answers_that_do_not_parse_are_refused_before_the_run() { + let mut s = one_doc(); + let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close"); + for (steps, says) in [ + (json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()), + (json!([1]), bad(0)), + (json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)), + (json!([{"event": "click"}]), bad(0)), + (json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)), + (json!([{"event": "change", "control": "x"}]), bad(0)), + (json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)), + (json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)), + (json!([{"event": "close", "control": "x"}]), bad(0)), + (json!([{"event": "close", "extra": 1}]), bad(0)), + ] { + let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string(); + assert!(e.contains(&says), "{steps}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { + let mut s = one_doc(); + framed( + &mut s, + &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), + ); + let d = s.script_window().expect("show waits"); + assert_eq!(d.title(), "Settings"); + assert_eq!(d.nodes.len(), 9); + assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first")); + let bold = d.find("Bold").unwrap(); + let size = d.find("size").unwrap(); + assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click"); + assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err()); + assert!(s.script_window_answer(UiEvent::Click(99)).is_err()); + s.script_window_answer(UiEvent::Click(bold)).unwrap(); + assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + let d = s.script_window().unwrap(); + assert!(d.nodes[bold].checked); + assert!(!d.nodes[size].enabled, "the handler disabled the slider"); + assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events"); + s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap(); + assert!(pump(&mut s).is_none()); + s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[1, "Ann", 5]])); + assert_eq!(r["dialogs"][0]["events"], 3); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); +} + +#[test] +fn stop_while_show_waits_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');")); + assert!(s.script_window().is_some()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_window(), None, "a run asked to stop no longer waits"); + assert!(s.script_window_answer(UiEvent::Close).is_err()); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); + framed(&mut s, &format!("{EDIT} {FORM} w.show();")); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();"); + let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error"); +} + +#[test] +fn a_show_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a callback").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +fn node(kind: &str, parent: f64) -> Data { + Data::Object(vec![ + ("kind".into(), Data::String(kind.into())), + ("parent".into(), Data::Number(parent)), + ("name".into(), Data::String(String::new())), + ("text".into(), Data::String("t".into())), + ("enabled".into(), Data::Bool(true)), + ("visible".into(), Data::Bool(true)), + ]) +} + +fn description(nodes: Vec) -> Data { + Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(-1.0)), + ("cancelElement".into(), Data::Number(-1.0)), + ]) +} + +fn with(n: Data, name: &str, value: Data) -> Data { + let Data::Object(mut fields) = n else { panic!("a node is an object") }; + fields.retain(|(k, _)| k != name); + fields.push((name.into(), value)); + Data::Object(fields) +} + +fn refused(d: &Data) -> String { + match scriptui::parse(d) { + Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m, + other => panic!("not refused: {other:?}"), + } +} + +#[test] +fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() { + let dialog = node("dialog", -1.0); + assert!(refused(&description(vec![])).contains("has no dialog")); + assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog")); + assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container")); + assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself"); + assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none")); + assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container")); + let many: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect(); + assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls"))); + let deep: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect(); + assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep"))); + let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1))); + assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB")); + let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0)); + assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger")); + let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)])); + assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number")); + let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into())); + assert!(refused(&description(vec![orient])).contains("row, column or stack")); + let align = with(node("button", 0.0), "alignment", Data::String("sideways".into())); + assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways")); +} + +#[test] +fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { + let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4])); + let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0)); + let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)])); + let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)])); + let huge = + with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)])); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap(); + assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height"); + assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0)); + assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row"); + for n in &d.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + } + let (w, h) = d.size(); + assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); +} + +/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and +/// not-a-number ones included) and texts of any length. +fn any_description() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + let kind = prop_oneof![ + Just("dialog"), + Just("group"), + Just("panel"), + Just("statictext"), + Just("edittext"), + Just("button"), + Just("checkbox"), + Just("radiobutton"), + Just("dropdownlist"), + Just("listbox"), + Just("slider"), + Just("progressbar"), + Just("wobble"), + ]; + let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::(), 6 => -50.0..400.0f64]; + let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))]; + let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4)); + let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2)); + // The container is a share of the controls before this one, or with a share past 1, one after it. + let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number); + proptest::collection::vec(fields, 0..40).prop_map(|nodes| { + let mut containers = vec![0usize]; + let mut out = Vec::new(); + for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() { + let kind = if i == 0 { "dialog" } else { kind }; + let parent = match i { + 0 => -1.0, + _ if share >= 1.0 => (i + 1) as f64, + _ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64, + }; + if matches!(kind, "group" | "panel") { + containers.push(i); + } + let numbers = |v: Option>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect())); + let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds)); + n = with(n, "size", numbers(size)); + n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect())); + n = with(n, "selection", Data::Number(value)); + out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value))); + } + description(out) + }) +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))] + + /// Any description is refused with an error or laid out with every place and size finite and + /// within the limit. + #[test] + fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) { + if let Ok(dialog) = scriptui::parse(&d) { + for n in &dialog.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len())); + } + } + } +} + +#[test] +fn an_event_is_checked_against_the_dialog() { + let d = scriptui::parse(&description(vec![ + node("dialog", -1.0), + node("button", 0.0), + with(node("edittext", 0.0), "readonly", Data::Bool(true)), + with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)), + with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])), + with(node("button", 0.0), "visible", Data::Bool(false)), + ])) + .unwrap(); + assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1))); + assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control"); + assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text"); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0)))); + assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err()); + assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err()); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None)))); + assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events"); + assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close)); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..800b0f35df 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -40,10 +40,12 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ]; /// The names the host adds that stay inside the document and the run, by the object that has them. -/// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not +/// change anything outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder Window alert confirm localize prompt toSource"), + ("Window.", "length prototype"), + ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 30de04cf12..f999a59b33 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -617,6 +617,7 @@ fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Val args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], resume: picked, + failed: None, }) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..bd78fa419d 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -193,18 +193,25 @@ pub(crate) type CodeObserver = Rc; pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; /// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the -/// answer, and gives the result of its call. +/// answer, and gives the result of its call. One that puts another [`Pause`] in +/// [`Interp::again`] makes that host call next, and the call's result is what that pause's +/// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; +/// What a [`Pause`] does with its kept values when its host call fails. +pub(crate) type FailFn = fn(&mut Interp, &[Value]); + /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits /// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on /// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +/// When the host call fails, `failed` is given `keep` before the error is thrown at the call. pub(crate) struct Pause { pub(crate) host: Value, pub(crate) args: Vec, pub(crate) keep: Vec, pub(crate) resume: ResumeFn, + pub(crate) failed: Option, } /// A [`Pause`] whose host call waits for its answer. @@ -276,6 +283,10 @@ pub(crate) struct Interp { /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, + /// The next host call a resume function asks for ([`ResumeFn`]). + pub(crate) again: Option, + /// ScriptUI's `Window` and its controls, when the host added them. + pub(crate) script_ui: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -528,6 +539,8 @@ impl Interp { can_wait: Rc::default(), waiting: false, resuming: None, + again: None, + script_ui: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -758,6 +771,7 @@ impl Interp { roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); + roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host)))); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -774,6 +788,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -2487,35 +2502,60 @@ impl Interp { /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host /// function is called as the script's own code calls it, so it may wait; then the resume /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands - /// in for that answer is the call's result for now. + /// in for that answer is the call's result for now. A resume function that asks [`Self::again`] + /// makes that call next, in this loop, so a built-in may ask any number of times. fn ask(&mut self, p: Pause) -> JsResult { - let Pause { host, args, keep, resume } = p; - let mark = self.temp_roots.len(); - self.temp_roots.push(host.clone()); - self.temp_roots.extend(args.iter().cloned()); - self.temp_roots.extend(keep.iter().cloned()); - let was_waiting = self.waiting; - let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), - _ => self.call(&host, &Value::Undefined, &args), - }; - self.temp_roots.truncate(mark); - let answer = answer?; - let r = Resumption { resume, keep }; - if self.waiting && !was_waiting { - self.resuming = Some(r); - return Ok(answer); + let mut p = p; + loop { + let Pause { host, args, keep, resume, failed } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + if answer.is_err() + && let Some(failed) = failed + { + failed(self, &keep); + } + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => p = next, + None => return Ok(v), + } } - self.resume(r, answer) } - /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and + /// makes the host call it asks for next, if any. fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => self.ask(next), + None => Ok(v), + } + } + + fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult { let mark = self.temp_roots.len(); self.temp_roots.push(answer.clone()); self.temp_roots.extend(r.keep.iter().cloned()); let v = (r.resume)(self, &r.keep, answer); self.temp_roots.truncate(mark); + if v.is_err() { + self.again = None; + } v } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c953004550 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -67,6 +67,7 @@ mod realm; mod regexp; mod regexp_builtins; mod regexp_vm; +pub mod scriptui; mod string_builtins; mod token; mod value; @@ -209,6 +210,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod scriptui_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 ee2cd364f8..ad8d10acce 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -256,6 +256,8 @@ impl Realm { interp.host_abort = None; interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -292,6 +294,8 @@ impl Realm { interp.join_stack.clear(); interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -488,6 +492,16 @@ impl Realm { } } + /// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host + /// functions in `items` show: `open` and `wait`, each given the dialog's description, and + /// `end`, given the result of `show()` and whether `show()` ended normally. + pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match crate::scriptui::install(&mut self.interp, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs new file mode 100644 index 0000000000..9afc647960 --- /dev/null +++ b/crates/js/src/scriptui.rs @@ -0,0 +1,1026 @@ +//! ScriptUI's `Window` with modal dialogs, as the help page +//! describes it, whose +//! drawing a host does ([`crate::Realm::define_script_ui`]). +//! +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A +//! window of type `palette` or `window`, and a resource specification in place of the type, throw +//! an `Error` that says they are not available yet. `add(type[, bounds, text, properties])` adds a +//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item +//! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). +//! The other documented control types throw an `Error` that says they are not available yet. A +//! list's `add("item", text)` adds an item; its `selection` is an item or `null`, and takes an +//! item, an index or `null`. +//! +//! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the +//! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the +//! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a +//! `change` with its new value, or a `close`. The control takes the change, its `onClick`, +//! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A +//! button without `onClick` closes the dialog with 1 when it is the dialog's default element and +//! with 2 when it is its cancel element. `close(result)` closes the dialog after the running handler +//! returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps the dialog +//! open when it returns `false`. A dialog that is showing cannot be shown again, and no other dialog +//! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether +//! it ended normally. +//! +//! An element keeps its kind, its container, its controls and a list's items in properties that a +//! script cannot change. The description lists the dialog first and every control after the +//! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] +//! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. + +use crate::HostItem; +use crate::builtins::{arg, constructor, method, native, pausable_method}; +use crate::heap::{Class, ENUMERABLE, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +use crate::host::Data; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; + +/// The most controls a dialog holds, its groups and panels included. +pub const MAX_CONTROLS: usize = 512; +/// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. +pub const MAX_DEPTH: usize = 16; +/// The most items a dialog's lists hold together. +pub const MAX_ITEMS: usize = 1024; +/// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. +pub const MAX_TEXT_BYTES: usize = 16 << 10; + +/// The control types `add` makes. +pub const BUILT: [&str; 11] = + ["group", "panel", "statictext", "edittext", "button", "checkbox", "radiobutton", "dropdownlist", "listbox", "slider", "progressbar"]; +/// The documented control types that are not available yet. +const LATER: [&str; 10] = + ["tabbedpanel", "tab", "scrollbar", "image", "iconbutton", "treeview", "flashplayer", "customview", "custombutton", "customboundedvalue"]; + +const KIND: &str = "__vcKind"; +const PARENT: &str = "__vcParent"; +const WINDOW: &str = "__vcWindow"; +const KIDS: &str = "__vcKids"; +const DEPTH: &str = "__vcDepth"; +const COUNT: &str = "__vcCount"; +const ITEM_COUNT: &str = "__vcItemCount"; +const CLOSING: &str = "__vcClosing"; +const ITEMS: &str = "__vcItems"; +const SELECTION: &str = "__vcSelection"; +const LIST: &str = "__vcList"; + +/// The objects of `Window`, kept by the realm, and the dialog that is showing. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + window_proto: ObjId, + control_proto: ObjId, + item_proto: ObjId, + layout: ObjId, + host: ObjId, + selection_get: ObjId, + selection_set: ObjId, + showing: Option, +} + +impl Classes { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> Vec { + let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; + all.extend(self.showing); + all + } +} + +/// Forgets the dialog that was showing when a run ended where it was. +pub(crate) fn end_run(i: &mut Interp) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = None; + } +} + +fn classes(i: &Interp) -> JsResult { + i.script_ui.clone().ok_or_else(|| Abrupt::Internal("Window is not installed".into())) +} + +fn error(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Error, message) +} + +fn range(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Range, message) +} + +/// The value of the own data property `name` of `o`, `undefined` when it has none. +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +/// Sets the property `name` of `o` that a script can read but not change. +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +/// Sets the property `name` of `o` that a script can change. +fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: OPEN }) +} + +fn number_slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match slot(i, o, name)? { + Value::Number(n) => n, + _ => 0.0, + }) +} + +fn object_slot(i: &Interp, o: ObjId, name: &str) -> JsResult> { + Ok(slot(i, o, name)?.as_object()) +} + +/// An element's kind, or `None` for a value that is not a ScriptUI window or control. +fn kind_of(i: &Interp, v: &Value) -> JsResult> { + let Some(o) = v.as_object() else { return Ok(None) }; + Ok(match slot(i, o, KIND)? { + Value::String(s) => Some((o, s.to_rust_string())), + _ => None, + }) +} + +/// `this` as an element, or a `TypeError` naming `what`. +fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String)> { + match kind_of(i, this)? { + Some(e) => Ok(e), + None => Err(i.type_error(&format!("{what}: this is not a ScriptUI window or control"))), + } +} + +/// Are `a` and `b` the same object? +fn same(a: &Value, b: &Value) -> bool { + matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) +} + +/// The values of an array made by [`list`]. +fn list_values(i: &Interp, a: ObjId) -> JsResult> { + let length = match &i.object(a)?.class { + Class::Array { length, .. } => *length, + _ => return Ok(Vec::new()), + }; + (0..length) + .map(|n| { + Ok(match i.get_own_property(a, &index_key(n))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) + }) + .collect() +} + +/// A new array holding `items`: one a script cannot change unless `open`. +fn list(i: &mut Interp, items: &[Value], open: bool) -> JsResult { + i.rooted(items, |i| i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len() + 1))))?; + let proto = i.intrinsics.array_proto; + let a = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: open }, Some(proto))); + let flags = if open { OPEN } else { ENUMERABLE }; + for (n, v) in items.iter().enumerate() { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + i.define(a, index_key(n), Prop::Data { value: v.clone(), flags })?; + } + i.object_mut(a)?.extensible = open; + Ok(a) +} + +/// Adds `v` to the end of the list in `o`'s slot `name`, and puts a copy a script can change in +/// its property `public`. +fn append(i: &mut Interp, o: ObjId, name: &str, public: &str, v: Value) -> JsResult<()> { + let mut items = match object_slot(i, o, name)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + items.push(v); + i.rooted(&items.clone(), |i| { + let kept = list(i, &items, false)?; + set_slot(i, o, name, Value::Object(kept))?; + let copy = list(i, &items, true)?; + set_open(i, o, public, Value::Object(copy)) + }) +} + +fn text_arg(i: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => Value::str(""), + v => Value::String(i.to_str(v)?), + }) +} + +/// A new element of `kind`, with the properties every element has. +fn new_element( + i: &mut Interp, + proto: ObjId, + kind: &str, + parent: Option, + window: Option, + depth: usize, + args: [&Value; 3], +) -> JsResult { + let [bounds, text, props] = args; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(32)))?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(o)); + let window = window.unwrap_or(o); + let parent = parent.map_or(Value::Null, Value::Object); + let layout = classes(i)?.layout; + set_slot(i, o, KIND, Value::str(kind))?; + set_slot(i, o, PARENT, parent.clone())?; + set_slot(i, o, WINDOW, Value::Object(window))?; + set_slot(i, o, DEPTH, Value::Number(depth as f64))?; + set_open(i, o, "type", Value::str(kind))?; + set_open(i, o, "parent", parent)?; + set_open(i, o, "window", Value::Object(window))?; + let text = text_arg(i, text)?; + set_open(i, o, "text", text)?; + let props = match props { + Value::Object(_) => props.clone(), + _ => Value::Object(i.new_object()), + }; + set_open(i, o, "properties", props.clone())?; + let name = i.get_value(&props, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + set_open(i, o, "enabled", Value::Bool(true))?; + set_open(i, o, "visible", Value::Bool(true))?; + if !matches!(bounds, Value::Undefined | Value::Null) { + set_open(i, o, "bounds", bounds.clone())?; + } + set_open(i, o, "layout", Value::Object(layout))?; + if matches!(kind, "dialog" | "group" | "panel") { + let kids = list(i, &[], false)?; + set_slot(i, o, KIDS, Value::Object(kids))?; + let children = list(i, &[], true)?; + set_open(i, o, "children", Value::Object(children))?; + set_open(i, o, "orientation", Value::str(if kind == "group" { "row" } else { "column" }))?; + set_open(i, o, "alignChildren", Value::str("center"))?; + set_open(i, o, "spacing", Value::Number(10.0))?; + set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?; + } + Ok(o) +} + +/// `new Window(type[, title, bounds, properties])`. +fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = i.to_str(&arg(args, 0))?.to_rust_string(); + if kind.contains('{') { + return Err(error(i, "Window: resource specifications are not available yet; build the dialog with add()")); + } + let lower = kind.to_lowercase(); + if lower == "palette" || lower == "window" { + return Err(error(i, &format!("Window: a window of type {lower} is not available yet; use dialog"))); + } + if lower != "dialog" { + return Err(error(i, "Window: the type must be dialog, palette or window")); + } + let proto = classes(i)?.window_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let o = new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?; + set_slot(i, o, COUNT, Value::Number(0.0))?; + set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; + Ok(Value::Object(o)) + })(); + i.temp_roots.truncate(mark); + r +} + +fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if !n.is_finite() { + return Err(range(i, &format!("{what} is not a finite number"))); + } + Ok(n) +} + +/// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. +fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "add")?; + let ty = i.to_str(&arg(args, 0))?.to_rust_string(); + if kind == "dropdownlist" || kind == "listbox" { + if ty.to_lowercase() != "item" { + return Err(error(i, "add: a list holds only items")); + } + return add_item(i, o, &arg(args, 1)); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + return Err(error(i, &format!("add: a {kind} holds no controls"))); + } + if ty.contains('{') { + return Err(error(i, "add: resource specifications are not available yet; add each control by its type")); + } + let ty = ty.to_lowercase(); + if LATER.contains(&ty.as_str()) { + return Err(error(i, &format!("add: the control type {ty} is not available yet"))); + } + let Some(&ty) = BUILT.iter().find(|b| **b == ty) else { return Err(error(i, &format!("add: there is no control type {ty}"))) }; + let depth = number_slot(i, o, DEPTH)? as usize + 1; + if depth > MAX_DEPTH { + return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a control without its window".into())) }; + let count = number_slot(i, win, COUNT)?; + if count as usize >= MAX_CONTROLS { + return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let props = arg(args, 3); + let list_kind = ty == "dropdownlist" || ty == "listbox"; + if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { + return Err(error(i, "add: a list box that selects several items is not available yet")); + } + let proto = classes(i)?.control_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() }; + let text = if list_kind || matches!(ty, "slider" | "progressbar") { Value::Undefined } else { arg(args, 2) }; + let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?; + match ty { + "checkbox" | "radiobutton" => set_open(i, c, "value", Value::Bool(false))?, + "slider" | "progressbar" => { + let (value, min, max) = + if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) }; + let given = |v: &Value| !matches!(v, Value::Undefined); + let value = if given(&value) { number_arg(i, &value, "add: the value")? } else { 0.0 }; + let min = if given(&min) { number_arg(i, &min, "add: the minimum value")? } else { 0.0 }; + let max = if given(&max) { number_arg(i, &max, "add: the maximum value")? } else { 100.0 }; + set_open(i, c, "minvalue", Value::Number(min))?; + set_open(i, c, "maxvalue", Value::Number(max))?; + set_open(i, c, "value", Value::Number(value))?; + } + "dropdownlist" | "listbox" => { + let kept = list(i, &[], false)?; + set_slot(i, c, ITEMS, Value::Object(kept))?; + set_slot(i, c, SELECTION, Value::Number(-1.0))?; + let items = list(i, &[], true)?; + set_open(i, c, "items", Value::Object(items))?; + let cl = classes(i)?; + i.define(c, key("selection"), Prop::Accessor { get: Some(cl.selection_get), set: Some(cl.selection_set), flags: ENUMERABLE })?; + } + _ => {} + } + if list_kind { + match arg(args, 2) { + Value::Undefined | Value::Null => {} + Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { + for item in list_values(i, a)? { + add_item(i, c, &item)?; + } + } + _ => return Err(i.type_error("add: give a list's items as an array")), + } + } + append(i, o, KIDS, "children", Value::Object(c))?; + set_slot(i, win, COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(c)) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Adds an item with `text` to the list `o`. +fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + if count as usize >= MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let text = text_arg(i, text)?; + let proto = classes(i)?.item_proto; + i.rooted(std::slice::from_ref(&text), |i| { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(item)], |i| { + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + append(i, o, ITEMS, "items", Value::Object(item))?; + set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(item)) + }) + }) +} + +fn list_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dropdownlist" || kind == "listbox" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a list"))), + } +} + +fn items_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, ITEMS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +fn selection_index(i: &Interp, o: ObjId) -> JsResult> { + let n = number_slot(i, o, SELECTION)?; + Ok((n >= 0.0).then_some(n as usize)) +} + +fn selection_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + Ok(selection_index(i, o)?.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +fn selection_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + let v = arg(args, 0); + let n = match &v { + Value::Undefined | Value::Null => -1.0, + Value::Number(n) if n.fract() == 0.0 && *n >= 0.0 && (*n as usize) < items.len() => *n, + Value::Number(n) => return Err(range(i, &format!("selection: the list has no item {n}"))), + v => match items.iter().position(|item| same(item, v)) { + Some(n) => n as f64, + None => return Err(i.type_error("selection: give an item of this list, its index or null")), + }, + }; + set_slot(i, o, SELECTION, Value::Number(n))?; + Ok(Value::Undefined) +} + +/// The list an item belongs to and its index there. +fn item_place(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Option)> { + let list = match this.as_object() { + Some(o) => object_slot(i, o, LIST)?, + None => None, + }; + let Some(list) = list else { return Err(i.type_error(&format!("{what}: this is not a list item"))) }; + let index = items_of(i, list)?.iter().position(|item| same(item, this)); + Ok((list, index)) +} + +fn item_index(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, index) = item_place(i, &this, "index")?; + Ok(Value::Number(index.map_or(-1.0, |n| n as f64))) +} + +fn item_selected_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + Ok(Value::Bool(index.is_some() && selection_index(i, list)? == index)) +} + +fn item_selected_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + let Some(index) = index else { return Ok(Value::Undefined) }; + if arg(args, 0).truthy() { + set_slot(i, list, SELECTION, Value::Number(index as f64))?; + } else if selection_index(i, list)? == Some(index) { + set_slot(i, list, SELECTION, Value::Number(-1.0))?; + } + Ok(Value::Undefined) +} + +fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + item_place(i, &this, "toString")?; + let text = i.get_value(&this, &key("text"))?; + Ok(Value::String(i.to_str(&text)?)) +} + +/// `list.removeAll()`. +fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "removeAll")?; + let n = items_of(i, o)?.len() as f64; + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; + let kept = list(i, &[], false)?; + set_slot(i, o, ITEMS, Value::Object(kept))?; + let items = list(i, &[], true)?; + set_open(i, o, "items", Value::Object(items))?; + set_slot(i, o, SELECTION, Value::Number(-1.0))?; + Ok(Value::Undefined) +} + +fn kids_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, KIDS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +/// `findElement(name)`: the first control in the element, in order, whose `name` is `name`. +fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "findElement")?; + let want = i.to_str(&arg(args, 0))?; + let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(c) = v.as_object() else { continue }; + let name = i.get_value(&v, &key("name"))?; + if matches!(&name, Value::String(s) if *s == want) { + return Ok(v); + } + stack.extend(kids_of(i, c)?.into_iter().rev()); + } + Ok(Value::Null) +} + +/// Calls the element's handler `name` when it has one. → its result, or `None` without one. +fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult> { + let f = i.get_value(&Value::Object(o), &key(name))?; + if !i.is_callable(&f) { + return Ok(None); + } + i.call(&f, &Value::Object(o), &[]).map(Some) +} + +/// `notify([event])`: runs the control's `onClick`, `onChange` or `onChanging`. +fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "notify")?; + let event = match arg(args, 0) { + Value::Undefined if matches!(kind.as_str(), "button" | "checkbox" | "radiobutton") => "onClick".to_string(), + Value::Undefined => "onChange".to_string(), + v => i.to_str(&v)?.to_rust_string(), + }; + if !matches!(event.as_str(), "onClick" | "onChange" | "onChanging") { + return Err(error(i, "notify: give onClick, onChange or onChanging")); + } + handler(i, o, &event)?; + Ok(Value::Undefined) +} + +fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "show")?; + i.put(o, key("visible"), Value::Bool(true), true)?; + Ok(Value::Undefined) +} + +fn control_hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "hide")?; + i.put(o, key("visible"), Value::Bool(false), true)?; + Ok(Value::Undefined) +} + +fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Undefined) +} + +fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dialog" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), + } +} + +/// `close([result])`: closes the dialog that is showing once the running handler returns. +fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = dialog_of(i, &this, "close")?; + let result = match arg(args, 0) { + Value::Undefined => 0.0, + v => number_arg(i, &v, "close: the result")?, + }; + if classes(i)?.showing == Some(o) { + set_slot(i, o, CLOSING, Value::Number(result))?; + } + Ok(Value::Undefined) +} + +/// `hide()`: closes the dialog that is showing with the result 0. +fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + close(i, this, &[], false) +} + +fn host_fn(i: &mut Interp, name: &str) -> JsResult { + let host = classes(i)?.host; + i.get_value(&Value::Object(host), &key(name)) +} + +fn set_showing(i: &mut Interp, showing: Option) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = showing; + } +} + +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { + let win = dialog_of(i, &this, "show")?; + match classes(i)?.showing { + Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), + Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), + None => {} + } + set_showing(i, Some(win)); + set_slot(i, win, CLOSING, Value::Undefined)?; + let described = describe(i, win); + let (desc, nodes, def, cancel) = match described { + Ok(d) => d, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; + let open = host_fn(i, "open")?; + Ok(Pause { + host: open, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: opened, + failed: Some(failed), + }) +} + +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. +fn failed(i: &mut Interp, keep: &[Value]) { + let Some(win) = arg(keep, 0).as_object() else { return }; + if classes(i).ok().and_then(|c| c.showing) != Some(win) { + return; + } + set_showing(i, None); + if let Ok(end) = host_fn(i, "end") { + let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + } +} + +/// `show()` ends with `result`. +fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { + set_showing(i, None); + set_slot(i, win, CLOSING, Value::Undefined)?; + let end = host_fn(i, "end")?; + i.call(&end, &Value::Undefined, &[Value::Number(result), Value::Bool(true)])?; + Ok(Value::Number(result)) +} + +/// Runs `onClose`. → false when it returned `false`. +fn may_close(i: &mut Interp, win: ObjId) -> JsResult { + Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) +} + +/// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. +fn next(i: &mut Interp, win: ObjId) -> JsResult { + loop { + i.use_fuel()?; + if let Value::Number(result) = slot(i, win, CLOSING)? { + set_slot(i, win, CLOSING, Value::Undefined)?; + if may_close(i, win)? { + return finish(i, win, result); + } + continue; + } + let (desc, nodes, def, cancel) = describe(i, win)?; + let wait = host_fn(i, "wait")?; + i.again = Some(Pause { + host: wait, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: answered, + failed: Some(failed), + }); + return Ok(Value::Undefined); + } +} + +/// Runs `r`; when it fails, the dialog is no longer showing. +fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let v = r(i); + if v.is_err() { + failed(i, keep); + } + v +} + +fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult { + guarded(i, keep, |i| { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) }; + handler(i, win, "onShow")?; + next(i, win) + }) +} + +/// What the host's `wait` gave: the event, which the dialog takes, and what happens next. +fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + guarded(i, keep, |i| { + let (Some(win), Some(nodes)) = (arg(keep, 0).as_object(), arg(keep, 1).as_object()) else { + return Err(Abrupt::Internal("show lost its dialog".into())); + }; + let Some(ev) = answer.as_object() else { return Err(Abrupt::Internal("the host gave show no event".into())) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + if may_close(i, win)? { + return finish(i, win, 0.0); + } + return next(i, win); + } + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event.as_str() { + "click" => { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + let parent = object_slot(i, c, PARENT)?; + for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { + if !same(&other, &Value::Object(c)) + && let Some((o, k)) = kind_of(i, &other)? + && k == "radiobutton" + { + i.put(o, key("value"), Value::Bool(false), true)?; + } + } + i.put(c, key("value"), Value::Bool(true), true)?; + } + if handler(i, c, "onClick")?.is_none() && kind == "button" { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + handler(i, c, "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + handler(i, c, "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + next(i, win) + }) +} + +fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; + match text { + Some(t) if t.len() <= MAX_TEXT_BYTES => Ok(t), + _ => Err(range(i, &format!("show: {what} is longer than 16 KiB"))), + } +} + +fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + i.get_value(&Value::Object(o), &key(name)) +} + +fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?)) +} + +/// An alignment: a name, or an array of a horizontal and a vertical name; `null` when not set. +fn alignment(i: &mut Interp, v: &Value) -> JsResult { + match v { + Value::Undefined | Value::Null => Ok(Data::Null), + Value::Object(a) if matches!(i.object(*a)?.class, Class::Array { .. }) => { + let mut out = Vec::new(); + for n in 0..2 { + let part = i.get_value(v, &index_key(n))?; + out.push(Data::String(text_of(i, &part, "an alignment")?.to_lowercase())); + } + Ok(Data::Array(out)) + } + v => Ok(Data::String(text_of(i, v, "an alignment")?.to_lowercase())), + } +} + +/// Numbers read from `v`'s indices, or else from its properties `names`. +fn numbers(i: &mut Interp, v: &Value, names: &[&str], what: &str) -> JsResult { + let Some(o) = v.as_object() else { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(Data::Null); + } + return Err(i.type_error(&format!("show: give {what} as an array or an object"))); + }; + let array = matches!(i.object(o)?.class, Class::Array { .. }); + let mut out = Vec::new(); + for (n, name) in names.iter().enumerate() { + let part = if array { i.get_value(v, &index_key(n as u32))? } else { i.get_value(v, &key(name))? }; + out.push(Data::Number(number_arg(i, &part, &format!("show: {what}"))?)); + } + Ok(Data::Array(out)) +} + +/// Bounds as `[left, top, right, bottom]`: from an array, from `x`, `y`, `width` and `height`, or +/// from `left`, `top`, `right` and `bottom`. +fn bounds(i: &mut Interp, v: &Value) -> JsResult { + if let Some(o) = v.as_object() + && !matches!(i.object(o)?.class, Class::Array { .. }) + && !matches!(i.get_value(v, &key("width"))?, Value::Undefined) + { + let Data::Array(xywh) = numbers(i, v, &["x", "y", "width", "height"], "bounds")? else { return Ok(Data::Null) }; + let n = |k: usize| match xywh.get(k) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + } + numbers(i, v, &["left", "top", "right", "bottom"], "bounds") +} + +fn margins(i: &mut Interp, v: &Value) -> JsResult { + if v.as_object().is_some() { + return numbers(i, v, &["left", "top", "right", "bottom"], "margins"); + } + let m = number_arg(i, v, "show: margins")?; + Ok(Data::Array(vec![Data::Number(m); 4])) +} + +/// The dialog's description: its elements in order, each after the container that holds it, as +/// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of +/// its default and cancel elements (-1 for none). +fn describe(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mark = i.temp_roots.len(); + let r = describe_rooted(i, win); + i.temp_roots.truncate(mark); + r +} + +fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mut order: Vec<(ObjId, String, f64)> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; + while let Some((v, parent, depth)) = stack.pop() { + i.use_fuel()?; + let Some((o, kind)) = kind_of(i, &v)? else { return Err(i.type_error("show: the dialog holds something that is not a control")) }; + if !seen.insert(o) { + return Err(i.type_error("show: a control appears twice in the dialog")); + } + if order.len() > MAX_CONTROLS { + return Err(range(i, &format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + if depth > MAX_DEPTH { + return Err(range(i, &format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + let index = order.len() as f64; + order.push((o, kind, parent)); + for kid in kids_of(i, o)?.into_iter().rev() { + stack.push((kid, index, depth + 1)); + } + } + let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); + i.temp_roots.extend(objects.iter().cloned()); + let mut nodes = Vec::with_capacity(order.len()); + let mut names = Vec::with_capacity(order.len()); + let mut items_total = 0usize; + for (o, kind, parent) in &order { + let o = *o; + let name_v = get(i, o, "name")?; + let name = text_of(i, &name_v, "a control's name")?; + let text_v = get(i, o, "text")?; + let text = text_of(i, &text_v, "a control's text")?; + let mut d: Vec<(String, Data)> = vec![ + ("kind".into(), Data::String(kind.clone())), + ("parent".into(), Data::Number(*parent)), + ("name".into(), Data::String(name.clone())), + ("text".into(), Data::String(text.clone())), + ]; + names.push((kind.clone(), name, text)); + let enabled = get(i, o, "enabled")?.truthy(); + let visible = get(i, o, "visible")?.truthy(); + d.push(("enabled".into(), Data::Bool(enabled))); + d.push(("visible".into(), Data::Bool(visible))); + let b = get(i, o, "bounds")?; + d.push(("bounds".into(), bounds(i, &b)?)); + let size = get(i, o, "preferredSize")?; + d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); + let a = get(i, o, "alignment")?; + d.push(("alignment".into(), alignment(i, &a)?)); + if matches!(kind.as_str(), "dialog" | "group" | "panel") { + let orientation = get(i, o, "orientation")?; + d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); + let ac = get(i, o, "alignChildren")?; + d.push(("alignChildren".into(), alignment(i, &ac)?)); + d.push(("spacing".into(), number_of(i, o, "spacing")?)); + let m = get(i, o, "margins")?; + d.push(("margins".into(), margins(i, &m)?)); + } + match kind.as_str() { + "checkbox" | "radiobutton" => { + let on = get(i, o, "value")?.truthy(); + d.push(("value".into(), Data::Bool(on))); + } + "slider" | "progressbar" => { + d.push(("value".into(), number_of(i, o, "value")?)); + d.push(("minvalue".into(), number_of(i, o, "minvalue")?)); + d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?)); + } + "edittext" => { + let props = get(i, o, "properties")?; + let (multiline, readonly) = match props { + Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), + _ => (false, false), + }; + d.push(("multiline".into(), Data::Bool(multiline))); + d.push(("readonly".into(), Data::Bool(readonly))); + } + "dropdownlist" | "listbox" => { + let items = items_of(i, o)?; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(range(i, &format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let mut texts = Vec::with_capacity(items.len()); + for item in &items { + let t = i.get_value(item, &key("text"))?; + texts.push(Data::String(text_of(i, &t, "a list item's text")?)); + } + d.push(("items".into(), Data::Array(texts))); + let sel = selection_index(i, o)?.filter(|n| *n < items.len()); + d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + } + _ => {} + } + nodes.push(Data::Object(d)); + } + let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { + let given = get(i, win, name)?; + if let Some(n) = objects.iter().position(|o| same(o, &given)) { + return Ok(n as f64); + } + if !matches!(given, Value::Undefined | Value::Null) { + return Ok(-1.0); + } + let button = |by_name: bool| names.iter().position(|(k, n, t)| k == "button" && (if by_name { n } else { t }).to_lowercase() == word); + Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + }; + let def = target(i, "defaultElement", "ok")?; + let cancel = target(i, "cancelElement", "cancel")?; + let desc = Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(def)), + ("cancelElement".into(), Data::Number(cancel)), + ]); + let desc = i.write_data(desc, 0, true)?; + i.temp_roots.push(desc.clone()); + let kept = list(i, &objects, false)?; + Ok((desc, kept, def, cancel)) +} + +/// Adds `Window`, its prototype's methods, and the host functions in `items`. +pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { + let host = i.host_object("Window", items)?; + let object_proto = i.intrinsics.object_proto; + i.rooted(&[Value::Object(host)], |i| { + i.reserve_heap(OBJECT_BYTES.saturating_mul(4))?; + let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(window_proto)); + let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(control_proto)); + let item_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(item_proto)); + let layout = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(layout)); + let selection_get = native(i, "selection", selection_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_get)); + let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_set)); + i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; + constructor(i, "Window", window, window_proto)?; + method(i, window_proto, "add", add, 4)?; + method(i, window_proto, "findElement", find_element, 1)?; + method(i, window_proto, "close", close, 1)?; + method(i, window_proto, "hide", hide, 0)?; + method(i, window_proto, "center", nothing, 1)?; + pausable_method(i, window_proto, "show", show, 0)?; + method(i, control_proto, "add", add, 4)?; + method(i, control_proto, "findElement", find_element, 1)?; + method(i, control_proto, "removeAll", remove_all, 0)?; + method(i, control_proto, "notify", notify, 1)?; + method(i, control_proto, "show", control_show, 0)?; + method(i, control_proto, "hide", control_hide, 0)?; + method(i, item_proto, "toString", item_to_string, 0)?; + let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; + i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; + let get = native(i, "selected", item_selected_get, 0, NativeKind::Plain, false)?; + let set = native(i, "selected", item_selected_set, 1, NativeKind::Plain, false)?; + i.define(item_proto, key("selected"), Prop::Accessor { get: Some(get), set: Some(set), flags: 0 })?; + method(i, layout, "layout", nothing, 1)?; + method(i, layout, "resize", nothing, 0)?; + i.object_mut(layout)?.extensible = false; + Ok(()) + }) +} diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs new file mode 100644 index 0000000000..18067d6375 --- /dev/null +++ b/crates/js/src/scriptui_tests.rs @@ -0,0 +1,309 @@ +//! ScriptUI's `Window`: building a dialog, its description, the events a host gives `show()`, the +//! handlers they run, and the limits on what a dialog may hold. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use super::*; + +/// What the host was given: each description, and each `end`'s result and whether it was normal. +#[derive(Default)] +struct Seen { + descriptions: Vec, + ends: Vec<(f64, bool)>, +} + +/// The events `wait` has left to give. +type Queue = Rc>>; + +/// A realm whose `wait` gives the events in `events`, in order, and throws when none is left +/// (or waits, where the run can). +fn realm(events: Vec) -> (Realm, Rc>, Queue) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let seen: Rc> = Rc::default(); + let queue = Rc::new(RefCell::new(VecDeque::from(events))); + let can_wait = r.wait_flag(); + let s = seen.clone(); + let open: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + Ok(Data::Undefined) + }); + let s = seen.clone(); + let q = queue.clone(); + let wait: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + match q.borrow_mut().pop_front() { + Some(e) => Ok(e), + None if can_wait.get() => Err(HostError::Wait), + None => Err(HostError::Error("no event left".into())), + } + }); + let s = seen.clone(); + let end: HostFunction = Rc::new(move |args| { + let n = match args.first() { + Some(Data::Number(n)) => *n, + _ => f64::NAN, + }; + s.borrow_mut().ends.push((n, matches!(args.get(1), Some(Data::Bool(true))))); + Ok(Data::Undefined) + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + (r, seen, queue) +} + +fn click(id: usize) -> Data { + Data::Object(vec![("event".into(), Data::String("click".into())), ("id".into(), Data::Number(id as f64))]) +} + +fn change(id: usize, value: Data) -> Data { + Data::Object(vec![("event".into(), Data::String("change".into())), ("id".into(), Data::Number(id as f64)), ("value".into(), value)]) +} + +fn close() -> Data { + Data::Object(vec![("event".into(), Data::String("close".into()))]) +} + +fn field<'a>(d: &'a Data, name: &str) -> &'a Data { + match d { + Data::Object(fields) => fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v), + _ => &Data::Undefined, + } +} + +fn nodes(d: &Data) -> Vec { + match field(d, "nodes") { + Data::Array(a) => a.clone(), + _ => Vec::new(), + } +} + +/// Every built control, in the order the description lists them: 0 is the dialog. +const FORM: &str = r#" + var w = new Window("dialog", "Form"); + var g = w.add("group"); + var label = g.add("statictext", undefined, "Name:"); + var name = g.add("edittext", undefined, "first"); + var p = w.add("panel", undefined, "Options"); + var check = p.add("checkbox", undefined, "Bold"); + var r1 = p.add("radiobutton", undefined, "A"); + var r2 = p.add("radiobutton", undefined, "B"); + var drop = p.add("dropdownlist", undefined, ["x", "y", "z"]); + var box = p.add("listbox", undefined, ["one", "two"]); + var slide = p.add("slider", undefined, 5, 0, 10); + var bar = p.add("progressbar", undefined, 3, 10); + var ok = w.add("button", undefined, "OK"); + var cancel = w.add("button", undefined, "Cancel", {name: "cancel"}); +"#; + +#[test] +fn a_dialog_with_each_control_gives_back_the_values_the_person_set() { + let events = vec![ + change(3, Data::String("second".into())), + click(5), + click(6), + click(7), + change(8, Data::Number(2.0)), + change(9, Data::Number(1.0)), + change(10, Data::Number(7.5)), + click(12), + ]; + let (mut r, seen, _) = realm(events); + let source = format!( + "{FORM} var result = w.show(); [result, name.text, check.value, r1.value, r2.value, drop.selection.text, box.selection.index, slide.value, bar.value].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|second|true|false|true|z|1|7.5|3".into())); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let kinds: Vec = first + .iter() + .map(|n| match field(n, "kind") { + Data::String(s) => s.clone(), + _ => String::new(), + }) + .collect(); + let want = [ + "dialog", + "group", + "statictext", + "edittext", + "panel", + "checkbox", + "radiobutton", + "radiobutton", + "dropdownlist", + "listbox", + "slider", + "progressbar", + "button", + "button", + ]; + assert_eq!(kinds, want); + assert_eq!(field(&first[3], "parent"), &Data::Number(1.0), "the field is in the group"); + assert_eq!(field(&first[8], "items"), &Data::Array(vec![Data::String("x".into()), Data::String("y".into()), Data::String("z".into())])); + assert_eq!(field(&first[10], "maxvalue"), &Data::Number(10.0)); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(12.0), "OK is the default element by its text"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(13.0), "Cancel is the cancel element by its name"); + assert_eq!(seen.ends, vec![(1.0, true)]); +} + +#[test] +fn the_default_and_cancel_buttons_close_with_1_and_2_and_a_close_gives_0() { + for (event, want) in [(click(12), 1.0), (click(13), 2.0), (close(), 0.0)] { + let (mut r, _, _) = realm(vec![event]); + assert_eq!(r.run(&format!("{FORM} w.show()")).unwrap(), JsValue::Number(want)); + } +} + +#[test] +fn a_button_with_a_handler_does_not_close_the_dialog() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + let source = format!("{FORM} var clicks = 0; ok.onClick = function () {{ clicks++; }}; [w.show(), clicks].join()"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,1".into())); +} + +#[test] +fn close_gives_its_result_and_on_close_can_keep_the_dialog_open() { + let (mut r, seen, _) = realm(vec![click(5), click(5)]); + let source = format!( + "{FORM} var asked = 0; check.onClick = function () {{ w.close(7); }}; w.onClose = function () {{ asked++; return asked > 1; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("7,2".into())); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn close_in_on_show_ends_show_without_waiting() { + let (mut r, seen, _) = realm(Vec::new()); + assert_eq!(r.run(&format!("{FORM} w.onShow = function () {{ w.close(4); }}; w.show()")).unwrap(), JsValue::Number(4.0)); + assert_eq!(seen.borrow().descriptions.len(), 1, "only open saw the dialog"); +} + +#[test] +fn handlers_change_other_controls_and_the_next_description_shows_it() { + let (mut r, seen, _) = realm(vec![click(5), click(12)]); + let source = + format!("{FORM} check.onClick = function () {{ name.text = check.value ? 'on' : 'off'; slide.enabled = false; }}; w.show(); name.text"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("on".into())); + let seen = seen.borrow(); + let after = nodes(&seen.descriptions[2]); + assert_eq!(field(&after[3], "text"), &Data::String("on".into())); + assert_eq!(field(&after[10], "enabled"), &Data::Bool(false)); +} + +#[test] +fn on_change_runs_after_on_changing() { + let (mut r, _, _) = realm(vec![change(3, Data::String("x".into())), click(12)]); + let source = format!( + "{FORM} var log = []; name.onChanging = function () {{ log.push('changing ' + name.text); }}; name.onChange = function () {{ log.push('change'); }}; w.show(); log.join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("changing x,change".into())); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel() { + let (mut r, seen, _) = realm(vec![click(5)]); + r.set_limits(Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run(&format!("{FORM} check.onClick = function () {{ for (;;) {{}} }}; w.show()")).unwrap_err(); + assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}"); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); +} + +#[test] +fn a_dialog_cannot_be_shown_inside_its_own_or_another_show() { + let (mut r, _, _) = realm(vec![click(5), click(12)]); + let source = format!( + "{FORM} var errors = []; check.onClick = function () {{ try {{ w.show(); }} catch (e) {{ errors.push(e.message); }} try {{ new Window('dialog').show(); }} catch (e) {{ errors.push(e.message); }} }}; w.show(); errors.join('|')" + ); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String("show: this dialog is already showing|show: a dialog cannot open while another dialog is showing".into()) + ); +} + +#[test] +fn a_dialog_can_be_shown_again_after_it_closed() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); +} + +#[test] +fn types_that_are_not_available_yet_throw_errors_that_say_so() { + for (source, want) in [ + ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('dialog { b: Button {} }')", "Window: resource specifications are not available yet; build the dialog with add()"), + ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), + ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), + ("new Window('dialog').add('button').add('button')", "add: a button holds no controls"), + ( + "new Window('dialog').add('listbox', undefined, [], {multiselect: true})", + "add: a list box that selects several items is not available yet", + ), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +#[test] +fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { + let (mut r, _, _) = realm(Vec::new()); + let many = + r.run("var w = new Window('dialog'); try { for (var i = 0; i < 100000; i++) w.add('button'); } catch (e) { [e.name, i].join() }").unwrap(); + assert_eq!(many, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS))); + let deep = + r.run("var c = new Window('dialog'); try { for (var d = 0; d < 1000; d++) c = c.add('group'); } catch (e) { [e.name, d].join() }").unwrap(); + assert_eq!(deep, JsValue::String(format!("RangeError,{}", scriptui::MAX_DEPTH))); + let items = r.run("var l = new Window('dialog').add('dropdownlist'); try { for (var n = 0; n < 5000; n++) l.add('item', n); } catch (e) { [e.name, n].join() }").unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS))); + let long = r + .run("var w = new Window('dialog'); w.add('statictext', undefined, new Array(20000).join('x')); try { w.show(); } catch (e) { e.message }") + .unwrap(); + assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into())); +} + +#[test] +fn a_bounds_value_that_is_not_finite_is_refused_when_shown() { + let (mut r, _, _) = realm(Vec::new()); + let v = r.run("var w = new Window('dialog'); w.add('button', [0, 0, Infinity, 20]); try { w.show(); } catch (e) { e.name }").unwrap(); + assert_eq!(v, JsValue::String("RangeError".into())); +} + +#[test] +fn a_script_cannot_change_a_dialog_s_controls_behind_its_back() { + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + w.children.push(w); w.__vcKids = []; try { w.__vcKids.push(w); } catch (e) {} b.__vcKind = 'dialog'; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); +} + +#[test] +fn a_show_that_waits_resumes_with_the_host_s_answer() { + let (mut r, seen, queue) = realm(Vec::new()); + r.start(&format!("{FORM} check.onClick = function () {{ name.text = 'clicked'; }}; var n = w.show(); n + ':' + name.text")).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits at open's first wait"); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits again after the handler"); + queue.borrow_mut().push_back(click(12)); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("1:clicked".into()))); + assert_eq!(seen.borrow().ends, vec![(1.0, true)]); +} + +#[test] +fn findelement_items_and_selection_follow_the_list() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var d = g.add('dropdownlist', undefined, [], {name: 'pick'}); \ + d.add('item', 'a'); var b = d.add('item', 'b'); d.selection = 1; var s1 = d.selection.text; b.selected = false; \ + var s2 = d.selection; d.selection = 0; d.removeAll(); [w.findElement('pick') === d, s1, s2, d.selection, d.items.length, String(b)].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("true,b,,,0,b".into())); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..eba418f360 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -131,6 +131,7 @@ pub mod save_swatch_library; pub mod save_symbol_library; pub mod script_check; pub mod script_run; +pub mod script_window; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; @@ -466,6 +467,7 @@ registry! { ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, + ScriptWindow: [script_window::KIND] => script_window::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, @@ -776,7 +778,7 @@ pub fn cancel(app: &mut VectorcraftApp) { if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { return; } - if let Some(d) = app.ui.dialog.take() { + if let Some(mut d) = app.ui.dialog.take() { if d.kind == "preferences" { crate::original_editor::cancel(app); } @@ -811,6 +813,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } + if d.kind == script_window::KIND { + script_window::cancel(app, &mut d); + } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. if d.kind == recolor::KIND { @@ -830,6 +835,11 @@ pub fn cancel(app: &mut VectorcraftApp) { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); + // A script's ScriptUI dialog stays open, with the text typed in its fields, until the + // script closes it or the run no longer waits at it. + if d.kind == script_window::KIND && app.ui.dialog.is_none() && app.session.script_running() { + app.ui.dialog = Some(d); + } } settle(app); } diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..fcf80916ae 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -194,9 +194,10 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result } /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which -/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +/// Cancel shows again as it was, with the text typed in a ScriptUI dialog's fields. Any other open +/// dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND || d.kind == super::script_window::KIND); if app.ui.dialog.is_some() { return; } @@ -218,6 +219,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { app.ui.dialog = None; } else if app.session.script_dialog().is_none() && app.session.script_picker().is_none() + && app.session.script_window().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs new file mode 100644 index 0000000000..443f3e96cb --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -0,0 +1,360 @@ +//! A dialog a script builds with ScriptUI's `new Window("dialog")` and shows with `show()` +//! (kind `scriptWindow`). It draws the controls the running script's dialog holds, at the places +//! the engine laid them out, and gives the script each click and change. +//! +//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`, +//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its +//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or +//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open; an event the +//! dialog cannot take is an error. An edit field gives its text when it loses the keyboard focus, +//! when Enter is pressed in a one-line field, or before a click on another control or a close. Events given in +//! one frame reach the script one at a time, in order. Enter outside a field clicks the default button, +//! and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog when it has +//! none. Stop ends the run and puts back everything it did. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_engine::script::scriptui::UiNode; +use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; + +use super::{DialogAction, DialogSpec}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of a script's ScriptUI dialog. +pub const KIND: &str = "scriptWindow"; + +/// The most of the dialog's content shown at once; a larger dialog scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading, + body_with_actions: Some(body), + confirm, + ok: None, + inputs: |_| &["event", "control", "value"], + min_width: 240.0, + max_width: Some(1000.0), + ..DialogSpec::FORM +}; + +/// Shows the ScriptUI dialog the running script waits at. +pub(crate) fn open(app: &mut VectorcraftApp, w: &ScriptUiDialog) { + app.ui.dialog = Some(Dialog::new(KIND, json!({"title": w.title(), SHOWN_KEY: w.shown}))); +} + +/// The field that holds which `show()` of the run the open dialog is for. +const SHOWN_KEY: &str = "shown"; + +/// Is `d` open for the dialog `w`, and not for one the script showed before it? +pub(crate) fn is_open_for(d: &Dialog, w: &ScriptUiDialog) -> bool { + d.kind == KIND && d.fields.get(SHOWN_KEY).and_then(Value::as_u64) == Some(w.shown) +} + +fn heading(d: &Dialog) -> String { + let title = d.str("title"); + if title.is_empty() { tl!("Script Alert").into() } else { vectorcraft_engine::script::dialogs::shown_text(&title, false) } +} + +fn memory_id() -> egui::Id { + egui::Id::unique("scriptWindow.shown") +} + +/// The dialog to draw: the one the run waits at, or while a handler runs, the one it last waited +/// at, with every control disabled. +fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Option<(Arc, bool)> { + if let Some(w) = app.session.script_window() { + let w = Arc::new(w); + ctx.data_mut(|m| m.insert_temp(memory_id(), w.clone())); + return Some((w, true)); + } + ctx.data(|m| m.get_temp::>(memory_id())).map(|w| (w, false)) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let Some((w, waiting)) = shown(app, ui.ctx()) else { return DialogAction::None }; + let mut events = Vec::new(); + let (width, height) = w.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { + let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + ui.add_enabled_ui(waiting, |ui| { + for (i, n) in w.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = control(ui, d, area.min, i, n, w.default_element == Some(i)) + { + events.push(e); + } + } + }); + }); + ui.add_space(12.0); + let mut stop = false; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::left_to_right(egui::Align::Center), |ui| { + stop = widgets::secondary_button(ui, tl!("Stop")).clicked(); + }); + if stop { + app.session.script_request_stop(); + app.ui.dialog = None; + return DialogAction::None; + } + let typing = ui.ctx().memory(|m| m.focused().is_some()); + if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + events.extend(w.default_element.map(UiEvent::Click)); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_))) { + commit_drafts(&w, d, &mut events); + } + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + queue.extend(events.iter().map(event_fields)); + if !waiting || queue.is_empty() { + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + return DialogAction::None; + } + let next = queue.remove(0); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + if let Value::Object(fields) = next { + d.fields.extend(fields); + } + DialogAction::Confirm +} + +/// The field that holds the events the person gave in one frame that the script has not had yet; +/// the script takes one event each time it waits. +const QUEUE_KEY: &str = "queued"; + +/// Before a click or a close, gives the script the text typed in each edit field that has not left +/// the field yet, so the handler of a button that closes the dialog, or `onClose`, reads it. +pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) { + let mut changes = Vec::new(); + for (i, n) in w.nodes.iter().enumerate() { + if n.kind != UiKind::EditText || n.readonly || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) { + continue; + } + if let Some(Value::String(text)) = d.fields.remove(&draft_key(i)) + && text != n.text + { + changes.push(UiEvent::Change(i, UiValue::Text(text))); + } + } + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + events.splice(at..at, changes); +} + +/// The field that holds an edit field's text while it is typed. +fn draft_key(i: usize) -> String { + format!("text{i}") +} + +/// Draws control `i` at its place from `origin`. → the event it gives. +fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &UiNode, default: bool) -> Option { + let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); + let t = Tokens::get(ui.ctx()); + let mut event = None; + ui.push_id(i, |ui| { + ui.add_enabled_ui(n.enabled, |ui| match n.kind { + UiKind::Dialog | UiKind::Group => {} + UiKind::Panel => { + let frame = rect.shrink(1.0); + let (enabled, name) = (ui.is_enabled(), n.text.clone()); + let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); + ui.painter().rect_stroke(frame, 4.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + if !n.text.is_empty() { + ui.painter().text(frame.min + egui::vec2(8.0, -6.0), egui::Align2::LEFT_TOP, &n.text, egui::FontId::proportional(11.0), t.text); + } + } + UiKind::StaticText => { + ui.put(rect, egui::Label::new(&n.text).wrap()); + } + UiKind::Button => { + let mut button = egui::Button::new(&n.text); + if default { + button = button.fill(t.accent_strong); + } + if ui.put(rect, button).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::CheckBox => { + let mut on = n.checked; + if ui.put(rect, egui::Checkbox::new(&mut on, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::RadioButton => { + if ui.put(rect, egui::RadioButton::new(n.checked, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::EditText => event = edit(ui, d, rect, i, n), + UiKind::DropDownList => { + let shown = n.selection.and_then(|k| n.items.get(k)).cloned().unwrap_or_default(); + let mut picked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() { + picked = Some(k); + } + } + }); + }); + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + UiKind::ListBox => { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(3.0)), |ui| { + egui::ScrollArea::vertical().id_salt(("script-window-listbox", i)).max_height(rect.height() - 6.0).show(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() && n.selection != Some(k) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + }); + }); + } + UiKind::Slider => { + let mut v = n.value; + let r = ui.put(rect, egui::Slider::new(&mut v, n.min..=n.max).show_value(false)); + name_for_screen_readers(ui, &r, n); + if (r.drag_stopped() || (r.changed() && !r.dragged())) && v != n.value { + event = Some(UiEvent::Change(i, UiValue::Number(v))); + } + } + UiKind::ProgressBar => { + let span = n.max - n.min; + let part = if span > 0.0 { ((n.value - n.min) / span) as f32 } else { 0.0 }; + let r = ui.put(rect, egui::ProgressBar::new(part)); + name_for_screen_readers(ui, &r, n); + } + }); + }); + event +} + +/// Screen readers call a control with no visible label of its own (an edit field, a slider or a +/// progress bar) by the name the script gave it, or else a slider or progress bar by its text. +fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode) { + let label = if !n.name.is_empty() { + n.name.clone() + } else if n.kind != UiKind::EditText { + n.text.clone() + } else { + String::new() + }; + if !label.is_empty() { + ui.ctx().accesskit_node_builder(r.id, |node| node.set_label(label)); + } +} + +/// An edit field: its text is kept in the dialog while it is typed and given to the script when +/// the field loses the focus, or at Enter in a one-line field. +fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, i: usize, n: &UiNode) -> Option { + let key = draft_key(i); + let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); + let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; + let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); + name_for_screen_readers(ui, &r, n); + if r.changed() { + d.fields.insert(key.clone(), json!(text)); + } + let entered = !n.multiline && r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if (r.lost_focus() || entered) && text != n.text && !n.readonly { + d.fields.remove(&key); + return Some(UiEvent::Change(i, UiValue::Text(text))); + } + if !r.has_focus() && !r.changed() { + d.fields.remove(&key); + } + None +} + +/// `event` as the dialog's `event`, `control` and `value` fields. +fn event_fields(event: &UiEvent) -> Value { + let (name, control, value) = match event { + UiEvent::Click(i) => ("click", json!(i), Value::Null), + UiEvent::Change(i, UiValue::Text(t)) => ("change", json!(i), json!(t)), + UiEvent::Change(i, UiValue::Number(v)) => ("change", json!(i), json!(v)), + UiEvent::Change(i, UiValue::Index(k)) => ("change", json!(i), json!(k)), + UiEvent::Close => ("close", Value::Null, Value::Null), + }; + json!({"event": name, "control": control, "value": value}) +} + +/// The event in the dialog's fields, for the dialog `w`. +fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { + let control = match d.fields.get("control") { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => { + w.find(s).ok_or_else(|| format!("the dialog has no control named {}", vectorcraft_engine::script::dialogs::cut_to(s, 64)))? + } + _ => 0, + }; + let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + match (d.str("event").as_str(), d.fields.get("value")) { + ("close", _) => Ok(UiEvent::Close), + ("click", _) => Ok(UiEvent::Click(control)), + ("change", Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), + ("change", Some(Value::Number(v))) if list => match v.as_u64() { + Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX))))), + None => Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))), + ("change", Some(Value::Null) | None) if list => Ok(UiEvent::Change(control, UiValue::Index(None))), + ("change", _) => Err("a change's `value` must be a string, a number or null".into()), + _ => Err("`event` must be click, change or close".into()), + } +} + +/// Gives the running script the event in the dialog's fields. The dialog stays open for the +/// script's next wait; an event it cannot take is an error. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; + let event = event_of(&w, d)?; + app.session.script_window_answer(event)?; + if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { + for k in ["event", "control", "value"] { + open.fields.remove(k); + } + } + Ok(Value::Null) +} + +/// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog +/// has none or it cannot be clicked, after the text still typed in its fields. Events the script +/// has not had yet go after the ones before them. +pub(super) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) { + let Some(w) = app.session.script_window() else { return }; + let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); + let mut events = vec![click.unwrap_or(UiEvent::Close)]; + commit_drafts(&w, d, &mut events); + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + let mut events = events.into_iter(); + if queue.is_empty() + && let Some(first) = events.next() + { + let _ = app.session.script_window_answer(first); + } + queue.extend(events.map(|e| event_fields(&e))); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..9d442848ce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6589,7 +6589,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false @msg is longer than 16 KiB ocupa més de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null -@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window ha de tenir `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps és la resposta d’una finestra, el `value` de la qual ha de ser una llista de passos +@msg has a step {i} that is not a valid click, change or close té un pas {i} que no és un clic, un canvi ni un tancament vàlid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ee8b68af7d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9868,7 +9868,9 @@ breakText Glyphs Glyfy @msg more than {MAX_IMPORT} presets více než {MAX_IMPORT} přednastavení @msg moved must be [[x,y]…] moved musí být [[x,y]…] @msg must be an object with `kind` and `value` musí být objekt s `kind` a `value` -@msg must have `kind` alert, confirm or prompt musí mít `kind` alert, confirm nebo prompt +@msg must have `kind` alert, confirm, prompt or window musí mít `kind` alert, confirm, prompt nebo window +@msg is a window's answer, whose `value` must be a list of steps je odpověď okna, jejíž `value` musí být seznam kroků +@msg has a step {i} that is not a valid click, change or close má krok {i}, který není platné kliknutí, změna ani zavření @msg must have exactly `kind` and `value` musí mít právě `kind` a `value` @msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné @msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..cc03e6ef1b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -233,7 +233,9 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false @msg is longer than 16 KiB er længere end 16 KiB @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null -@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window skal have `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps er et vindues svar, hvis `value` skal være en liste over trin +@msg has a step {i} that is not a valid click, change or close har et trin {i}, der ikke er et gyldigt klik, en gyldig ændring eller en gyldig lukning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..e92726501f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8629,7 +8629,9 @@ breakText Glyphs Glyphen @msg missing `picks` `picks` fehlt @msg missing `word` `word` fehlt @msg must be an object with `kind` and `value` muss ein Objekt mit `kind` und `value` sein -@msg must have `kind` alert, confirm or prompt muss `kind` alert, confirm oder prompt haben +@msg must have `kind` alert, confirm, prompt or window muss `kind` alert, confirm, prompt oder window haben +@msg is a window's answer, whose `value` must be a list of steps ist die Antwort auf ein Fenster, deren `value` eine Liste von Schritten sein muss +@msg has a step {i} that is not a valid click, change or close hat einen Schritt {i}, der kein gültiger Klick, keine gültige Änderung und kein gültiges Schließen ist @msg must have exactly `kind` and `value` muss genau `kind` und `value` haben @msg needs a closing quote after the name braucht ein schließendes Anführungszeichen nach dem Namen @msg needs a name braucht einen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..12d3aba3c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2787,7 +2787,9 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false @msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null -@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt +@msg must have `kind` alert, confirm, prompt or window πρέπει να έχει `kind` alert, confirm, prompt ή window +@msg is a window's answer, whose `value` must be a list of steps είναι απάντηση παραθύρου, της οποίας το `value` πρέπει να είναι λίστα βημάτων +@msg has a step {i} that is not a valid click, change or close έχει ένα βήμα {i} που δεν είναι έγκυρο κλικ, αλλαγή ή κλείσιμο @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} @msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..c404d6ed6e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5061,7 +5061,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false @msg is longer than 16 KiB ocupa más de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null -@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window debe tener `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps es la respuesta de una ventana, cuyo `value` debe ser una lista de pasos +@msg has a step {i} that is not a valid click, change or close tiene un paso {i} que no es un clic, un cambio ni un cierre válido @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..2ae421c004 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5302,7 +5302,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false @msg is longer than 16 KiB on pidempi kuin 16 KiB @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null -@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt +@msg must have `kind` alert, confirm, prompt or window `kind`-arvon on oltava alert, confirm, prompt tai window +@msg is a window's answer, whose `value` must be a list of steps on ikkunan vastaus, jonka `value`-arvon on oltava luettelo vaiheista +@msg has a step {i} that is not a valid click, change or close sisältää vaiheen {i}, joka ei ole kelvollinen napsautus, muutos tai sulkeminen @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..aa2a24c90d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9728,7 +9728,9 @@ breakText Glyphs Glyphes @msg more than {MAX_IMPORT} presets plus de {MAX_IMPORT} paramètres prédéfinis @msg moved must be [[x,y]…] moved doit être [[x,y]…] @msg must be an object with `kind` and `value` doit être un objet avec `kind` et `value` -@msg must have `kind` alert, confirm or prompt doit avoir `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window doit avoir `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps est la réponse d’une fenêtre, dont la `value` doit être une liste d’étapes +@msg has a step {i} that is not a valid click, change or close a une étape {i} qui n’est ni un clic, ni une modification, ni une fermeture valide @msg must have exactly `kind` and `value` doit avoir exactement `kind` et `value` @msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est obligatoire @msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..5bdc231564 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7736,7 +7736,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए @msg is longer than 16 KiB 16 KiB से लंबा है @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए -@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए +@msg must have `kind` alert, confirm, prompt or window `kind` alert, confirm, prompt या window होना चाहिए +@msg is a window's answer, whose `value` must be a list of steps एक window का उत्तर है, जिसका `value` चरणों की सूची होना चाहिए +@msg has a step {i} that is not a valid click, change or close में चरण {i} मान्य क्लिक, बदलाव या बंद करना नहीं है @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए @msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..af96effe62 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9739,7 +9739,9 @@ breakText Glyphs Glifák @msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás @msg moved must be [[x,y]…] moved: [[x,y]…] kell @msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell -@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen +@msg must have `kind` alert, confirm, prompt or window a `kind` értéke alert, confirm, prompt vagy window kell legyen +@msg is a window's answer, whose `value` must be a list of steps egy ablak válasza, amelynek `value` értéke lépések listája kell legyen +@msg has a step {i} that is not a valid click, change or close {i}. lépése nem érvényes kattintás, módosítás vagy bezárás @msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia @msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező @msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..87d73912db 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -140,7 +140,9 @@ @msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false @msg is longer than 16 KiB lebih panjang dari 16 KiB @msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null -@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt +@msg must have `kind` alert, confirm, prompt or window harus memiliki `kind` alert, confirm, prompt, atau window +@msg is a window's answer, whose `value` must be a list of steps adalah jawaban jendela, yang `value`-nya harus berupa daftar langkah +@msg has a step {i} that is not a valid click, change or close memiliki langkah {i} yang bukan klik, perubahan, atau penutupan yang valid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..5aab7c3e3d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8678,7 +8678,9 @@ breakText Glyphs Glifi @msg missing `picks` `picks` mancante @msg missing `word` `word` mancante @msg must be an object with `kind` and `value` deve essere un oggetto con `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve avere `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window deve avere `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps è la risposta di una finestra, il cui `value` deve essere un elenco di passaggi +@msg has a step {i} that is not a valid click, change or close ha un passaggio {i} che non è un clic, una modifica o una chiusura validi @msg must have exactly `kind` and `value` deve avere esattamente `kind` e `value` @msg needs a closing quote after the name richiede una virgoletta di chiusura dopo il nome @msg needs a name richiede un nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..ef0740a8bb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7495,7 +7495,9 @@ axis Y Axis Y 軸 @msg missing `picks` `picks` がありません @msg missing `word` `word` がありません @msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください -@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください +@msg must have `kind` alert, confirm, prompt or window の `kind` には alert、confirm、prompt、window のいずれかを指定してください +@msg is a window's answer, whose `value` must be a list of steps は window の回答で、`value` には手順のリストを指定してください +@msg has a step {i} that is not a valid click, change or close の手順 {i} は有効なクリック、変更、閉じる操作のいずれでもありません @msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください @msg needs a closing quote after the name 名前の後に閉じ引用符が必要です @msg needs a name 名前が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..e7223c60c8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1085,7 +1085,9 @@ @msg more than {MAX_IMPORT} presets {MAX_IMPORT}-ზე მეტი პრესეტი @msg moved must be [[x,y]…] moved უნდა იყოს [[x,y]…] @msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ით და `value`-თი -@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt +@msg must have `kind` alert, confirm, prompt or window `kind` უნდა იყოს alert, confirm, prompt ან window +@msg is a window's answer, whose `value` must be a list of steps არის ფანჯრის პასუხი, რომლის `value` უნდა იყოს ნაბიჯების სია +@msg has a step {i} that is not a valid click, change or close შეიცავს ნაბიჯს {i}, რომელიც არ არის სწორი დაწკაპუნება, ცვლილება ან დახურვა @msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value` @msg name (a toolbar's name) is required საჭიროა name (ხელსაწყოთა ზოლის სახელი) @msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) უნდა იყოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..e40e7055a2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9508,7 +9508,9 @@ breakText Glyphs 글리프 @msg more than {MAX_IMPORT} presets 사전 설정이 {MAX_IMPORT}개보다 많습니다 @msg moved must be [[x,y]…] moved는 [[x,y]…]여야 합니다 @msg must be an object with `kind` and `value` `kind`와 `value`가 있는 개체여야 합니다 -@msg must have `kind` alert, confirm or prompt `kind`가 alert, confirm 또는 prompt여야 합니다 +@msg must have `kind` alert, confirm, prompt or window `kind`가 alert, confirm, prompt 또는 window여야 합니다 +@msg is a window's answer, whose `value` must be a list of steps 창의 답이며, `value`는 단계 목록이어야 합니다 +@msg has a step {i} that is not a valid click, change or close 단계 {i}이(가) 올바른 클릭, 변경 또는 닫기가 아닙니다 @msg must have exactly `kind` and `value` `kind`와 `value`만 있어야 합니다 @msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 @msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d52992f4a9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7380,7 +7380,9 @@ imageTrace Outline Contour @msg more than {MAX_IMPORT} presets meer dan {MAX_IMPORT} voorinstellingen @msg moved must be [[x,y]…] moved moet [[x,y]…] zijn @msg must be an object with `kind` and `value` moet een object met `kind` en `value` zijn -@msg must have `kind` alert, confirm or prompt moet `kind` alert, confirm of prompt hebben +@msg must have `kind` alert, confirm, prompt or window moet `kind` alert, confirm, prompt of window hebben +@msg is a window's answer, whose `value` must be a list of steps is het antwoord van een venster, waarvan `value` een lijst met stappen moet zijn +@msg has a step {i} that is not a valid click, change or close heeft een stap {i} die geen geldige klik, wijziging of sluiting is @msg must have exactly `kind` and `value` moet precies `kind` en `value` hebben @msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist @msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..1a2148f0e1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8882,7 +8882,9 @@ breakText Glyphs Glify @msg missing `picks` brak `picks` @msg missing `word` brak `word` @msg must be an object with `kind` and `value` musi być obiektem z `kind` i `value` -@msg must have `kind` alert, confirm or prompt `kind` musi mieć wartość alert, confirm lub prompt +@msg must have `kind` alert, confirm, prompt or window `kind` musi mieć wartość alert, confirm, prompt lub window +@msg is a window's answer, whose `value` must be a list of steps jest odpowiedzią okna, której `value` musi być listą kroków +@msg has a step {i} that is not a valid click, change or close ma krok {i}, który nie jest prawidłowym kliknięciem, zmianą ani zamknięciem @msg must have exactly `kind` and `value` musi mieć dokładnie `kind` i `value` @msg needs a closing quote after the name wymaga zamykającego cudzysłowu po nazwie @msg needs a name wymaga nazwy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..82cdb0a2b2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9930,7 +9930,9 @@ swatch Yellow Green Verde-amarelado @msg more than {MAX_IMPORT} presets mais de {MAX_IMPORT} predefinições @msg moved must be [[x,y]…] moved deve ser [[x,y]…] @msg must be an object with `kind` and `value` deve ser um objeto com `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve ter `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window deve ter `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps é a resposta de uma janela, cujo `value` deve ser uma lista de etapas +@msg has a step {i} that is not a valid click, change or close tem uma etapa {i} que não é um clique, uma alteração nem um fechamento válido @msg must have exactly `kind` and `value` deve ter exatamente `kind` e `value` @msg name (a toolbar's name) is required name (o nome de uma barra de ferramentas) é obrigatório @msg name (a toolbar's name) must be a string name (o nome de uma barra de ferramentas) deve ser uma string diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..6f351f1d76 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5083,7 +5083,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false @msg is longer than 16 KiB длиннее 16 КиБ @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null -@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt +@msg must have `kind` alert, confirm, prompt or window должен иметь `kind` alert, confirm, prompt или window +@msg is a window's answer, whose `value` must be a list of steps является ответом окна, `value` которого должен быть списком шагов +@msg has a step {i} that is not a valid click, change or close содержит шаг {i}, который не является допустимым щелчком, изменением или закрытием @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..532e1ade50 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4959,7 +4959,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false @msg is longer than 16 KiB är längre än 16 KiB @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null -@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window måste ha `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps är ett fönsters svar, vars `value` måste vara en lista med steg +@msg has a step {i} that is not a valid click, change or close har ett steg {i} som inte är ett giltigt klick, en giltig ändring eller en giltig stängning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..daba147a6d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5774,12 +5774,14 @@ fn script_answers_errors_are_translated() { "is a confirm's answer, whose `value` must be true or false", "is longer than 16 KiB", "is a prompt's answer, whose `value` must be a string or null", - "must have `kind` alert, confirm or prompt", + "must have `kind` alert, confirm, prompt or window", + "is a window's answer, whose `value` must be a list of steps", ]; let in_app = "`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"; let lists = ["`answers` must be a list of answers", "`answers` has more than {MAX_ANSWERS} answers", "`answers` is larger than 1 MiB"]; + let step = "has a step {i} that is not a valid click, change or close"; let scanned = message_literals(); - for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app]) { + for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app, step]) { assert!(scanned.contains(template), "{template}"); } let ok = json!({"kind": "alert", "value": "ok"}); @@ -5791,6 +5793,7 @@ fn script_answers_errors_are_translated() { json!({"kind": "prompt", "value": "x".repeat(16 * 1024 + 1)}), json!({"kind": "prompt", "value": 1}), json!({"kind": "beep", "value": 1}), + json!({"kind": "window", "value": "click"}), ]; let run = |s: &mut Session, answers: Value| s.execute("script.run", &json!({"source": "1", "answers": answers})).unwrap_err(); let mut s = Session::new(); @@ -5807,6 +5810,8 @@ fn script_answers_errors_are_translated() { errors.push((run(&mut s, json!(vec![ok.clone(); 10_001])), "`answers` has more than 10000 answers".to_string(), None)); let long = json!({"kind": "prompt", "value": "x".repeat(16 * 1024)}); errors.push((run(&mut s, json!(vec![long; 70])), lists[2].to_string(), None)); + let steps = json!([{"kind": "window", "value": [{"event": "close"}, {"event": "tap"}]}]); + errors.push((run(&mut s, steps), "`answers[0]` has a step 1 that is not a valid click, change or close".to_string(), None)); s.script_frames = true; errors.push((run(&mut s, json!([ok])), in_app.to_string(), None)); for (e, want, reason) in &errors { @@ -5826,8 +5831,8 @@ fn script_answers_errors_are_translated() { let numbers: Vec<&str> = want.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); let names = ["`answers", "`kind`", "`value`", "true", "false", "null"]; assert!(numbers.iter().chain(&names).all(|n| !want.contains(n) || shown.contains(n)), "{code}: {shown}"); - if want.ends_with("alert, confirm or prompt") { - assert!(["alert", "confirm", "prompt"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); + if want.ends_with("alert, confirm, prompt or window") { + assert!(["alert", "confirm", "prompt", "window"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); } } } diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..22568734be 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7871,7 +7871,9 @@ axis Y Axis Y ekseni @msg missing `picks` `picks` eksik @msg missing `word` `word` eksik @msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır -@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have `kind` alert, confirm, prompt or window `kind` değeri alert, confirm, prompt veya window olmalıdır +@msg is a window's answer, whose `value` must be a list of steps bir pencerenin yanıtıdır ve `value` değeri bir adım listesi olmalıdır +@msg has a step {i} that is not a valid click, change or close içindeki {i}. adım geçerli bir tıklama, değişiklik veya kapatma değil @msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir @msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir @msg needs a name bir ad gerekir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..1c44123d26 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9509,7 +9509,9 @@ breakText Glyphs Гліфи @msg more than {MAX_IMPORT} presets понад {MAX_IMPORT} наборів @msg moved must be [[x,y]…] moved має бути [[x,y]…] @msg must be an object with `kind` and `value` має бути об’єктом із `kind` і `value` -@msg must have `kind` alert, confirm or prompt повинен мати `kind` зі значенням alert, confirm або prompt +@msg must have `kind` alert, confirm, prompt or window повинен мати `kind` зі значенням alert, confirm, prompt або window +@msg is a window's answer, whose `value` must be a list of steps є відповіддю вікна, `value` якої має бути списком кроків +@msg has a step {i} that is not a valid click, change or close має крок {i}, який не є допустимим клацанням, зміною або закриттям @msg must have exactly `kind` and `value` повинен мати рівно `kind` і `value` @msg name (a toolbar's name) is required name (ім’я панелі інструментів) є обов’язковим @msg name (a toolbar's name) must be a string name (ім’я панелі інструментів) має бути рядком diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..2758865931 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5582,7 +5582,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false @msg is longer than 16 KiB dài hơn 16 KiB @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null -@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt +@msg must have `kind` alert, confirm, prompt or window phải có `kind` là alert, confirm, prompt hoặc window +@msg is a window's answer, whose `value` must be a list of steps là câu trả lời của một cửa sổ, có `value` phải là danh sách các bước +@msg has a step {i} that is not a valid click, change or close có bước {i} không phải là một lần nhấp, thay đổi hoặc đóng hợp lệ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..dac4499a58 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8888,7 +8888,9 @@ breakText Glyphs 字形 @msg missing `picks` 缺少 `picks` @msg missing `word` 缺少 `word` @msg must be an object with `kind` and `value` 必须是包含 `kind` 和 `value` 的对象 -@msg must have `kind` alert, confirm or prompt `kind` 必须是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必须是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是窗口的回答,其 `value` 必须是步骤列表 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的点击、更改或关闭 @msg must have exactly `kind` and `value` 必须只包含 `kind` 和 `value` @msg needs a closing quote after the name 名称后需要右引号 @msg needs a name 需要名称 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..bf6ee14a81 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8824,7 +8824,9 @@ breakText Glyphs 字符 @msg missing `picks` 未提供 `picks` @msg missing `word` 未提供 `word` @msg must be an object with `kind` and `value` 必須是包含 `kind` 和 `value` 的物件 -@msg must have `kind` alert, confirm or prompt `kind` 必須是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必須是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是視窗的回答,其 `value` 必須是步驟清單 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的點按、變更或關閉 @msg must have exactly `kind` and `value` 只能有 `kind` 和 `value` @msg needs a closing quote after the name 名稱之後需要結尾引號 @msg needs a name 需要名稱 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..f3d5f14912 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,12 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, +//! waits for the person's answer. use serde_json::json; use crate::VectorcraftApp; -use crate::dialogs::script_run; +use crate::dialogs::{script_run, script_window}; use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -29,7 +30,7 @@ pub fn poll(app: &mut VectorcraftApp) { if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { app.canvas.hover_cursor = None; } - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND || d.kind == script_window::KIND) { app.ui.dialog = None; } script_run::settle_close(app); @@ -49,6 +50,14 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + // A ScriptUI dialog the script closed gives way to the file dialog or dialog function it waits + // at now. + if app.session.script_window().is_none() + && (app.session.script_picker().is_some() || app.session.script_dialog().is_some()) + && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) + { + app.ui.dialog = None; + } if let Some(picker) = app.session.script_picker() { if app.ui.dialog.is_none() { script_run::open_picker(app, &picker); @@ -68,6 +77,21 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { app.ui.dialog = None; } + if let Some(window) = app.session.script_window() { + // A dialog the script showed after closing the one that is open replaces it. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND && !script_window::is_open_for(d, &window)) { + app.ui.dialog = None; + } + if app.ui.dialog.is_none() { + script_window::open(app, &window); + } + return true; + } + // While a handler runs, the ScriptUI dialog stays open, until the run ends or asks about its + // growth. + if app.session.script_waiting() && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) { + app.ui.dialog = None; + } if app.session.script_waiting() { if app.ui.dialog.is_none() { app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..ac934f6d18 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -43,6 +43,7 @@ mod screenshots; mod script_check; mod script_dialogs; mod script_run; +mod script_window; mod scripts_menu; mod scrub; mod selectall; diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs new file mode 100644 index 0000000000..1cc241b049 --- /dev/null +++ b/crates/ui-egui/src/tests/script_window.rs @@ -0,0 +1,273 @@ +//! A script's ScriptUI dialog in the app: it opens when `show()` waits, takes clicks and changes +//! from the person and from `ui.dialog.confirm`, Enter and Escape, Stop, and quitting while it +//! waits. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_run::CLOSE_KIND; +use crate::dialogs::script_window::{self, KIND}; +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +const FORM: &str = "var w = new Window('dialog', 'Make'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); bold.onClick = function () { name.text = 'clicked'; }; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "w.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its ScriptUI dialog is open and it waits (true). +fn until_window(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) && app.session.script_window().is_some() { + return true; + } + } + panic!("the script neither ended nor opened its dialog"); +} + +/// Gives the dialog an event as `ui.dialog.set` and `ui.dialog.confirm` do. +fn give(app: &mut VectorcraftApp, event: Value) -> Result { + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in event.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } + dialogs::confirm(app) +} + +thread_local! { + static CTX: egui::Context = { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; +} + +/// One headless frame of the dialog layer and the shortcuts. Each key pressed in it is let go in a +/// second frame. +fn frame(app: &mut VectorcraftApp, events: Vec) { + let ctx = CTX.with(Clone::clone); + let released: Vec = events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, physical_key, modifiers, pressed: true, .. } => { + Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + } + _ => None, + }) + .collect(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pressed = !released.is_empty(); + for events in std::iter::once(events).chain(pressed.then_some(released)) { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + dialogs::show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn the_dialog_takes_events_and_stays_open_while_its_handlers_run() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} var r = w.show(); vc.log([r, name.text, bold.value]);")); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "Make"); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open for the next wait"); + assert!(until_window(&mut app)); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "clicked", "the handler changed the field"); + assert!(give(&mut app, json!({"event": "click", "control": 99})).is_err()); + assert!(give(&mut app, json!({"event": "wave"})).is_err()); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann", true]])); + assert!(app.ui.dialog.is_none()); + assert_eq!(objects(&app), 1); +} + +#[test] +fn text_still_in_a_field_reaches_the_script_before_a_click() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!("Ann")); + let mut events = vec![UiEvent::Click(3)]; + script_window::commit_drafts(&w, d, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("Ann".into())), UiEvent::Click(3)]); + assert!(!d.fields.contains_key("text1"), "the text is given once"); + d.fields.insert("queued".into(), json!([{"event": "change", "control": 1, "value": "Ann"}, {"event": "click", "control": 3, "value": null}])); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the change and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann"]])); +} + +#[test] +fn escape_clicks_the_cancel_button_and_closes_a_dialog_without_one() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Escape)]); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([2])); + start(&mut app, "var w = new Window('dialog'); w.add('statictext', undefined, 'Hi'); vc.log(w.show());"); + assert!(until_window(&mut app)); + dialogs::cancel(&mut app); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn escape_keeps_the_dialog_open_until_the_script_closes_it() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.onClose = function () { return false; }; vc.log(w.show());"); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.fields["queued"], json!([{"event": "close", "control": null, "value": null}]), "with the close after the typed text"); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "typed"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "onClose kept the dialog open"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued")); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +fn start_typing(app: &mut VectorcraftApp) { + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); +} + +#[test] +fn escape_gives_the_typed_text_before_the_cancel_click() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'old'); var c = w.add('button', undefined, 'Cancel'); \ + c.onClick = function () { vc.log(e.text); w.close(2); }; vc.log(w.show());", + ); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the script takes the text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on Cancel closes the dialog"); + assert_eq!(log(&app), json!(["typed", 2])); +} + +#[test] +fn a_second_dialog_replaces_the_first() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log([b.show(), b.children[0].text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("left over")); + assert!(until_window(&mut app)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("title"), "B", "the second dialog's title"); + assert!(!d.fields.contains_key("text1"), "without the first dialog's typed text"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "y"]])); +} + +#[test] +fn a_dialog_function_after_show_opens_its_own_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} w.show(); alert('done');")); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..100 { + script_runs::poll(&mut app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind != KIND) { + break; + } + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::NOTICE_KIND), "the alert opens"); + assert!(app.session.script_dialog().is_some()); +} + +#[test] +fn stop_in_the_dialog_rolls_the_run_back() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} w.show(); vc.log('after');")); + assert!(until_window(&mut app)); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND)); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the dialog opens again"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("text1"), "typed", "with the text typed in its field"); + dialogs::script_run::ask_to_close(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_large_dialog_draws_in_a_small_window() { + let mut app = app(); + let source = "var w = new Window('dialog', 'Big'); var p = w.add('panel', undefined, 'Lots'); \ + for (var i = 0; i < 200; i++) p.add('checkbox', undefined, 'Option ' + i); \ + var l = w.add('listbox', undefined, ['a', 'b']); var d = w.add('dropdownlist', undefined, ['x', 'y']); \ + w.add('slider', undefined, 2, 0, 5); w.add('progressbar', undefined, 1, 4); w.add('edittext', undefined, 'm', {multiline: true}); \ + w.add('button', undefined, 'OK'); vc.log(w.show());"; + start(&mut app, source); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([1])); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..771273aed2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2841,10 +2841,12 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for - `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` - for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and - `dialogsTruncated` is true when the list stopped at its limit. + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm`, `{kind, message, title, preset, answer}` + for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`). + `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` + for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a + `show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list + stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -2895,6 +2897,67 @@ empty object are the same. vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` +The help pages https://extendscript.docsforadobe.dev/user-interface-tools/window-object/, +https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and +https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its +controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it: + +- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) or a + resource string throws an `Error` that says it is not available yet. +- `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The + types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, + `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, + and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, + minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `listbox` with + `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` + and the rest) throw that they are not available yet, and an unknown type throws too. +- A list's `add("item", text)` adds an item, `removeAll()` removes them, `items` lists them and `selection` is the + selected item or `null`; setting it to an item or an index selects it. An item has `text`, `index` and + `selected`. +- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, + `window`, `show()` and `hide()`. A container also has `children`, `orientation` (`row`, `column` or `stack`; a + group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` + (15 to start, 0 for a group) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, + `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + +`show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check +box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An +edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another +control, and a slider gives its +value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. +Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` +returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the +cancel button is clicked, while they have no `onClick`, and 0 for the close box. `onClose` runs before the dialog +closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled +OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside +a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in +function. A shown dialog can be shown again after it closes. + +`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of +text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws +too, and a slider's minimum above its maximum. It lays the controls out from each container's `orientation`, +`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places +it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. + +In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, +which ends the run as `script.stop` does. Enter outside a field clicks the default button. Escape clicks the +cancel button, or closes the dialog when it has none. Quitting while it waits asks whether to stop the script, and +Cancel shows it again. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in +the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a disabled or +hidden control, a value out of a list's range and a click on a control that takes none are errors, and the dialog +stays open. + +A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is +`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a +control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a +list's item index or `null`. The dialog takes the next step each time it waits. The run ends with an error that +the script cannot catch, and every document goes back, when no step is left, when a step names a control the +dialog does not have or that cannot take it, or when the dialog closes with steps it did not use. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' +``` + The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A script reads files with them: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..939047032e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,6 +1066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). From 95d1f700418f32db2c0bf99afb1bafa37c40bcf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:17:22 -0800 Subject: [PATCH 020/198] Scripts: .js scripts define classes with extends, super and new.target With Options::es2015, vectorcraft-js reads and runs ECMAScript 2015 classes: declarations, scoped to their block like let, and expressions, with extends, static members, getters and setters and computed method names. Class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without new throws a TypeError. A derived constructor's this throws a ReferenceError until super(...) returns, and its default constructor passes its arguments on. super.name and super[key] read, call and write through the prototype of the method's home object, in class methods and in object literal methods, which ES2015 allows in a .js script. new.target names the constructor new was applied to, in functions and their arrow functions. A class can extend null, a function, a class, or the built-in constructors Object, Function, Array, String, Number, Boolean, RegExp, Date and the error types; extending any other built-in throws a TypeError. Each class and method takes fuel and counts against the heap limit, and deep constructor chains stop at the frame limit. A .jsx file and a source string stay ES5.1, where class syntax is a SyntaxError. The test262 runner adds the class, super and new.target tests to its ES2015 subset (1,125 tests). With the option, 554 of 554 negative parse runs and 1,527 of 1,633 other runs pass; the failing runs use Object.setPrototypeOf, RegExp.prototype.flags, function name properties, a configurable length, the caller and arguments restrictions, or super and new.target in direct eval. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests/script_run.rs | 23 ++ crates/js/src/ast.rs | 66 ++++ crates/js/src/bytecode.rs | 87 ++++- crates/js/src/class_ops.rs | 484 ++++++++++++++++++++++++++ crates/js/src/compiler.rs | 174 ++++++++- crates/js/src/es2015_tests.rs | 210 ++++++++++- crates/js/src/interp.rs | 160 +++++---- crates/js/src/interp_tests.rs | 4 + crates/js/src/lib.rs | 6 +- crates/js/src/parser.rs | 253 +++++++++++++- crates/js/tests/test262.rs | 10 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 3 +- 13 files changed, 1395 insertions(+), 94 deletions(-) create mode 100644 crates/js/src/class_ops.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..2ee69f12c3 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_defines_classes_and_a_jsx_script_cannot() { + let dir = fresh_folder("es2015-classes"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "class Shape { constructor(n) { this.n = n; } sides() { return this.n; } }\n\ + class Square extends Shape { constructor() { super(4); } sides() { return super.sides() * 10; } }\n\ + vc.log(new Square().sides());\nvc.log(eval('class E {} typeof E'));\n"; + let r = s.execute("script.run", &path(&write("shapes.js", modern))).unwrap(); + assert_eq!(r["log"], json!([40, "function"]), "{r}"); + for (name, text) in [("legacy.jsx", "class A {}"), ("object.jsx", "var o = { m() {} };")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..409b5a25bb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -98,6 +98,8 @@ pub enum PropertyValue { Init(ExprId), Get(FunctionId), Set(FunctionId), + /// A method (`m() {…}`, ECMA-262 2015 section 14.3). + Method(FunctionId), } #[derive(Clone, Debug, PartialEq)] @@ -218,6 +220,54 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// A class expression. + Class(Box), + /// `super(arguments)` in a derived class's constructor. + SuperCall(Vec), + /// `super.property` in a class's methods and constructor. + SuperMember(Name), + /// `super[index]`. + SuperIndex(ExprId), + /// `new.target`. + NewTarget, +} + +/// A class declaration or expression (ECMA-262 2015 section 14.5). +#[derive(Clone, Debug, PartialEq)] +pub struct ClassDef { + pub name: Option, + /// The expression after `extends`. + pub heritage: Option, + /// The constructor as written, or the default one a class without one gets. Its span is the + /// class's. + pub constructor: FunctionId, + /// The methods and accessors other than the constructor, in source order. + pub elements: Vec, + pub span: Span, +} + +/// A method or accessor in a class body. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassElement { + pub key: ClassKey, + /// Defined on the constructor (`static`) rather than on its `prototype`. + pub is_static: bool, + pub kind: MethodKind, + pub function: FunctionId, +} + +/// A class element's name: written out, or computed (`[expression]`). +#[derive(Clone, Debug, PartialEq)] +pub enum ClassKey { + Fixed(PropertyKey), + Computed(ExprId), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MethodKind { + Method, + Get, + Set, } /// A piece of a template literal's text between its substitutions. @@ -314,6 +364,8 @@ pub enum Stmt { /// `let` or `const` declarations (a `const` always has an initializer). Lexical(LexKind, Vec), FunctionDecl(FunctionId), + /// A class declaration, its name a `let`-like binding of the scope it stands in. + Class(Box), Expr(ExprId), Block(Vec), Empty, @@ -377,6 +429,12 @@ pub enum FunctionKind { Setter, /// An arrow function; one with an expression body has a body of one `return` statement. Arrow, + /// A method in a class body. + Method, + /// The constructor of a class without `extends`. + ClassConstructor, + /// The constructor of a class with `extends`. + DerivedConstructor, } #[derive(Clone, Debug, PartialEq)] @@ -394,9 +452,17 @@ pub struct Function { /// or the code around it is strict. pub strict: bool, pub span: Span, + /// The function is defined in a class body (a method, an accessor or the constructor): it has + /// a home object for `super.property`. + pub home: bool, } impl Function { + /// The function is a class constructor. + pub fn is_class_constructor(&self) -> bool { + matches!(self.kind, FunctionKind::ClassConstructor | FunctionKind::DerivedConstructor) + } + /// The parameters are plain names: no default value and no rest parameter. pub fn simple_params(&self) -> bool { self.rest.is_none() && self.defaults.iter().all(Option::is_none) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..08dff47905 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -36,6 +36,8 @@ pub(crate) enum Op { Swap, /// `a b c` → `b c a`. Rot3, + /// Pushes a copy of the value `n` places under the top one (`Pick(0)` is `Dup`). + Pick(u32), /// Pushes the value of the variable `names[i]`. GetVar(u32), /// Pushes the value of the variable and the `this` a call to it gets. @@ -205,6 +207,59 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `[superclass]` → `constructor prototype`: makes a class's prototype object and its + /// constructor from `functions[ctor]`, the superclass on the stack when `heritage` is true + /// (ECMA-262 2015 section 14.5.14). + ClassStart { + ctor: u32, + heritage: bool, + }, + /// `constructor prototype key` → `constructor prototype`: defines the method, getter (`kind` 1) + /// or setter (`kind` 2) made from `functions[func]` under the key, on the constructor when + /// `is_static` is true and otherwise on the prototype. + ClassMethod { + func: u32, + kind: u8, + is_static: bool, + }, + /// `object` → `object`: defines the enumerable method, getter (`kind` 1) or setter (`kind` + /// 2) made from `functions[func]` under `names[name]` on an object literal's object, its home + /// object (section 12.2.6.8). + InitMethod { + func: u32, + kind: u8, + name: u32, + }, + /// `this key` → `this home key`: the key as a property name, with the prototype of the + /// running method's home object between, for a `super` property (section 12.3.5.3). + SuperRef, + /// `this home key` → the property's value, read from the home object with `this` as the + /// receiver. + SuperGet, + /// `this home key` → `value this`, for a call. + SuperGetThis, + /// `this home key value` → `value`, written through the home object with `this` as the + /// receiver. + SuperSet, + /// `this home key` → `this home key this home key`. + SuperDup, + /// `this home key` → the old or new value: `++` or `--` on a `super` property. + SuperInc { + prefix: bool, + dec: bool, + }, + /// Pushes the constructor `super(…)` calls: the prototype of the running class constructor. + SuperCtor, + /// `constructor arg…` → the object it constructs, with the running constructor's + /// `new.target`. + SuperCall(u32), + /// `constructor array` → the object it constructs, with the array's elements as arguments. + SuperCallSpread, + /// `value` → `value`: binds the running derived constructor's `this` to the value; a + /// `ReferenceError` when it is bound already. + BindThis, + /// Pushes `new.target`. + NewTarget, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +354,15 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is a class constructor's: calling it without `new` is a `TypeError`. + pub(crate) class_ctor: bool, + /// The code is a derived class constructor's: its `this` is bound by `super(…)`. + pub(crate) derived: bool, + /// The code is a class method's or accessor's: it has no `prototype` and is not a + /// constructor. + pub(crate) method: bool, + /// The code reads `new.target`, itself or in an arrow function inside it. + pub(crate) uses_new_target: bool, } impl Code { @@ -347,6 +411,10 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::Dup2 => e(2, 4), Op::Swap | Op::ToKey => e(2, 2), Op::Rot3 => e(3, 3), + Op::Pick(n) => { + let below = n.checked_add(1).ok_or("operand too large")?; + e(below, below.checked_add(1).ok_or("operand too large")?) + } Op::GetVarThis(_) => e(0, 2), Op::SetVar(_) | Op::GetMember(_) | Op::DeleteMember(_) | Op::IncMember { .. } => e(1, 1), Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1), @@ -381,6 +449,19 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), Op::ToStr => e(1, 1), + Op::ClassStart { heritage, .. } => e(u32::from(heritage), 2), + Op::ClassMethod { .. } => e(3, 2), + Op::InitMethod { .. } => e(1, 1), + Op::SuperRef => e(2, 3), + Op::SuperGet => e(3, 1), + Op::SuperGetThis => e(3, 2), + Op::SuperSet => e(4, 1), + Op::SuperDup => e(3, 6), + Op::SuperInc { .. } => e(3, 1), + Op::SuperCtor | Op::NewTarget => e(0, 1), + Op::SuperCall(n) => e(n.checked_add(1).ok_or("operand too large")?, 1), + Op::SuperCallSpread => e(2, 1), + Op::BindThis => e(1, 1), }) } @@ -411,7 +492,11 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { | Op::InitVar(i) | Op::LoadParam(i) | Op::AnnexB(i) => check(i, code.names.len(), "name"), - Op::Closure(i) => check(i, code.functions.len(), "function"), + Op::Closure(i) | Op::ClassStart { ctor: i, .. } | Op::ClassMethod { func: i, .. } => check(i, code.functions.len(), "function"), + Op::InitMethod { func, name, .. } => { + check(func, code.functions.len(), "function")?; + check(name, code.names.len(), "name") + } Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs new file mode 100644 index 0000000000..a6cf6d2949 --- /dev/null +++ b/crates/js/src/class_ops.rs @@ -0,0 +1,484 @@ +//! Classes, `super` and `new.target` (ECMA-262 2015 sections 12.3.5, 12.3.8 and 14.5), and +//! `new` with a `new.target` (sections 7.3.13 and 9.2.2). +//! +//! The running code reaches what these need through bindings whose names start with a NUL, +//! which no identifier holds: +//! +//! - `\0this` holds a derived class constructor's `this`, uninitialized until `super(…)` returns, +//! and the `this` an arrow function closes over. +//! - `\0func` holds a derived class constructor's function object, whose prototype `super(…)` +//! constructs. +//! - `\0newtarget` holds `new.target` for the arrow functions inside a function. +//! - `\0home` holds the home object of a class method, in an environment of the method's own. + +use std::rc::Rc; + +use crate::bytecode::Code; +use crate::heap::{ + Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, Key, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key, + string_bytes, +}; +use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, binding_bytes, closure_bytes, internal}; +use crate::value::{Str, Value}; + +const FUNC: &[u16] = &[0, 0x66, 0x75, 0x6E, 0x63]; +const NEW_TARGET: &[u16] = &[0, 0x6E, 0x65, 0x77, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74]; +const HOME: &[u16] = &[0, 0x68, 0x6F, 0x6D, 0x65]; + +/// The most bound functions `new` and `IsConstructor` unwrap in one chain. +const MAX_BOUND_CHAIN: usize = 10_000; + +/// The bytes of the hidden bindings [`Interp::function_bindings`] adds for `code`. +pub(crate) fn hidden_bytes(code: &Code) -> usize { + if code.derived { + binding_bytes(ARROW_THIS.len()) + binding_bytes(FUNC.len()) + binding_bytes(NEW_TARGET.len()) + } else if code.uses_new_target && !code.arrow { + binding_bytes(NEW_TARGET.len()) + } else { + 0 + } +} + +impl Interp { + /// The nearest declarative environment from `start` outward that holds `name`. + fn hidden_env(&self, start: EnvId, name: &[u16]) -> Option { + let mut cur = Some(start); + while let Some(e) = cur { + match self.heap.env(e)? { + Env::Decl { bindings, outer } => { + if bindings.contains(name) { + return Some(e); + } + cur = *outer; + } + Env::Obj { outer, .. } => cur = *outer, + } + } + None + } + + /// The value of the hidden binding `name` nearest the running code, or `undefined`. + fn hidden_value(&self, name: &[u16]) -> JsResult { + let env = self.frame()?.env; + match self.hidden_env(env, name) { + Some(e) => self.binding_value(e, name), + None => Ok(Value::Undefined), + } + } + + /// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived + /// class constructor's `this`, function object and `new.target`, and the `new.target` of a + /// function whose arrow functions read it. Gives the environment of a derived constructor's + /// `this`. The caller has reserved [`hidden_bytes`] of `code`. + pub(crate) fn function_bindings(&mut self, code: &Code, env: EnvId, callee: ObjId, new_target: Option) -> JsResult> { + let nt = new_target.map_or(Value::Undefined, Value::Object); + if code.derived { + self.env_insert(env, Rc::from(ARROW_THIS), Binding::lexical(false))?; + self.env_insert(env, Rc::from(FUNC), Binding::new(Value::Object(callee), false, false))?; + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + return Ok(Some(env)); + } + if code.uses_new_target && !code.arrow { + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + } + Ok(None) + } + + /// The `this` an arrow function closing over `env` starts with: `undefined` while a derived + /// constructor's `this` is not yet bound. + pub(crate) fn arrow_this(&self, env: EnvId) -> Value { + match self.hidden_env(env, ARROW_THIS) { + Some(e) if !self.uninitialized(e, ARROW_THIS) => self.binding_value(e, ARROW_THIS).unwrap_or(Value::Undefined), + _ => Value::Undefined, + } + } + + fn this_not_bound(&mut self) -> Abrupt { + self.throw(ErrorType::Reference, "'this' is used before super() is called") + } + + /// The value of `this` in the running code (ResolveThisBinding, section 8.3.2). In a derived + /// class constructor and the arrow functions inside it, reading it before `super(…)` returns + /// is a `ReferenceError`. + pub(crate) fn this_value(&mut self) -> JsResult { + let frame = self.frame()?; + if (frame.code.arrow || frame.code.derived) + && let Some(e) = self.hidden_env(frame.env, ARROW_THIS) + { + if self.uninitialized(e, ARROW_THIS) { + return Err(self.this_not_bound()); + } + return self.binding_value(e, ARROW_THIS); + } + Ok(self.frame()?.this.clone()) + } + + /// What a derived class constructor whose `this` is in `env` gives for the return value `v` + /// (section 9.2.2, steps 13 to 15). + pub(crate) fn derived_result(&mut self, env: EnvId, v: Value) -> JsResult { + match v { + Value::Object(_) => Ok(v), + Value::Undefined if self.uninitialized(env, ARROW_THIS) => Err(self.this_not_bound()), + Value::Undefined => self.binding_value(env, ARROW_THIS), + _ => Err(self.type_error("a derived class constructor must return an object or undefined")), + } + } + + /// IsConstructor (section 7.2.4). + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut v = v.clone(); + for _ in 0..MAX_BOUND_CHAIN { + match self.func_of(&v) { + Some(Func::Closure { code, .. }) => return !(code.arrow || code.method), + Some(Func::Native { constructor, .. }) => return constructor, + Some(Func::Bound { target, .. }) => v = Value::Object(target), + _ => return false, + } + } + false + } + + /// Does the built-in constructor `f` make objects that a subclass may give its own + /// prototype? It does when its `prototype` is one of the realm's built-in prototypes. + fn subclassable(&self, f: ObjId) -> JsResult { + let Some(Prop::Data { value: Value::Object(p), .. }) = self.get_own_property(f, &key("prototype"))? else { return Ok(false) }; + let i = &self.intrinsics; + Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] + .contains(&p) + || i.error_protos.contains(&p)) + } + + /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). + fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { + match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { + Value::Object(p) => Ok(p), + _ => Ok(fallback), + } + } + + /// Does the prototype chain from `start` reach `target`? + fn chain_reaches(&self, start: ObjId, target: ObjId) -> JsResult { + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if o == target { + return Ok(true); + } + steps += 1; + if steps > 1_000_000 { + return Ok(true); + } + cur = self.object(o)?.proto; + } + Ok(false) + } + + /// Constructs `f` with `args` and `new_target` (`f` itself when `None`) and pushes the + /// result, or the frame that makes it, after taking the stack back to `start`. The operands + /// at `start` and above keep `f` and `args` reachable. + pub(crate) fn construct(&mut self, start: usize, f: Value, mut args: Vec, new_target: Option) -> JsResult<()> { + let mut f = f; + let mut new_target = new_target; + // A bound function constructs its target with its arguments first, and a `new.target` + // that is the bound function becomes the target (section 9.4.1.2). + let mut steps = 0usize; + while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { + self.use_fuel()?; + steps += 1; + if steps > MAX_BOUND_CHAIN { + return Err(self.type_error("the value is not a constructor")); + } + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + if new_target.is_some() && new_target == f.as_object() { + new_target = Some(target); + } + f = Value::Object(target); + } + let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) }; + let nt = new_target.unwrap_or(callee); + match self.func_of(&f) { + Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), + Some(Func::Closure { code, env }) if code.derived => { + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, false) + } + Some(Func::Closure { code, env }) => { + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), false) + } + Some(Func::Native { f: native, constructor: true, .. }) => { + let subclass = nt != callee; + if subclass && !self.subclassable(callee)? { + return Err(self.type_error("this built-in cannot be subclassed")); + } + let intrinsic = match self.get_own_property(callee, &key("prototype"))? { + Some(Prop::Data { value: Value::Object(p), .. }) => Some(p), + _ => None, + }; + let v = if subclass && intrinsic == Some(self.intrinsics.object_proto) { + // `Object` constructed for a subclass makes an ordinary object, whatever its + // argument (section 19.1.1.1, step 1). + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else { + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + let v = r?; + if subclass && let Value::Object(o) = v { + let proto = self.rooted(std::slice::from_ref(&v), |i| { + let fallback = intrinsic.unwrap_or(i.intrinsics.object_proto); + i.prototype_from(nt, fallback) + })?; + if self.object(o)?.proto == intrinsic && !self.chain_reaches(proto, o)? { + self.object_mut(o)?.proto = Some(proto); + } + } + v + }; + self.stack.truncate(start); + self.push(v) + } + _ => Err(self.type_error("the value is not a constructor")), + } + } + + /// `heritage?` → `F proto`: the constructor and prototype of a class whose constructor is + /// `functions[ctor]` (ClassDefinitionEvaluation, section 14.5.14, steps 5 to 18). + pub(crate) fn op_class_start(&mut self, ctor: u32, heritage: bool) -> JsResult<()> { + self.use_fuel()?; + let (proto_parent, ctor_parent) = if heritage { + let h = self.peek(0)?; + match h { + Value::Null => (None, self.intrinsics.function_proto), + Value::Object(c) if self.is_constructor(&h) => match self.get_from(c, &key("prototype"), &h)? { + Value::Object(p) => (Some(p), c), + Value::Null => (None, c), + _ => return Err(self.type_error("the prototype of the class's superclass is not an object or null")), + }, + _ => return Err(self.type_error("a class can extend only a constructor or null")), + } + } else { + (Some(self.intrinsics.object_proto), self.intrinsics.function_proto) + }; + let frame = self.frame()?; + let env = frame.env; + let Some(code) = frame.code.functions.get(ctor as usize).cloned() else { return internal("function out of range") }; + let need = (2 * OBJECT_BYTES) + .saturating_add(ENV_BYTES) + .saturating_add(binding_bytes(HOME.len())) + .saturating_add(closure_bytes(&code)) + .saturating_add(binding_bytes("prototype".len())) + .saturating_add(binding_bytes("constructor".len())); + let roots: Vec = proto_parent.map(Value::Object).into_iter().collect(); + self.rooted(&roots, |i| i.reserve_heap(need))?; + let proto = self.heap.alloc_object(Object::new(Class::Ordinary, proto_parent)); + // The constructor's home object is the prototype, as for the other prototype methods + // (section 14.5.14, step 12). + let home = self.home_env(proto, env); + let f = self.make_closure(code, home)?; + self.object_mut(f)?.proto = Some(ctor_parent); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + self.define(proto, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; + if heritage { + self.pop()?; + } + self.push(Value::Object(f))?; + self.push(Value::Object(proto)) + } + + /// An environment inside `outer` whose home object is `home`. + fn home_env(&mut self, home: ObjId, outer: EnvId) -> EnvId { + let mut bindings = PropMap::default(); + bindings.insert(Rc::from(HOME), Binding::new(Value::Object(home), false, false)); + self.heap.bytes += string_bytes(HOME.len()); + self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) }) + } + + /// `F proto key` → `F proto`: defines the method `functions[func]` (`kind` 0), getter (1) or + /// setter (2) named `key` on the prototype, or with `is_static` on the constructor (section + /// 14.3.8 and 14.5.14, step 21). + pub(crate) fn op_class_method(&mut self, func: u32, kind: u8, is_static: bool) -> JsResult<()> { + let kv = self.peek(0)?; + let k: Key = self.to_key(&kv)?; + let Value::Object(target) = self.peek(if is_static { 2 } else { 1 })? else { return internal("class operand is not an object") }; + self.define_method(target, k, func, kind, false)?; + self.pop().map(drop) + } + + /// `object` → `object`: defines an object literal's method or accessor `functions[func]` + /// under `names[name]` (section 12.2.6.8). + pub(crate) fn op_init_method(&mut self, func: u32, kind: u8, name: u32) -> JsResult<()> { + let k = self.name(name)?; + let Value::Object(target) = self.peek(0)? else { return internal("object literal is not an object") }; + self.define_method(target, k, func, kind, true) + } + + /// Defines the method (`kind` 0), getter (1) or setter (2) made from `functions[func]` of the + /// running code under `k` on `target`, its home object (MakeMethod, section 14.3.8). The + /// caller keeps `target` reachable. + fn define_method(&mut self, target: ObjId, k: Key, func: u32, kind: u8, enumerable: bool) -> JsResult<()> { + self.use_fuel()?; + let frame = self.frame()?; + let env = frame.env; + let Some(code) = frame.code.functions.get(func as usize).cloned() else { return internal("function out of range") }; + let need = OBJECT_BYTES + .saturating_add(ENV_BYTES) + .saturating_add(binding_bytes(HOME.len())) + .saturating_add(closure_bytes(&code)) + .saturating_add(binding_bytes(k.len())); + let root = Value::String(Str::from_rc(k.clone())); + self.rooted(&[root], |i| i.reserve_heap(need))?; + let home = self.home_env(target, env); + let f = self.make_closure(code, home)?; + let (enumerable, configurable) = (Some(enumerable), Some(true)); + let desc = match kind { + 0 => Desc { value: Some(Value::Object(f)), writable: Some(true), enumerable, configurable, ..Desc::default() }, + 1 => Desc { get: Some(Some(f)), enumerable, configurable, ..Desc::default() }, + _ => Desc { set: Some(Some(f)), enumerable, configurable, ..Desc::default() }, + }; + self.rooted(&[Value::Object(f)], |i| i.define_own_property(target, k, &desc, true)).map(drop) + } + + /// `this key` → `this home key`: the prototype of the running method's home object, `null` + /// when it has none, and the key as a property name (MakeSuperPropertyReference, section + /// 12.3.5.3). + pub(crate) fn op_super_ref(&mut self) -> JsResult<()> { + let kv = self.peek(0)?; + let k = self.to_key(&kv)?; + let Value::Object(home) = self.hidden_value(HOME)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in methods")) }; + let proto = self.object(home)?.proto.map_or(Value::Null, Value::Object); + self.replace(1, proto)?; + self.push(Value::String(Str::from_rc(k))) + } + + /// The three operands of a `super` property: `this`, the prototype and the key. + fn super_operands(&mut self, depth: usize) -> JsResult<(Value, ObjId, Key)> { + let k = self.peek(depth)?; + let proto = self.peek(depth + 1)?; + let this = self.peek(depth + 2)?; + let k = self.to_key(&k)?; + let Value::Object(p) = proto else { + let name = String::from_utf16_lossy(&k); + return Err(self.type_error(&format!("cannot use super property '{name}': the home object has no prototype"))); + }; + Ok((this, p, k)) + } + + /// `this home key` → `value`, or with `with_this` → `value this`. + pub(crate) fn op_super_get(&mut self, with_this: bool) -> JsResult<()> { + let (this, p, k) = self.super_operands(0)?; + let v = self.get_from(p, &k, &this)?; + self.replace(3, v)?; + if with_this { self.push(this) } else { Ok(()) } + } + + /// `this home key value` → `value`. + pub(crate) fn op_super_set(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let (this, p, k) = self.super_operands(1)?; + self.super_put(p, k, v.clone(), &this)?; + self.replace(4, v) + } + + /// `this home key` → the old or new number of a `++` or `--` on a `super` property. + pub(crate) fn op_super_inc(&mut self, prefix: bool, dec: bool) -> JsResult<()> { + let (this, p, k) = self.super_operands(0)?; + let v = self.get_from(p, &k, &this)?; + let old = self.to_number(&v)?; + let new = if dec { old - 1.0 } else { old + 1.0 }; + self.super_put(p, k, Value::Number(new), &this)?; + self.replace(3, Value::Number(if prefix { new } else { old })) + } + + /// [[Set]] of `k` on `proto` with `receiver` as `this` (OrdinarySet, section 9.1.9). A write + /// that cannot be made throws a `TypeError` in strict mode code and does nothing otherwise + /// (PutValue, section 6.2.3.2). + fn super_put(&mut self, proto: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<()> { + let throw = self.frame()?.code.strict; + let why = match self.find_property(proto, &k)? { + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"), + _ => None, + }; + let (r, desc) = match (why, receiver) { + (Some(why), _) => return self.super_reject(throw, &k, why), + (None, Value::Object(r)) => match self.get_own_property(*r, &k)? { + Some(Prop::Accessor { .. }) => return self.super_reject(throw, &k, "it is an accessor"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.super_reject(throw, &k, "it is read-only"), + Some(Prop::Data { .. }) => (*r, Desc { value: Some(v), ..Desc::default() }), + None => (*r, Desc::data(v, WRITABLE | ENUMERABLE | CONFIGURABLE)), + }, + (None, _) => return self.super_reject(throw, &k, "`this` is a primitive value"), + }; + self.define_own_property(r, k, &desc, throw).map(drop) + } + + fn super_reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { + if !throw { + return Ok(()); + } + let name = String::from_utf16_lossy(k); + Err(self.type_error(&format!("cannot assign to property '{name}': {why}"))) + } + + /// Pushes the constructor `super(…)` calls: the prototype of the running derived class + /// constructor (GetSuperConstructor, section 12.3.5.2). + pub(crate) fn op_super_ctor(&mut self) -> JsResult<()> { + let Value::Object(f) = self.hidden_value(FUNC)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in constructors")) }; + let proto = self.object(f)?.proto.map_or(Value::Null, Value::Object); + self.push(proto) + } + + /// `ctor args…` → the object `ctor` constructs with the running code's `new.target` + /// (section 12.3.5.1, steps 6 to 9). + pub(crate) fn op_super_call(&mut self, argc: u32) -> JsResult<()> { + let n = argc as usize; + let start = + self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("super call below the stack".into()))?; + let ctor = self.stack.get(start).cloned().unwrap_or(Value::Undefined); + if !self.is_constructor(&ctor) { + return Err(self.type_error("the superclass is not a constructor")); + } + let Value::Object(nt) = self.hidden_value(NEW_TARGET)? else { return Err(self.type_error("super() needs new.target")) }; + let args: Vec = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default(); + self.construct(start, ctor, args, Some(nt)) + } + + /// `value` → `value`: binds the running derived class constructor's `this` to the object + /// `super(…)` made; a second binding is a `ReferenceError` (section 8.1.1.3.1). + pub(crate) fn op_bind_this(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let frame = self.frame()?; + let (start, own) = (frame.env, frame.this_env); + let Some(env) = self.hidden_env(start, ARROW_THIS) else { return internal("super() outside a derived constructor") }; + if !self.uninitialized(env, ARROW_THIS) { + return Err(self.throw(ErrorType::Reference, "super() was already called")); + } + if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) + && let Some(b) = bindings.get_mut(ARROW_THIS) + { + b.value = v.clone(); + b.uninitialized = false; + } + if own == Some(env) { + self.frame_mut()?.this = v; + } + Ok(()) + } + + /// Pushes `new.target` (section 12.3.8.1). + pub(crate) fn op_new_target(&mut self) -> JsResult<()> { + let frame = self.frame()?; + let v = if frame.code.arrow { self.hidden_value(NEW_TARGET)? } else { frame.new_target.map_or(Value::Undefined, Value::Object) }; + self.push(v) + } +} diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..5f4a82ecb4 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -17,8 +17,8 @@ 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, ClassDef, ClassKey, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, MethodKind, + 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}; @@ -93,6 +93,7 @@ struct FnCompiler<'a> { scopes: Vec, templates: Vec