diff --git a/ASSETS.md b/ASSETS.md index 5e3dc3281c..9220086fa7 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -16,6 +16,15 @@ | `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file | | `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file | +## Printing-condition characterization data + +Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed. + +| Asset | Author | Source | Licence | Notes | +|---|---|---|---|---| +| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) | +| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) | + Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table. **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). diff --git a/Cargo.lock b/Cargo.lock index 0417aba6f0..e6d867905b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,6 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", ] @@ -8786,6 +8787,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-geom 0.24.1", + "vectorcraft-js", "wasmi", "wasmparser 0.228.0", "wat", @@ -8930,6 +8932,7 @@ dependencies = [ "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", "vectorcraft-text", + "vectorcraft-tools", ] [[package]] diff --git a/NOTICE b/NOTICE index 434cd3e524..99d05d6235 100644 --- a/NOTICE +++ b/NOTICE @@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option. Original copyright and full license notices are preserved in each hyph-*.tex file. Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5. +FOGRA51 and FOGRA52 characterization data (crates/color/data/): +Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org, +https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed +unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is +permitted, including redistribution as part of commercial and non-commercial software, provided +that the data are distributed unmodified and Fogra is identified as the source. The designation +FOGRAxx may be used solely to identify the respective reference data. Such use does not imply +certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and +Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code; +they are not Fogra profiles. + JPEG encoder dependency notices diff --git a/ROADMAP.md b/ROADMAP.md index abd6a3548b..c8c020dcd3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -142,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. @@ -151,6 +153,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 6b4e0b8344..2416b17b89 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,11 +238,13 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each +/// script's `Folder.userData` in the Script Data folder there, keeps File Info's /// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_startup_scripts_dir(&mut h.session); prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index db055d3246..8907fe4bd1 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -824,6 +824,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // The startup scripts are in the Startup Scripts folder next to the preferences. + prefs_dir::attach_startup_scripts_dir(&mut session); // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); @@ -977,6 +979,9 @@ fn main() -> std::process::ExitCode { single_instance::set_ui(&cc.egui_ctx); } let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files)); + // With General › Run Startup Scripts on and Safe Mode off, the startup scripts run + // now, as the person's own; in Safe Mode they wait for the choice that ends it. + file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index b4940d192d..8f1b50dd58 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -66,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only +/// read: the user makes it. +pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Startup Scripts") { + session.attach_startup_scripts_dir(dir); + } +} + /// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template /// makes. pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 53fa68502a..f97d3db59d 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -22,3 +22,4 @@ moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } serde_json = { workspace = true } +sha2 = { version = "0.10", default-features = false } diff --git a/crates/color/data/.gitattributes b/crates/color/data/.gitattributes new file mode 100644 index 0000000000..05b9b7ef3c --- /dev/null +++ b/crates/color/data/.gitattributes @@ -0,0 +1,2 @@ +# The characterization data files are kept byte for byte as published (CRLF line endings). +*.txt -text diff --git a/crates/color/data/FOGRA51.txt b/crates/color/data/FOGRA51.txt new file mode 100644 index 0000000000..1bf721cbbd --- /dev/null +++ b/crates/color/data/FOGRA51.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA51" +ORIGINATOR "Fogra, www.fogra.org, developed by GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 1 = premium coated, fluorescence moderate (8-14 DeltaB according to ISO 15397), 115 g/m2, tone value increase curves A (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 95.00 1.50 -6.00 +2 0 10 0 0 90.08 8.15 -7.42 +3 0 20 0 0 85.20 14.67 -8.29 +4 0 30 0 0 80.33 21.39 -8.87 +5 0 40 0 0 75.43 28.45 -9.24 +6 0 55 0 0 67.98 40.01 -9.56 +7 0 70 0 0 60.42 52.69 -9.17 +8 0 85 0 0 53.32 65.54 -7.71 +9 0 100 0 0 48.06 75.29 -5.18 +10 10 0 0 0 91.19 -2.28 -10.93 +11 10 10 0 0 86.47 4.14 -11.97 +12 10 20 0 0 81.74 10.48 -12.69 +13 10 30 0 0 77.05 17.05 -13.20 +14 10 40 0 0 72.39 23.71 -13.36 +15 10 55 0 0 65.04 35.29 -13.80 +16 10 70 0 0 57.69 47.54 -13.21 +17 10 85 0 0 50.64 60.42 -12.20 +18 10 100 0 0 45.36 70.44 -10.15 +19 20 0 0 0 87.20 -5.64 -15.58 +20 20 10 0 0 82.71 0.55 -16.41 +21 20 20 0 0 78.13 6.82 -17.10 +22 20 30 0 0 73.63 12.96 -17.21 +23 20 40 0 0 69.00 19.75 -17.58 +24 20 55 0 0 61.92 30.79 -17.90 +25 20 70 0 0 54.67 43.07 -17.59 +26 20 85 0 0 47.85 55.48 -16.64 +27 20 100 0 0 42.75 65.36 -14.76 +28 30 0 0 0 83.19 -9.04 -20.26 +29 30 10 0 0 78.86 -3.06 -21.03 +30 30 20 0 0 74.49 3.06 -21.47 +31 30 30 0 0 70.10 9.12 -21.61 +32 30 40 0 0 65.63 15.55 -21.84 +33 30 55 0 0 58.82 26.25 -21.96 +34 30 70 0 0 51.79 38.09 -21.59 +35 30 85 0 0 45.06 50.62 -20.96 +36 30 100 0 0 40.08 60.48 -19.61 +37 40 0 0 0 79.15 -12.57 -24.94 +38 40 10 0 0 74.98 -6.71 -25.60 +39 40 20 0 0 70.80 -0.81 -25.82 +40 40 30 0 0 66.54 5.13 -25.91 +41 40 40 0 0 62.24 11.37 -26.06 +42 40 55 0 0 55.70 21.88 -26.29 +43 40 70 0 0 48.86 33.45 -25.85 +44 40 85 0 0 42.31 45.45 -25.15 +45 40 100 0 0 37.42 55.26 -24.13 +46 55 0 0 0 72.95 -18.09 -32.32 +47 55 10 0 0 69.08 -12.46 -32.61 +48 55 20 0 0 65.15 -6.92 -32.53 +49 55 30 0 0 61.16 -1.28 -32.51 +50 55 40 0 0 57.13 4.79 -32.58 +51 55 55 0 0 50.88 15.11 -32.86 +52 55 70 0 0 44.47 25.94 -32.21 +53 55 85 0 0 38.22 37.55 -31.73 +54 55 100 0 0 33.61 47.12 -31.03 +55 70 0 0 0 66.57 -24.03 -39.84 +56 70 10 0 0 63.02 -18.76 -39.93 +57 70 20 0 0 59.38 -13.26 -39.73 +58 70 30 0 0 55.73 -8.01 -39.46 +59 70 40 0 0 51.98 -2.30 -39.36 +60 70 55 0 0 46.09 7.47 -39.17 +61 70 70 0 0 40.13 17.91 -38.49 +62 70 85 0 0 34.29 29.43 -38.42 +63 70 100 0 0 30.05 38.27 -37.82 +64 85 0 0 0 60.62 -30.20 -47.07 +65 85 10 0 0 57.34 -25.34 -47.00 +66 85 20 0 0 54.05 -20.11 -46.39 +67 85 30 0 0 50.67 -14.86 -46.05 +68 85 40 0 0 47.21 -9.60 -45.78 +69 85 55 0 0 41.82 -0.52 -45.22 +70 85 70 0 0 36.22 9.96 -44.61 +71 85 85 0 0 30.93 20.56 -44.00 +72 85 100 0 0 26.93 28.85 -43.51 +73 100 0 0 0 56.12 -34.90 -52.52 +74 100 10 0 0 53.12 -30.18 -52.18 +75 100 20 0 0 49.98 -25.20 -51.65 +76 100 30 0 0 46.82 -20.29 -51.01 +77 100 40 0 0 43.67 -14.81 -50.35 +78 100 55 0 0 38.75 -6.19 -49.58 +79 100 70 0 0 33.65 3.36 -48.78 +80 100 85 0 0 28.60 13.42 -48.00 +81 100 100 0 0 24.74 21.12 -47.45 +82 0 0 10 0 94.39 -0.05 3.02 +83 0 10 10 0 89.49 6.73 1.30 +84 0 20 10 0 84.62 13.27 0.10 +85 0 30 10 0 79.82 20.14 -0.92 +86 0 40 10 0 75.00 27.19 -1.77 +87 0 55 10 0 67.58 39.10 -2.81 +88 0 70 10 0 60.05 51.73 -2.96 +89 0 85 10 0 53.14 64.72 -2.17 +90 0 100 10 0 48.16 74.50 -0.60 +91 10 0 10 0 90.49 -4.02 -1.77 +92 10 10 10 0 85.82 2.56 -3.46 +93 10 20 10 0 81.12 9.05 -4.50 +94 10 30 10 0 76.46 15.71 -5.46 +95 10 40 10 0 71.79 22.68 -6.25 +96 10 55 10 0 64.57 34.21 -7.17 +97 10 70 10 0 57.26 46.86 -7.31 +98 10 85 10 0 50.43 59.66 -6.79 +99 10 100 10 0 45.39 69.49 -5.43 +100 20 0 10 0 86.44 -7.45 -6.60 +101 20 10 10 0 82.01 -1.17 -8.02 +102 20 20 10 0 77.49 5.15 -8.92 +103 20 30 10 0 72.97 11.64 -9.73 +104 20 40 10 0 68.44 18.44 -10.47 +105 20 55 10 0 61.44 29.71 -11.32 +106 20 70 10 0 54.31 42.07 -11.62 +107 20 85 10 0 47.62 54.54 -11.26 +108 20 100 10 0 42.65 64.50 -10.16 +109 30 0 10 0 82.42 -11.08 -11.48 +110 30 10 10 0 78.15 -5.00 -12.67 +111 30 20 10 0 73.82 1.16 -13.49 +112 30 30 10 0 69.44 7.49 -14.18 +113 30 40 10 0 65.05 14.11 -14.78 +114 30 55 10 0 58.30 25.08 -15.56 +115 30 70 10 0 51.40 37.07 -15.81 +116 30 85 10 0 44.85 49.58 -15.76 +117 30 100 10 0 40.03 59.14 -14.92 +118 40 0 10 0 78.34 -14.91 -16.35 +119 40 10 10 0 74.24 -8.90 -17.42 +120 40 20 10 0 70.09 -2.91 -17.98 +121 40 30 10 0 65.91 3.27 -18.54 +122 40 40 10 0 61.68 9.69 -19.12 +123 40 55 10 0 55.18 20.32 -19.84 +124 40 70 10 0 48.45 32.09 -20.21 +125 40 85 10 0 42.11 44.34 -20.15 +126 40 100 10 0 37.43 53.85 -19.55 +127 55 0 10 0 72.13 -20.88 -23.94 +128 55 10 10 0 68.33 -15.07 -24.69 +129 55 20 10 0 64.46 -9.33 -25.04 +130 55 30 10 0 60.56 -3.46 -25.47 +131 55 40 10 0 56.60 2.73 -25.84 +132 55 55 10 0 50.46 12.95 -26.33 +133 55 70 10 0 44.07 24.26 -26.67 +134 55 85 10 0 37.99 36.05 -26.83 +135 55 100 10 0 33.49 45.40 -26.61 +136 70 0 10 0 65.70 -27.36 -31.85 +137 70 10 10 0 62.29 -21.91 -32.17 +138 70 20 10 0 58.73 -16.35 -32.31 +139 70 30 10 0 55.11 -10.78 -32.46 +140 70 40 10 0 51.44 -4.87 -32.68 +141 70 55 10 0 45.66 4.96 -33.04 +142 70 70 10 0 39.72 15.80 -33.20 +143 70 85 10 0 34.08 27.07 -33.31 +144 70 100 10 0 29.85 36.13 -33.10 +145 85 0 10 0 59.68 -34.68 -39.35 +146 85 10 10 0 56.58 -29.13 -39.40 +147 85 20 10 0 53.35 -23.81 -39.27 +148 85 30 10 0 50.01 -18.41 -39.22 +149 85 40 10 0 46.60 -12.87 -39.27 +150 85 55 10 0 41.29 -3.48 -39.33 +151 85 70 10 0 35.80 6.88 -39.36 +152 85 85 10 0 30.60 17.60 -39.25 +153 85 100 10 0 26.69 26.51 -39.05 +154 100 0 10 0 55.09 -39.46 -45.04 +155 100 10 10 0 52.33 -34.67 -44.86 +156 100 20 10 0 49.27 -29.55 -44.55 +157 100 30 10 0 46.18 -24.31 -44.32 +158 100 40 10 0 43.11 -18.79 -44.05 +159 100 55 10 0 38.18 -9.90 -43.86 +160 100 70 10 0 33.15 -0.14 -43.50 +161 100 85 10 0 28.30 10.01 -43.28 +162 100 100 10 0 24.62 18.19 -43.14 +163 0 0 20 0 93.66 -1.17 11.88 +164 0 10 20 0 88.80 5.61 9.82 +165 0 20 20 0 83.99 12.38 8.29 +166 0 30 20 0 79.22 19.33 6.84 +167 0 40 20 0 74.45 26.49 5.48 +168 0 55 20 0 67.16 38.37 3.96 +169 0 70 20 0 59.71 51.18 3.25 +170 0 85 20 0 52.90 63.96 3.39 +171 0 100 20 0 48.12 73.47 4.61 +172 10 0 20 0 89.71 -5.18 6.94 +173 10 10 20 0 85.11 1.37 4.94 +174 10 20 20 0 80.48 7.98 3.55 +175 10 30 20 0 75.86 14.70 2.17 +176 10 40 20 0 71.22 21.76 0.95 +177 10 55 20 0 64.07 33.39 -0.52 +178 10 70 20 0 56.85 46.17 -1.38 +179 10 85 20 0 50.19 58.88 -1.37 +180 10 100 20 0 45.29 68.63 -0.38 +181 20 0 20 0 85.72 -8.99 2.17 +182 20 10 20 0 81.30 -2.54 0.32 +183 20 20 20 0 76.83 3.86 -1.11 +184 20 30 20 0 72.35 10.44 -2.33 +185 20 40 20 0 67.84 17.35 -3.39 +186 20 55 20 0 60.91 28.74 -4.79 +187 20 70 20 0 53.93 41.13 -5.60 +188 20 85 20 0 47.39 53.82 -5.87 +189 20 100 20 0 42.55 63.34 -5.04 +190 30 0 20 0 81.66 -12.79 -2.89 +191 30 10 20 0 77.44 -6.52 -4.62 +192 30 20 20 0 73.13 -0.29 -5.75 +193 30 30 20 0 68.80 6.12 -6.82 +194 30 40 20 0 64.43 12.85 -7.84 +195 30 55 20 0 57.77 23.97 -9.14 +196 30 70 20 0 50.99 36.22 -10.04 +197 30 85 20 0 44.59 48.53 -10.43 +198 30 100 20 0 39.88 58.18 -9.88 +199 40 0 20 0 77.55 -16.73 -7.99 +200 40 10 20 0 73.52 -10.68 -9.43 +201 40 20 20 0 69.39 -4.59 -10.41 +202 40 30 20 0 65.23 1.69 -11.32 +203 40 40 20 0 61.04 8.29 -12.27 +204 40 55 20 0 54.63 19.05 -13.50 +205 40 70 20 0 48.07 30.94 -14.39 +206 40 85 20 0 41.81 43.21 -15.01 +207 40 100 20 0 37.28 52.69 -14.60 +208 55 0 20 0 71.31 -23.09 -15.80 +209 55 10 20 0 67.58 -17.25 -16.84 +210 55 20 20 0 63.73 -11.42 -17.58 +211 55 30 20 0 59.85 -5.38 -18.43 +212 55 40 20 0 55.97 0.93 -19.08 +213 55 55 20 0 49.94 11.27 -20.01 +214 55 70 20 0 43.68 22.77 -20.85 +215 55 85 20 0 37.73 34.62 -21.62 +216 55 100 20 0 33.31 43.89 -21.69 +217 70 0 20 0 64.93 -30.24 -23.83 +218 70 10 20 0 61.50 -24.61 -24.57 +219 70 20 20 0 57.98 -18.95 -25.00 +220 70 30 20 0 54.40 -13.10 -25.57 +221 70 40 20 0 50.79 -7.11 -26.06 +222 70 55 20 0 45.17 2.77 -26.82 +223 70 70 20 0 39.33 13.82 -27.50 +224 70 85 20 0 33.74 25.26 -28.26 +225 70 100 20 0 29.61 34.33 -28.32 +226 85 0 20 0 58.88 -38.00 -31.58 +227 85 10 20 0 55.83 -32.55 -31.96 +228 85 20 20 0 52.62 -27.03 -32.09 +229 85 30 20 0 49.31 -21.43 -32.36 +230 85 40 20 0 45.93 -15.65 -32.81 +231 85 55 20 0 40.74 -6.29 -33.32 +232 85 70 20 0 35.38 4.26 -33.81 +233 85 85 20 0 30.26 15.11 -34.30 +234 85 100 20 0 26.54 23.88 -34.29 +235 100 0 20 0 54.45 -43.84 -37.25 +236 100 10 20 0 51.62 -38.86 -37.54 +237 100 20 20 0 48.62 -33.48 -37.55 +238 100 30 20 0 45.58 -28.05 -37.59 +239 100 40 20 0 42.45 -22.44 -37.78 +240 100 55 20 0 37.59 -13.09 -37.99 +241 100 70 20 0 32.60 -3.11 -38.23 +242 100 85 20 0 27.97 7.02 -38.33 +243 100 100 20 0 24.56 15.08 -38.49 +244 0 0 30 0 92.93 -2.11 20.82 +245 0 10 30 0 88.12 4.83 18.28 +246 0 20 30 0 83.36 11.75 16.24 +247 0 30 30 0 78.60 18.51 14.37 +248 0 40 30 0 73.91 25.86 12.81 +249 0 55 30 0 66.79 37.74 10.67 +250 0 70 30 0 59.48 50.64 9.35 +251 0 85 30 0 52.78 63.42 8.80 +252 0 100 30 0 48.13 72.82 9.76 +253 10 0 30 0 88.96 -6.25 15.64 +254 10 10 30 0 84.38 0.40 13.34 +255 10 20 30 0 79.79 7.05 11.44 +256 10 30 30 0 75.22 13.84 9.77 +257 10 40 30 0 70.66 20.96 8.20 +258 10 55 30 0 63.65 32.73 6.16 +259 10 70 30 0 56.56 45.35 4.71 +260 10 85 30 0 50.04 58.07 4.09 +261 10 100 30 0 45.28 67.61 4.74 +262 20 0 30 0 84.94 -10.13 10.68 +263 20 10 30 0 80.55 -3.72 8.48 +264 20 20 30 0 76.13 2.80 6.78 +265 20 30 30 0 71.71 9.46 5.24 +266 20 40 30 0 67.28 16.43 3.81 +267 20 55 30 0 60.45 27.89 1.78 +268 20 70 30 0 53.60 40.27 0.33 +269 20 85 30 0 47.22 53.05 -0.46 +270 20 100 30 0 42.46 62.48 0.00 +271 30 0 30 0 80.90 -14.17 5.54 +272 30 10 30 0 76.69 -7.84 3.48 +273 30 20 30 0 72.44 -1.53 1.92 +274 30 30 30 0 68.15 4.97 0.52 +275 30 40 30 0 63.83 11.80 -0.74 +276 30 55 30 0 57.26 22.97 -2.61 +277 30 70 30 0 50.59 35.16 -4.16 +278 30 85 30 0 44.35 47.52 -5.07 +279 30 100 30 0 39.76 57.01 -4.74 +280 40 0 30 0 76.82 -18.46 0.41 +281 40 10 30 0 72.77 -12.19 -1.43 +282 40 20 30 0 68.68 -6.06 -2.83 +283 40 30 30 0 64.56 0.33 -4.14 +284 40 40 30 0 60.43 6.99 -5.30 +285 40 55 30 0 54.10 17.91 -7.03 +286 40 70 30 0 47.63 29.88 -8.51 +287 40 85 30 0 41.55 42.11 -9.54 +288 40 100 30 0 37.11 51.53 -9.65 +289 55 0 30 0 70.50 -25.13 -7.66 +290 55 10 30 0 66.84 -19.26 -9.16 +291 55 20 30 0 62.99 -13.24 -10.21 +292 55 30 30 0 59.14 -7.08 -11.30 +293 55 40 30 0 55.33 -0.69 -12.30 +294 55 55 30 0 49.41 9.81 -13.81 +295 55 70 30 0 43.25 21.40 -15.18 +296 55 85 30 0 37.44 33.28 -16.35 +297 55 100 30 0 33.22 42.37 -16.72 +298 70 0 30 0 64.19 -32.83 -15.78 +299 70 10 30 0 60.75 -27.06 -16.96 +300 70 20 30 0 57.25 -21.23 -17.84 +301 70 30 30 0 53.69 -15.28 -18.64 +302 70 40 30 0 50.13 -9.20 -19.42 +303 70 55 30 0 44.66 0.84 -20.69 +304 70 70 30 0 38.92 12.02 -21.93 +305 70 85 30 0 33.50 23.44 -22.97 +306 70 100 30 0 29.46 32.47 -23.51 +307 85 0 30 0 58.20 -40.80 -23.80 +308 85 10 30 0 55.08 -35.60 -24.55 +309 85 20 30 0 51.91 -29.96 -25.06 +310 85 30 30 0 48.63 -24.28 -25.64 +311 85 40 30 0 45.31 -18.47 -26.30 +312 85 55 30 0 40.24 -8.71 -27.30 +313 85 70 30 0 34.98 1.95 -28.25 +314 85 85 30 0 29.96 12.75 -29.23 +315 85 100 30 0 26.31 21.41 -29.66 +316 100 0 30 0 53.75 -47.89 -29.55 +317 100 10 30 0 50.87 -42.60 -30.25 +318 100 20 30 0 47.88 -37.15 -30.69 +319 100 30 30 0 44.86 -31.58 -31.07 +320 100 40 30 0 41.80 -25.81 -31.46 +321 100 55 30 0 37.06 -16.36 -32.11 +322 100 70 30 0 32.17 -6.06 -32.78 +323 100 85 30 0 27.64 4.24 -33.30 +324 100 100 30 0 24.42 12.12 -33.86 +325 0 0 40 0 92.30 -2.85 30.21 +326 0 10 40 0 87.51 4.01 27.25 +327 0 20 40 0 82.77 11.08 24.69 +328 0 30 40 0 78.05 17.89 22.50 +329 0 40 40 0 73.41 25.29 20.43 +330 0 55 40 0 66.38 37.19 17.71 +331 0 70 40 0 59.22 49.87 15.87 +332 0 85 40 0 52.68 62.69 14.60 +333 0 100 40 0 48.17 72.08 14.73 +334 10 0 40 0 88.35 -7.18 24.87 +335 10 10 40 0 83.73 -0.45 22.05 +336 10 20 40 0 79.16 6.30 19.75 +337 10 30 40 0 74.64 13.16 17.72 +338 10 40 40 0 70.14 20.29 15.78 +339 10 55 40 0 63.25 32.11 13.18 +340 10 70 40 0 56.28 44.74 11.11 +341 10 85 40 0 49.91 57.53 9.88 +342 10 100 40 0 45.28 67.03 9.82 +343 20 0 40 0 84.26 -11.13 19.59 +344 20 10 40 0 79.86 -4.64 17.06 +345 20 20 40 0 75.48 1.93 14.90 +346 20 30 40 0 71.13 8.64 13.02 +347 20 40 40 0 66.77 15.64 11.23 +348 20 55 40 0 60.06 27.12 8.66 +349 20 70 40 0 53.30 39.52 6.57 +350 20 85 40 0 47.08 52.15 5.20 +351 20 100 40 0 42.48 61.62 5.11 +352 30 0 40 0 80.13 -15.20 14.20 +353 30 10 40 0 75.98 -9.00 11.91 +354 30 20 40 0 71.79 -2.59 9.96 +355 30 30 40 0 67.57 3.98 8.28 +356 30 40 40 0 63.34 10.85 6.55 +357 30 55 40 0 56.85 22.07 4.10 +358 30 70 40 0 50.28 34.34 2.00 +359 30 85 40 0 44.20 46.84 0.51 +360 30 100 40 0 39.73 56.15 0.27 +361 40 0 40 0 76.04 -19.68 8.86 +362 40 10 40 0 72.08 -13.55 6.80 +363 40 20 40 0 68.03 -7.37 5.09 +364 40 30 40 0 63.97 -0.88 3.41 +365 40 40 40 0 59.91 5.85 1.87 +366 40 55 40 0 53.66 16.87 -0.44 +367 40 70 40 0 47.28 28.91 -2.48 +368 40 85 40 0 41.35 41.02 -4.11 +369 40 100 40 0 37.09 50.34 -4.61 +370 55 0 40 0 69.75 -26.88 0.64 +371 55 10 40 0 66.15 -20.98 -1.12 +372 55 20 40 0 62.33 -14.93 -2.61 +373 55 30 40 0 58.52 -8.70 -3.96 +374 55 40 40 0 54.78 -2.19 -5.29 +375 55 55 40 0 48.96 8.44 -7.30 +376 55 70 40 0 42.92 20.09 -9.21 +377 55 85 40 0 37.27 31.98 -10.90 +378 55 100 40 0 33.15 41.15 -11.72 +379 70 0 40 0 63.35 -34.69 -7.90 +380 70 10 40 0 60.09 -29.24 -9.16 +381 70 20 40 0 56.60 -23.38 -10.36 +382 70 30 40 0 53.08 -17.39 -11.47 +383 70 40 40 0 49.63 -11.13 -12.58 +384 70 55 40 0 44.24 -0.96 -14.34 +385 70 70 40 0 38.63 10.30 -16.10 +386 70 85 40 0 33.31 21.83 -17.72 +387 70 100 40 0 29.38 30.77 -18.60 +388 85 0 40 0 57.58 -44.64 -15.60 +389 85 10 40 0 54.39 -38.45 -16.91 +390 85 20 40 0 51.21 -32.80 -17.83 +391 85 30 40 0 48.02 -26.95 -18.78 +392 85 40 40 0 44.78 -20.99 -19.67 +393 85 55 40 0 39.81 -11.13 -21.12 +394 85 70 40 0 34.65 -0.40 -22.60 +395 85 85 40 0 29.74 10.62 -24.04 +396 85 100 40 0 26.08 19.22 -25.01 +397 100 0 40 0 52.96 -51.61 -21.76 +398 100 10 40 0 50.06 -46.17 -22.89 +399 100 20 40 0 47.12 -40.58 -23.70 +400 100 30 40 0 44.18 -34.82 -24.39 +401 100 40 40 0 41.16 -29.04 -25.13 +402 100 55 40 0 36.59 -19.17 -26.07 +403 100 70 40 0 31.81 -8.79 -27.14 +404 100 85 40 0 27.38 1.57 -28.22 +405 100 100 40 0 24.35 9.47 -29.16 +406 0 0 55 0 91.32 -3.67 45.02 +407 0 10 55 0 86.60 3.32 41.44 +408 0 20 55 0 81.91 10.35 38.27 +409 0 30 55 0 77.28 17.36 35.23 +410 0 40 55 0 72.69 24.78 32.53 +411 0 55 55 0 65.75 36.53 28.96 +412 0 70 55 0 58.79 49.47 25.89 +413 0 85 55 0 52.49 61.80 23.63 +414 0 100 55 0 48.17 71.02 22.53 +415 10 0 55 0 87.33 -8.13 39.05 +416 10 10 55 0 82.76 -1.44 35.92 +417 10 20 55 0 78.26 5.40 32.96 +418 10 30 55 0 73.82 12.35 30.24 +419 10 40 55 0 69.36 19.58 27.72 +420 10 55 55 0 62.58 31.42 24.17 +421 10 70 55 0 55.80 44.02 21.11 +422 10 85 55 0 49.64 56.62 18.78 +423 10 100 55 0 45.26 65.78 17.66 +424 20 0 55 0 83.17 -12.28 33.49 +425 20 10 55 0 78.82 -5.81 30.49 +426 20 20 55 0 74.53 0.85 27.86 +427 20 30 55 0 70.27 7.62 25.37 +428 20 40 55 0 65.98 14.73 22.98 +429 20 55 55 0 59.38 26.33 19.51 +430 20 70 55 0 52.79 38.78 16.47 +431 20 85 55 0 46.77 51.10 14.01 +432 20 100 55 0 42.46 60.41 12.84 +433 30 0 55 0 79.08 -16.83 27.95 +434 30 10 55 0 74.93 -10.40 25.19 +435 30 20 55 0 70.84 -3.93 22.75 +436 30 30 55 0 66.74 2.75 20.39 +437 30 40 55 0 62.57 9.68 18.12 +438 30 55 55 0 56.19 21.01 14.74 +439 30 70 55 0 49.77 33.34 11.67 +440 30 85 55 0 43.92 45.47 9.21 +441 30 100 55 0 39.74 54.78 7.73 +442 40 0 55 0 74.94 -21.38 22.21 +443 40 10 55 0 71.05 -15.28 19.78 +444 40 20 55 0 67.11 -8.96 17.52 +445 40 30 55 0 63.13 -2.38 15.35 +446 40 40 55 0 59.14 4.42 13.19 +447 40 55 55 0 53.03 15.57 10.01 +448 40 70 55 0 46.84 27.72 7.05 +449 40 85 55 0 41.11 39.71 4.39 +450 40 100 55 0 37.05 48.72 2.84 +451 55 0 55 0 68.69 -29.37 13.83 +452 55 10 55 0 65.11 -23.16 11.48 +453 55 20 55 0 61.40 -17.05 9.50 +454 55 30 55 0 57.67 -10.69 7.59 +455 55 40 55 0 53.99 -4.11 5.73 +456 55 55 55 0 48.34 6.63 2.83 +457 55 70 55 0 42.50 18.45 -0.02 +458 55 85 55 0 37.02 30.29 -2.59 +459 55 100 55 0 33.06 39.36 -4.19 +460 70 0 55 0 62.29 -38.07 5.01 +461 70 10 55 0 59.01 -32.13 3.09 +462 70 20 55 0 55.59 -26.22 1.37 +463 70 30 55 0 52.17 -20.09 -0.28 +464 70 40 55 0 48.82 -13.71 -1.90 +465 70 55 55 0 43.60 -3.37 -4.48 +466 70 70 55 0 38.16 8.07 -7.13 +467 70 85 55 0 32.99 19.73 -9.60 +468 70 100 55 0 29.27 28.50 -11.05 +469 85 0 55 0 56.30 -48.22 -3.54 +470 85 10 55 0 53.32 -42.47 -5.11 +471 85 20 55 0 50.17 -36.82 -6.61 +472 85 30 55 0 47.07 -30.67 -8.01 +473 85 40 55 0 44.00 -24.40 -9.30 +474 85 55 55 0 39.12 -14.36 -11.59 +475 85 70 55 0 34.10 -3.35 -13.90 +476 85 85 55 0 29.38 7.83 -16.08 +477 85 100 55 0 25.90 16.32 -17.55 +478 100 0 55 0 51.74 -56.78 -9.82 +479 100 10 55 0 49.04 -51.08 -11.37 +480 100 20 55 0 46.18 -45.42 -12.66 +481 100 30 55 0 43.31 -39.42 -13.93 +482 100 40 55 0 40.36 -33.37 -15.04 +483 100 55 55 0 35.87 -23.24 -16.72 +484 100 70 55 0 31.27 -12.66 -18.78 +485 100 85 55 0 27.09 -2.18 -20.46 +486 100 100 55 0 24.21 5.65 -21.76 +487 0 0 70 0 90.44 -4.21 61.28 +488 0 10 70 0 85.77 2.80 56.87 +489 0 20 70 0 81.09 9.84 53.00 +490 0 30 70 0 76.48 16.91 49.31 +491 0 40 70 0 71.94 24.41 45.95 +492 0 55 70 0 65.15 36.37 41.18 +493 0 70 70 0 58.43 49.19 36.75 +494 0 85 70 0 52.34 61.38 33.02 +495 0 100 70 0 48.12 70.32 31.23 +496 10 0 70 0 86.46 -9.05 54.87 +497 10 10 70 0 81.91 -2.16 50.99 +498 10 20 70 0 77.44 4.73 47.51 +499 10 30 70 0 73.02 11.72 44.05 +500 10 40 70 0 68.62 19.03 40.88 +501 10 55 70 0 61.95 30.97 36.27 +502 10 70 70 0 55.36 43.55 31.94 +503 10 85 70 0 49.42 55.97 28.39 +504 10 100 70 0 45.20 65.01 26.02 +505 20 0 70 0 82.24 -13.32 48.89 +506 20 10 70 0 77.92 -6.70 45.51 +507 20 20 70 0 73.66 -0.06 42.17 +508 20 30 70 0 69.44 6.82 38.88 +509 20 40 70 0 65.21 14.02 35.84 +510 20 55 70 0 58.74 25.68 31.39 +511 20 70 70 0 52.33 38.11 27.14 +512 20 85 70 0 46.51 50.27 23.44 +513 20 100 70 0 42.41 59.29 21.01 +514 30 0 70 0 78.07 -17.87 43.09 +515 30 10 70 0 73.98 -11.48 39.78 +516 30 20 70 0 69.92 -4.97 36.83 +517 30 30 70 0 65.90 1.75 33.70 +518 30 40 70 0 61.82 8.78 30.68 +519 30 55 70 0 55.56 20.17 26.31 +520 30 70 70 0 49.35 32.36 22.15 +521 30 85 70 0 43.69 44.38 18.44 +522 30 100 70 0 39.68 53.47 15.90 +523 40 0 70 0 73.98 -22.90 37.12 +524 40 10 70 0 70.07 -16.58 34.00 +525 40 20 70 0 66.20 -10.17 31.17 +526 40 30 70 0 62.32 -3.58 28.33 +527 40 40 70 0 58.41 3.28 25.48 +528 40 55 70 0 52.40 14.45 21.22 +529 40 70 70 0 46.41 26.53 17.14 +530 40 85 70 0 40.89 38.51 13.44 +531 40 100 70 0 36.92 47.37 10.71 +532 55 0 70 0 67.60 -30.86 27.73 +533 55 10 70 0 64.09 -25.02 25.24 +534 55 20 70 0 60.47 -18.80 22.65 +535 55 30 70 0 56.83 -12.32 20.18 +536 55 40 70 0 53.21 -5.67 17.61 +537 55 55 70 0 47.69 5.15 13.72 +538 55 70 70 0 42.01 17.01 9.78 +539 55 85 70 0 36.68 28.82 6.07 +540 55 100 70 0 32.90 37.72 3.54 +541 70 0 70 0 61.29 -40.43 18.62 +542 70 10 70 0 58.04 -34.62 16.20 +543 70 20 70 0 54.66 -28.67 13.93 +544 70 30 70 0 51.30 -22.40 11.72 +545 70 40 70 0 48.01 -15.87 9.54 +546 70 55 70 0 42.93 -5.37 6.00 +547 70 70 70 0 37.56 6.18 2.28 +548 70 85 70 0 32.58 17.77 -1.13 +549 70 100 70 0 29.06 26.58 -3.37 +550 85 0 70 0 55.28 -51.54 9.65 +551 85 10 70 0 52.34 -46.03 7.48 +552 85 20 70 0 49.26 -40.18 5.39 +553 85 30 70 0 46.20 -33.94 3.49 +554 85 40 70 0 43.20 -27.44 1.61 +555 85 55 70 0 38.43 -17.14 -1.50 +556 85 70 70 0 33.50 -6.00 -4.84 +557 85 85 70 0 28.95 5.31 -7.80 +558 85 100 70 0 25.67 13.88 -9.72 +559 100 0 70 0 50.73 -61.02 2.60 +560 100 10 70 0 48.21 -55.39 0.72 +561 100 20 70 0 45.44 -49.63 -1.00 +562 100 30 70 0 42.62 -43.53 -2.73 +563 100 40 70 0 39.70 -37.18 -4.35 +564 100 55 70 0 35.23 -27.11 -7.09 +565 100 70 70 0 30.83 -16.11 -9.93 +566 100 85 70 0 26.73 -5.47 -12.46 +567 100 100 70 0 23.72 2.46 -14.35 +568 0 0 85 0 89.59 -4.30 78.11 +569 0 10 85 0 84.95 2.54 73.06 +570 0 20 85 0 80.31 9.68 68.63 +571 0 30 85 0 75.68 16.89 64.42 +572 0 40 85 0 71.16 24.60 60.45 +573 0 55 85 0 64.45 36.51 54.18 +574 0 70 85 0 57.96 49.04 48.36 +575 0 85 85 0 52.13 61.07 43.19 +576 0 100 85 0 47.99 69.68 39.86 +577 10 0 85 0 85.55 -9.23 71.49 +578 10 10 85 0 81.09 -2.42 66.99 +579 10 20 85 0 76.64 4.44 62.82 +580 10 30 85 0 72.24 11.56 58.76 +581 10 40 85 0 67.88 18.92 54.75 +582 10 55 85 0 61.33 30.85 48.95 +583 10 70 85 0 54.90 43.36 43.26 +584 10 85 85 0 49.13 55.47 38.08 +585 10 100 85 0 45.14 64.10 34.49 +586 20 0 85 0 81.36 -13.65 65.14 +587 20 10 85 0 77.09 -7.16 61.17 +588 20 20 85 0 72.84 -0.43 57.17 +589 20 30 85 0 68.64 6.47 53.13 +590 20 40 85 0 64.48 13.65 49.28 +591 20 55 85 0 58.18 25.27 43.67 +592 20 70 85 0 51.93 37.62 38.17 +593 20 85 85 0 46.26 49.68 33.02 +594 20 100 85 0 42.33 58.32 29.28 +595 30 0 85 0 77.18 -18.38 59.03 +596 30 10 85 0 73.12 -12.09 55.20 +597 30 20 85 0 69.08 -5.53 51.31 +598 30 30 85 0 65.10 1.21 47.44 +599 30 40 85 0 61.10 8.24 43.80 +600 30 55 85 0 55.02 19.58 38.24 +601 30 70 85 0 48.98 31.85 32.80 +602 30 85 85 0 43.45 43.87 27.73 +603 30 100 85 0 39.54 52.37 24.01 +604 40 0 85 0 73.06 -23.79 52.82 +605 40 10 85 0 69.17 -17.36 48.97 +606 40 20 85 0 65.31 -10.95 45.45 +607 40 30 85 0 61.54 -4.31 41.81 +608 40 40 85 0 57.71 2.53 38.22 +609 40 55 85 0 51.83 13.72 32.78 +610 40 70 85 0 45.95 25.74 27.38 +611 40 85 85 0 40.57 37.63 22.38 +612 40 100 85 0 36.75 46.47 18.73 +613 55 0 85 0 66.74 -32.47 42.68 +614 55 10 85 0 63.21 -26.14 39.43 +615 55 20 85 0 59.65 -19.87 36.28 +616 55 30 85 0 56.09 -13.45 33.04 +617 55 40 85 0 52.53 -6.79 29.71 +618 55 55 85 0 47.04 4.10 24.69 +619 55 70 85 0 41.46 16.00 19.59 +620 55 85 85 0 36.31 27.79 14.79 +621 55 100 85 0 32.71 36.31 11.24 +622 70 0 85 0 60.47 -42.45 32.73 +623 70 10 85 0 57.21 -36.32 29.79 +624 70 20 85 0 53.91 -30.40 26.81 +625 70 30 85 0 50.58 -24.08 23.94 +626 70 40 85 0 47.32 -17.50 21.06 +627 70 55 85 0 42.29 -6.82 16.47 +628 70 70 85 0 37.07 4.81 11.72 +629 70 85 85 0 32.23 16.31 7.26 +630 70 100 85 0 28.82 24.87 4.19 +631 85 0 85 0 54.46 -54.22 23.01 +632 85 10 85 0 51.57 -48.37 20.27 +633 85 20 85 0 48.53 -42.64 17.57 +634 85 30 85 0 45.48 -36.40 14.93 +635 85 40 85 0 42.49 -29.85 12.53 +636 85 55 85 0 37.83 -19.39 8.47 +637 85 70 85 0 33.00 -8.08 4.12 +638 85 85 85 0 28.57 3.18 0.18 +639 85 100 85 0 25.43 11.63 -2.39 +640 100 0 85 0 49.96 -64.51 15.36 +641 100 10 85 0 47.41 -58.78 12.75 +642 100 20 85 0 44.65 -52.99 10.45 +643 100 30 85 0 41.89 -46.75 8.26 +644 100 40 85 0 39.07 -40.33 6.10 +645 100 55 85 0 34.71 -30.16 2.55 +646 100 70 85 0 30.39 -18.98 -1.03 +647 100 85 85 0 26.30 -8.17 -4.54 +648 100 100 85 0 23.41 -0.06 -6.91 +649 0 0 100 0 88.94 -4.04 92.37 +650 0 10 100 0 84.35 2.93 87.22 +651 0 20 100 0 79.78 9.93 81.60 +652 0 30 100 0 75.21 17.28 76.85 +653 0 40 100 0 70.62 24.83 71.77 +654 0 55 100 0 63.88 36.93 64.40 +655 0 70 100 0 57.59 49.26 57.55 +656 0 85 100 0 52.01 61.00 50.67 +657 0 100 100 0 47.99 69.33 45.87 +658 10 0 100 0 84.88 -9.03 85.57 +659 10 10 100 0 80.46 -2.31 80.34 +660 10 20 100 0 76.04 4.64 75.42 +661 10 30 100 0 71.67 11.72 70.79 +662 10 40 100 0 67.35 19.15 65.96 +663 10 55 100 0 60.90 30.93 59.02 +664 10 70 100 0 54.64 43.31 51.96 +665 10 85 100 0 48.99 55.24 45.19 +666 10 100 100 0 45.04 63.72 40.42 +667 20 0 100 0 80.77 -13.83 78.87 +668 20 10 100 0 76.46 -7.14 74.05 +669 20 20 100 0 72.22 -0.38 69.36 +670 20 30 100 0 68.04 6.52 64.80 +671 20 40 100 0 63.93 13.74 60.16 +672 20 55 100 0 57.77 25.26 53.24 +673 20 70 100 0 51.60 37.64 46.37 +674 20 85 100 0 46.02 49.50 39.93 +675 20 100 100 0 42.23 57.82 34.97 +676 30 0 100 0 76.59 -18.60 71.99 +677 30 10 100 0 72.50 -12.16 67.57 +678 30 20 100 0 68.46 -5.64 63.14 +679 30 30 100 0 64.48 1.16 58.73 +680 30 40 100 0 60.55 8.16 54.27 +681 30 55 100 0 54.62 19.50 47.44 +682 30 70 100 0 48.58 31.69 40.86 +683 30 85 100 0 43.13 43.66 34.41 +684 30 100 100 0 39.46 52.01 29.54 +685 40 0 100 0 72.38 -23.80 65.39 +686 40 10 100 0 68.53 -17.53 60.92 +687 40 20 100 0 64.71 -11.10 56.67 +688 40 30 100 0 60.89 -4.52 52.46 +689 40 40 100 0 57.14 2.33 48.24 +690 40 55 100 0 51.41 13.38 41.88 +691 40 70 100 0 45.56 25.66 35.24 +692 40 85 100 0 40.29 37.45 29.13 +693 40 100 100 0 36.70 45.88 24.52 +694 55 0 100 0 65.91 -32.53 54.58 +695 55 10 100 0 62.59 -26.47 50.75 +696 55 20 100 0 59.11 -20.23 46.81 +697 55 30 100 0 55.54 -13.83 42.95 +698 55 40 100 0 52.01 -7.26 39.19 +699 55 55 100 0 46.59 3.64 32.94 +700 55 70 100 0 41.08 15.58 26.86 +701 55 85 100 0 36.08 27.28 21.06 +702 55 100 100 0 32.70 35.56 16.76 +703 70 0 100 0 59.63 -42.60 43.88 +704 70 10 100 0 56.60 -36.95 40.31 +705 70 20 100 0 53.43 -30.88 36.45 +706 70 30 100 0 50.19 -24.60 33.23 +707 70 40 100 0 46.91 -18.05 29.57 +708 70 55 100 0 41.84 -7.51 24.01 +709 70 70 100 0 36.68 4.08 18.30 +710 70 85 100 0 31.95 15.53 13.05 +711 70 100 100 0 28.80 23.72 9.51 +712 85 0 100 0 53.87 -54.67 33.22 +713 85 10 100 0 51.03 -49.29 29.89 +714 85 20 100 0 48.04 -43.53 26.60 +715 85 30 100 0 45.06 -37.12 23.67 +716 85 40 100 0 42.07 -30.62 20.53 +717 85 55 100 0 37.41 -20.56 15.59 +718 85 70 100 0 32.65 -9.17 10.53 +719 85 85 100 0 28.24 2.04 5.75 +720 85 100 100 0 25.19 10.15 2.41 +721 100 0 100 0 49.45 -65.93 24.34 +722 100 10 100 0 46.96 -60.39 21.27 +723 100 20 100 0 44.05 -54.48 18.55 +724 100 30 100 0 41.15 -48.29 15.72 +725 100 40 100 0 38.48 -41.98 13.33 +726 100 55 100 0 34.36 -31.57 9.17 +727 100 70 100 0 30.07 -20.37 4.97 +728 100 85 100 0 26.03 -9.33 0.89 +729 100 100 100 0 23.26 -1.43 -1.68 +730 0 0 0 20 82.71 0.94 -5.62 +731 0 10 0 20 78.45 6.47 -6.68 +732 0 20 0 20 74.25 12.01 -7.43 +733 0 40 0 20 65.83 23.80 -8.37 +734 0 70 0 20 52.56 45.08 -8.58 +735 0 100 0 20 41.55 65.30 -5.71 +736 10 0 0 20 79.36 -2.33 -9.67 +737 10 10 0 20 75.31 3.17 -10.70 +738 10 20 0 20 71.30 8.58 -11.24 +739 10 40 0 20 63.19 20.12 -11.99 +740 10 70 0 20 50.27 40.99 -12.23 +741 10 100 0 20 39.26 61.11 -9.78 +742 20 0 0 20 75.95 -5.23 -13.49 +743 20 10 0 20 72.11 0.09 -14.35 +744 20 20 0 20 68.25 5.43 -14.78 +745 20 40 0 20 60.40 16.65 -15.36 +746 20 70 0 20 47.87 36.80 -15.52 +747 20 100 0 20 37.04 57.03 -13.72 +748 40 0 0 20 69.10 -11.23 -21.56 +749 40 10 0 20 65.58 -6.21 -22.07 +750 40 20 0 20 62.05 -1.20 -22.23 +751 40 40 0 20 54.78 9.46 -22.46 +752 40 70 0 20 43.04 28.63 -22.45 +753 40 100 0 20 32.63 47.99 -21.35 +754 70 0 0 20 58.12 -21.50 -34.42 +755 70 10 0 20 55.16 -16.81 -34.55 +756 70 20 0 20 52.10 -12.14 -34.34 +757 70 40 0 20 45.77 -2.39 -34.02 +758 70 70 0 20 35.49 15.40 -33.51 +759 70 100 0 20 26.51 32.84 -32.87 +760 100 0 0 20 48.98 -31.63 -45.54 +761 100 10 0 20 46.34 -27.12 -45.42 +762 100 20 0 20 43.61 -22.59 -44.94 +763 100 40 0 20 38.05 -13.31 -44.04 +764 100 70 0 20 29.66 2.59 -42.50 +765 100 100 0 20 22.32 17.88 -41.00 +766 0 0 10 20 82.08 -0.43 2.12 +767 0 10 10 20 77.87 5.25 0.62 +768 0 20 10 20 73.70 10.89 -0.32 +769 0 40 10 20 65.36 22.88 -2.09 +770 0 70 10 20 52.24 44.24 -3.18 +771 0 100 10 20 41.50 64.41 -1.47 +772 10 0 10 20 78.75 -3.78 -2.02 +773 10 10 10 20 74.75 1.74 -3.29 +774 10 20 10 20 70.75 7.32 -4.27 +775 10 40 10 20 62.70 19.02 -5.73 +776 10 70 10 20 49.95 40.01 -6.79 +777 10 100 10 20 39.21 60.16 -5.49 +778 20 0 10 20 75.33 -6.75 -5.99 +779 20 10 10 20 71.53 -1.40 -7.15 +780 20 20 10 20 67.69 3.99 -7.90 +781 20 40 10 20 59.92 15.38 -9.14 +782 20 70 10 20 47.54 35.82 -10.26 +783 20 100 10 20 36.98 55.83 -9.42 +784 40 0 10 20 68.40 -13.14 -14.26 +785 40 10 10 20 64.96 -8.07 -15.10 +786 40 20 10 20 61.47 -2.98 -15.54 +787 40 40 10 20 54.32 7.85 -16.39 +788 40 70 10 20 42.71 27.36 -17.38 +789 40 100 10 20 32.59 46.75 -17.33 +790 70 0 10 20 57.44 -24.20 -27.58 +791 70 10 10 20 54.53 -19.46 -27.93 +792 70 20 10 20 51.55 -14.66 -28.01 +793 70 40 10 20 45.33 -4.69 -28.22 +794 70 70 10 20 35.23 13.33 -28.64 +795 70 100 10 20 26.30 31.00 -28.75 +796 100 0 10 20 48.23 -35.34 -39.06 +797 100 10 10 20 45.63 -30.85 -39.21 +798 100 20 10 20 43.02 -26.27 -38.96 +799 100 40 10 20 37.66 -16.66 -38.52 +800 100 70 10 20 29.27 -0.20 -37.91 +801 100 100 10 20 22.22 15.10 -37.07 +802 0 0 20 20 81.45 -1.38 9.64 +803 0 10 20 20 77.25 4.34 7.86 +804 0 20 20 20 73.12 10.06 6.49 +805 0 40 20 20 64.84 22.12 4.16 +806 0 70 20 20 51.91 43.69 2.07 +807 0 100 20 20 41.41 63.64 2.97 +808 10 0 20 20 78.11 -4.87 5.45 +809 10 10 20 20 74.12 0.73 3.79 +810 10 20 20 20 70.15 6.30 2.57 +811 10 40 20 20 62.16 18.17 0.46 +812 10 70 20 20 49.61 39.24 -1.60 +813 10 100 20 20 39.15 59.40 -1.24 +814 20 0 20 20 74.68 -8.04 1.44 +815 20 10 20 20 70.90 -2.56 -0.16 +816 20 20 20 20 67.10 2.82 -1.15 +817 20 40 20 20 59.38 14.41 -3.05 +818 20 70 20 20 47.21 35.03 -5.08 +819 20 100 20 20 36.90 54.86 -5.04 +820 40 0 20 20 67.71 -14.77 -7.13 +821 40 10 20 20 64.30 -9.60 -8.30 +822 40 20 20 20 60.84 -4.43 -9.06 +823 40 40 20 20 53.77 6.59 -10.44 +824 40 70 20 20 42.34 26.28 -12.30 +825 40 100 20 20 32.49 45.57 -12.97 +826 70 0 20 20 56.75 -26.54 -20.75 +827 70 10 20 20 53.86 -21.79 -21.34 +828 70 20 20 20 50.93 -16.89 -21.75 +829 70 40 20 20 44.78 -6.62 -22.48 +830 70 70 20 20 34.86 11.61 -23.78 +831 70 100 20 20 26.20 29.16 -24.51 +832 100 0 20 20 47.59 -38.93 -32.48 +833 100 10 20 20 45.04 -34.21 -32.90 +834 100 20 20 20 42.44 -29.59 -32.99 +835 100 40 20 20 37.19 -19.80 -33.02 +836 100 70 20 20 28.88 -2.84 -33.18 +837 100 100 20 20 22.16 12.41 -33.00 +838 0 0 40 20 80.14 -3.01 25.29 +839 0 10 40 20 76.01 2.86 22.83 +840 0 20 40 20 71.91 8.72 20.88 +841 0 40 40 20 63.81 21.02 17.21 +842 0 70 40 20 51.28 42.65 13.10 +843 0 100 40 20 41.30 61.99 12.09 +844 10 0 40 20 76.77 -6.66 20.81 +845 10 10 40 20 72.86 -0.97 18.54 +846 10 20 40 20 68.95 4.71 16.71 +847 10 40 40 20 61.17 16.76 13.44 +848 10 70 40 20 49.02 38.03 9.25 +849 10 100 40 20 39.06 57.64 7.80 +850 20 0 40 20 73.30 -10.02 16.38 +851 20 10 40 20 69.58 -4.54 14.35 +852 20 20 40 20 65.88 0.98 12.67 +853 20 40 40 20 58.41 12.76 9.72 +854 20 70 40 20 46.62 33.55 5.61 +855 20 100 40 20 36.79 53.11 3.81 +856 40 0 40 20 66.37 -17.46 7.35 +857 40 10 40 20 62.99 -12.21 5.73 +858 40 20 40 20 59.61 -6.95 4.41 +859 40 40 40 20 52.68 4.36 1.85 +860 40 70 40 20 41.62 24.36 -1.85 +861 40 100 40 20 32.33 43.36 -4.12 +862 70 0 40 20 55.45 -30.66 -6.92 +863 70 10 40 20 52.60 -25.78 -7.99 +864 70 20 40 20 49.69 -20.75 -8.84 +865 70 40 40 20 43.73 -10.19 -10.64 +866 70 70 40 20 34.11 8.50 -13.67 +867 70 100 40 20 25.99 26.13 -15.97 +868 100 0 40 20 46.29 -45.35 -19.06 +869 100 10 40 20 43.77 -40.52 -20.15 +870 100 20 40 20 41.27 -35.59 -20.78 +871 100 40 40 20 36.13 -25.27 -21.82 +872 100 70 40 20 28.13 -7.69 -23.54 +873 100 100 40 20 21.98 7.77 -24.64 +874 0 0 70 20 78.33 -4.36 52.11 +875 0 10 70 20 74.31 1.50 48.49 +876 0 20 70 20 70.31 7.50 45.34 +877 0 40 70 20 62.38 20.05 39.65 +878 0 70 70 20 50.42 41.66 31.53 +879 0 100 70 20 41.27 60.30 26.02 +880 10 0 70 20 74.92 -8.37 46.88 +881 10 10 70 20 71.08 -2.62 43.77 +882 10 20 70 20 67.27 3.20 40.93 +883 10 40 70 20 59.70 15.50 35.44 +884 10 70 70 20 48.08 36.88 27.54 +885 10 100 70 20 38.99 55.74 21.69 +886 20 0 70 20 71.38 -12.08 42.09 +887 20 10 70 20 67.75 -6.50 39.17 +888 20 20 70 20 64.15 -0.83 36.48 +889 20 40 70 20 56.91 11.18 31.35 +890 20 70 70 20 45.67 32.09 23.49 +891 20 100 70 20 36.72 50.81 17.58 +892 40 0 70 20 64.39 -20.27 32.26 +893 40 10 70 20 61.14 -14.96 29.58 +894 40 20 70 20 57.87 -9.56 27.24 +895 40 40 70 20 51.18 2.00 22.70 +896 40 70 70 20 40.75 22.13 15.28 +897 40 100 70 20 32.17 40.58 9.35 +898 70 0 70 20 53.50 -35.51 16.03 +899 70 10 70 20 50.76 -30.50 14.14 +900 70 20 70 20 47.97 -25.36 12.38 +901 70 40 70 20 42.28 -14.37 8.75 +902 70 70 70 20 33.17 4.78 2.36 +903 70 100 70 20 25.77 22.27 -2.65 +904 100 0 70 20 44.46 -53.40 1.85 +905 100 10 70 20 42.18 -48.36 0.30 +906 100 20 70 20 39.74 -43.26 -1.04 +907 100 40 70 20 34.83 -32.31 -3.86 +908 100 70 70 20 27.27 -13.76 -8.52 +909 100 100 70 20 21.35 1.97 -11.63 +910 0 0 100 20 76.87 -4.54 79.60 +911 0 10 100 20 72.83 1.43 74.97 +912 0 20 100 20 68.92 7.44 70.62 +913 0 40 100 20 61.20 20.10 61.93 +914 0 70 100 20 49.71 41.31 48.84 +915 0 100 100 20 41.18 59.22 38.07 +916 10 0 100 20 73.45 -8.73 74.00 +917 10 10 100 20 69.65 -2.93 69.64 +918 10 20 100 20 65.91 2.91 65.50 +919 10 40 100 20 58.54 15.23 57.36 +920 10 70 100 20 47.42 36.32 44.40 +921 10 100 100 20 38.84 54.38 33.77 +922 20 0 100 20 69.96 -12.68 68.26 +923 20 10 100 20 66.33 -7.02 64.24 +924 20 20 100 20 62.79 -1.30 60.34 +925 20 40 100 20 55.81 10.68 52.70 +926 20 70 100 20 45.00 31.40 40.12 +927 20 100 100 20 36.57 49.59 29.43 +928 40 0 100 20 62.91 -21.30 56.40 +929 40 10 100 20 59.71 -15.94 52.97 +930 40 20 100 20 56.52 -10.45 49.55 +931 40 40 100 20 50.09 0.97 42.51 +932 40 70 100 20 40.01 21.17 30.74 +933 40 100 100 20 32.07 39.11 20.63 +934 70 0 100 20 51.96 -37.71 37.64 +935 70 10 100 20 49.37 -32.65 34.74 +936 70 20 100 20 46.70 -27.43 31.79 +937 70 40 100 20 41.15 -16.27 25.96 +938 70 70 100 20 32.42 2.80 16.16 +939 70 100 100 20 25.44 19.59 8.23 +940 100 0 100 20 43.29 -57.56 20.62 +941 100 10 100 20 40.94 -52.67 18.23 +942 100 20 100 20 38.56 -47.34 15.65 +943 100 40 100 20 33.86 -36.19 11.18 +944 100 70 100 20 26.63 -17.39 4.15 +945 100 100 100 20 20.99 -1.62 -0.77 +946 0 0 0 40 69.76 0.49 -4.90 +947 0 20 0 40 62.52 9.75 -6.42 +948 0 40 0 40 55.49 19.69 -7.37 +949 0 70 0 40 44.14 37.55 -7.50 +950 0 100 0 40 34.72 54.79 -5.39 +951 20 0 0 40 63.98 -4.58 -11.33 +952 20 20 0 40 57.76 4.18 -12.29 +953 20 40 0 40 51.20 13.57 -12.79 +954 20 70 0 40 40.49 30.70 -12.92 +955 20 100 0 40 31.10 47.69 -11.55 +956 40 0 0 40 58.32 -9.67 -17.98 +957 40 20 0 40 52.62 -1.32 -18.41 +958 40 40 0 40 46.55 7.66 -18.54 +959 40 70 0 40 36.62 23.92 -18.55 +960 40 100 0 40 27.63 40.22 -17.89 +961 70 0 0 40 49.03 -18.54 -28.83 +962 70 20 0 40 44.15 -10.67 -28.60 +963 70 40 0 40 38.98 -2.29 -28.34 +964 70 70 0 40 30.42 12.73 -27.73 +965 70 100 0 40 22.75 27.22 -27.19 +966 100 0 0 40 41.19 -27.41 -38.38 +967 100 20 0 40 36.82 -19.61 -37.84 +968 100 40 0 40 32.22 -11.48 -37.07 +969 100 70 0 40 25.31 2.23 -35.53 +970 100 100 0 40 19.62 14.55 -33.73 +971 0 0 20 40 68.48 -1.48 7.70 +972 0 20 20 40 61.60 7.93 5.17 +973 0 40 20 40 54.61 18.06 3.27 +974 0 70 20 40 43.64 36.12 1.49 +975 0 100 20 40 34.63 53.16 2.14 +976 20 0 20 40 62.92 -7.02 0.95 +977 20 20 20 40 56.68 2.01 -1.02 +978 20 40 20 40 50.25 11.62 -2.51 +979 20 70 20 40 39.95 28.97 -4.21 +980 20 100 20 40 31.08 45.77 -4.40 +981 40 0 20 40 57.13 -12.61 -6.09 +982 40 20 20 40 51.60 -4.11 -7.49 +983 40 40 20 40 45.74 5.11 -8.49 +984 40 70 20 40 36.05 21.59 -10.01 +985 40 100 20 40 27.54 37.87 -10.67 +986 70 0 20 40 47.88 -22.76 -17.42 +987 70 20 20 40 43.15 -14.56 -18.18 +988 70 40 20 40 38.11 -5.86 -18.70 +989 70 70 20 40 29.84 9.42 -19.58 +990 70 100 20 40 22.58 23.94 -20.09 +991 100 0 20 40 40.09 -33.23 -27.46 +992 100 20 20 40 35.84 -25.12 -27.85 +993 100 40 20 40 31.60 -16.66 -27.78 +994 100 70 20 40 24.95 -2.44 -27.50 +995 100 100 20 40 19.60 9.81 -26.69 +996 0 0 40 40 67.34 -2.97 20.70 +997 0 20 40 40 60.49 6.72 17.16 +998 0 40 40 40 53.65 17.00 14.18 +999 0 70 40 40 43.08 35.13 10.76 +1000 0 100 40 40 34.42 51.63 9.58 +1001 20 0 40 40 61.72 -8.83 13.51 +1002 20 20 40 40 55.59 0.33 10.60 +1003 20 40 40 40 49.39 10.16 8.24 +1004 20 70 40 40 39.43 27.57 4.85 +1005 20 100 40 40 30.97 44.02 3.01 +1006 40 0 40 40 55.94 -14.96 6.09 +1007 40 20 40 40 50.51 -6.27 3.84 +1008 40 40 40 40 44.79 3.13 1.87 +1009 40 70 40 40 35.43 19.91 -1.18 +1010 40 100 40 40 27.45 35.74 -3.21 +1011 70 0 40 40 46.81 -26.12 -5.92 +1012 70 20 40 40 42.13 -17.78 -7.34 +1013 70 40 40 40 37.20 -8.87 -8.67 +1014 70 70 40 40 29.18 6.90 -10.97 +1015 70 100 40 40 22.53 21.10 -12.82 +1016 100 0 40 40 39.03 -38.48 -16.29 +1017 100 20 40 40 34.93 -30.04 -17.54 +1018 100 40 40 40 30.74 -21.21 -18.24 +1019 100 70 40 40 24.32 -6.31 -19.35 +1020 100 100 40 40 19.38 6.17 -19.49 +1021 0 0 70 40 65.58 -4.34 43.22 +1022 0 20 70 40 59.01 5.50 37.69 +1023 0 40 70 40 52.35 15.95 33.01 +1024 0 70 70 40 42.19 34.08 26.08 +1025 0 100 70 40 34.49 49.62 21.24 +1026 20 0 70 40 59.97 -10.70 35.00 +1027 20 20 70 40 54.07 -1.36 30.56 +1028 20 40 70 40 48.05 8.63 26.41 +1029 20 70 70 40 38.58 26.14 19.73 +1030 20 100 70 40 30.92 41.83 14.44 +1031 40 0 70 40 54.25 -17.46 26.83 +1032 40 20 70 40 48.93 -8.59 23.01 +1033 40 40 70 40 43.38 0.94 19.38 +1034 40 70 70 40 34.64 17.81 13.15 +1035 40 100 70 40 27.34 33.21 7.92 +1036 70 0 70 40 45.12 -30.22 13.41 +1037 70 20 70 40 40.64 -21.71 10.48 +1038 70 40 70 40 35.97 -12.44 7.61 +1039 70 70 70 40 28.46 3.51 2.52 +1040 70 100 70 40 22.34 17.67 -1.78 +1041 100 0 70 40 37.66 -44.89 1.47 +1042 100 20 70 40 33.71 -36.24 -1.01 +1043 100 40 70 40 29.67 -26.80 -3.12 +1044 100 70 70 40 23.55 -11.20 -6.77 +1045 100 100 70 40 18.98 1.43 -8.62 +1046 0 0 100 40 64.34 -4.61 66.28 +1047 0 20 100 40 57.63 5.32 58.83 +1048 0 40 100 40 51.26 15.71 51.46 +1049 0 70 100 40 41.55 33.60 39.83 +1050 0 100 100 40 34.41 48.54 30.21 +1051 20 0 100 40 58.63 -11.29 56.88 +1052 20 20 100 40 52.81 -1.95 50.58 +1053 20 40 100 40 47.05 8.03 44.11 +1054 20 70 100 40 37.96 25.36 33.13 +1055 20 100 100 40 30.81 40.60 23.75 +1056 40 0 100 40 52.92 -18.48 47.26 +1057 40 20 100 40 47.71 -9.52 41.60 +1058 40 40 100 40 42.45 0.10 35.78 +1059 40 70 100 40 33.93 16.86 25.64 +1060 40 100 100 40 27.31 31.57 16.97 +1061 70 0 100 40 43.72 -32.23 31.03 +1062 70 20 100 40 39.54 -23.58 26.64 +1063 70 40 100 40 35.03 -14.28 21.85 +1064 70 70 100 40 27.87 1.79 13.74 +1065 70 100 100 40 22.08 15.59 7.09 +1066 100 0 100 40 36.61 -48.49 16.76 +1067 100 20 100 40 32.70 -39.49 12.87 +1068 100 40 100 40 28.94 -29.96 8.97 +1069 100 70 100 40 23.06 -14.02 3.66 +1070 100 100 100 40 18.84 -1.48 0.17 +1071 0 0 0 60 55.11 0.16 -3.90 +1072 0 20 0 60 49.23 7.50 -5.02 +1073 0 40 0 60 43.70 15.24 -5.67 +1074 0 70 0 60 34.64 29.50 -5.70 +1075 0 100 0 60 27.25 42.69 -3.97 +1076 20 0 0 60 50.37 -3.85 -8.86 +1077 20 20 0 60 45.68 3.01 -9.52 +1078 20 40 0 60 40.52 10.45 -9.77 +1079 20 70 0 60 31.99 24.00 -9.64 +1080 20 100 0 60 24.71 36.96 -8.33 +1081 40 0 0 60 45.88 -7.92 -14.06 +1082 40 20 0 60 41.69 -1.34 -14.21 +1083 40 40 0 60 37.05 5.92 -14.19 +1084 40 70 0 60 29.25 18.74 -13.96 +1085 40 100 0 60 22.30 31.03 -13.17 +1086 70 0 0 60 38.53 -15.13 -22.51 +1087 70 20 0 60 34.83 -8.72 -22.31 +1088 70 40 0 60 31.15 -1.90 -21.87 +1089 70 70 0 60 24.56 9.92 -21.11 +1090 70 100 0 60 18.99 20.53 -20.02 +1091 100 0 0 60 32.32 -22.10 -30.18 +1092 100 20 0 60 29.16 -15.54 -29.66 +1093 100 40 0 60 25.87 -8.89 -28.81 +1094 100 70 0 60 20.64 2.09 -26.98 +1095 100 100 0 60 16.87 10.72 -24.84 +1096 0 0 20 60 53.73 -1.52 5.86 +1097 0 20 20 60 48.47 6.03 3.92 +1098 0 40 20 60 42.94 14.05 2.55 +1099 0 70 20 60 34.35 28.20 1.31 +1100 0 100 20 60 27.39 41.04 1.93 +1101 20 0 20 60 49.43 -5.78 0.64 +1102 20 20 20 60 44.77 1.35 -0.70 +1103 20 40 20 60 39.78 8.90 -1.76 +1104 20 70 20 60 31.68 22.45 -2.88 +1105 20 100 20 60 24.82 35.20 -2.86 +1106 40 0 20 60 44.94 -10.16 -4.74 +1107 40 20 20 60 40.87 -3.51 -5.71 +1108 40 40 20 60 36.39 3.73 -6.30 +1109 40 70 20 60 28.83 16.68 -7.24 +1110 40 100 20 60 22.27 28.94 -7.50 +1111 70 0 20 60 37.72 -18.19 -13.72 +1112 70 20 20 60 34.14 -11.65 -14.11 +1113 70 40 20 60 30.36 -4.71 -14.34 +1114 70 70 20 60 24.09 7.36 -14.52 +1115 70 100 20 60 18.86 17.97 -14.34 +1116 100 0 20 60 31.60 -26.33 -21.61 +1117 100 20 20 60 28.46 -19.57 -21.70 +1118 100 40 20 60 25.25 -12.54 -21.49 +1119 100 70 20 60 20.49 -1.37 -20.68 +1120 100 100 20 60 16.88 7.38 -19.20 +1121 0 0 40 60 52.68 -2.67 15.85 +1122 0 20 40 60 47.36 4.88 13.13 +1123 0 40 40 60 42.12 12.95 11.02 +1124 0 70 40 60 33.95 27.10 8.41 +1125 0 100 40 60 27.18 39.42 7.54 +1126 20 0 40 60 48.50 -7.28 10.40 +1127 20 20 40 60 43.81 -0.10 8.37 +1128 20 40 40 60 39.03 7.63 6.71 +1129 20 70 40 60 31.26 21.24 4.17 +1130 20 100 40 60 24.70 33.40 2.83 +1131 40 0 40 60 44.02 -12.08 4.67 +1132 40 20 40 60 39.95 -5.27 3.17 +1133 40 40 40 60 35.64 2.13 1.88 +1134 40 70 40 60 28.35 15.13 -0.31 +1135 40 100 40 60 22.18 26.92 -1.83 +1136 70 0 40 60 36.90 -20.87 -4.66 +1137 70 20 40 60 33.37 -14.28 -5.60 +1138 70 40 40 60 29.67 -6.99 -6.41 +1139 70 70 40 60 23.62 5.21 -7.78 +1140 70 100 40 60 18.91 15.47 -8.68 +1141 100 0 40 60 30.78 -30.24 -12.90 +1142 100 20 40 60 27.78 -23.12 -13.56 +1143 100 40 40 60 24.77 -15.96 -13.91 +1144 100 70 40 60 20.15 -4.47 -14.11 +1145 100 100 40 60 16.68 4.82 -13.41 +1146 0 0 70 60 51.15 -4.04 33.32 +1147 0 20 70 60 46.21 3.70 29.16 +1148 0 40 70 60 41.10 11.85 25.54 +1149 0 70 70 60 33.12 25.82 20.00 +1150 0 100 70 60 27.29 37.43 16.11 +1151 20 0 70 60 46.98 -8.95 27.14 +1152 20 20 70 60 42.58 -1.61 23.88 +1153 20 40 70 60 37.93 6.17 20.61 +1154 20 70 70 60 30.59 19.79 15.51 +1155 20 100 70 60 24.72 31.23 11.25 +1156 40 0 70 60 42.69 -14.23 20.77 +1157 40 20 70 60 38.67 -7.26 18.07 +1158 40 40 70 60 34.49 0.25 15.33 +1159 40 70 70 60 27.76 13.33 10.62 +1160 40 100 70 60 22.27 24.45 6.60 +1161 70 0 70 60 35.60 -24.15 10.44 +1162 70 20 70 60 32.21 -17.35 8.27 +1163 70 40 70 60 28.76 -9.97 6.18 +1164 70 70 70 60 23.18 2.47 2.77 +1165 70 100 70 60 18.79 12.57 -0.31 +1166 100 0 70 60 29.84 -34.93 1.13 +1167 100 20 70 60 26.91 -27.69 -0.65 +1168 100 40 70 60 23.97 -20.18 -2.17 +1169 100 70 70 60 19.64 -8.07 -4.26 +1170 100 100 70 60 16.55 1.20 -5.07 +1171 0 0 100 60 50.25 -4.33 50.82 +1172 0 20 100 60 45.01 3.42 44.96 +1173 0 40 100 60 40.03 11.41 39.03 +1174 0 70 100 60 32.56 25.13 29.69 +1175 0 100 100 60 27.15 36.15 22.32 +1176 20 0 100 60 45.86 -9.57 43.71 +1177 20 20 100 60 41.49 -2.22 38.85 +1178 20 40 100 60 37.06 5.50 33.68 +1179 20 70 100 60 30.07 18.85 25.03 +1180 20 100 100 60 24.72 30.00 17.63 +1181 40 0 100 60 41.53 -15.21 36.44 +1182 40 20 100 60 37.56 -8.14 31.96 +1183 40 40 100 60 33.65 -0.54 27.58 +1184 40 70 100 60 27.21 12.41 19.43 +1185 40 100 100 60 22.13 22.96 12.95 +1186 70 0 100 60 34.38 -25.71 23.46 +1187 70 20 100 60 31.39 -18.85 20.31 +1188 70 40 100 60 28.15 -11.44 16.90 +1189 70 70 100 60 22.81 0.83 10.97 +1190 70 100 100 60 18.77 10.78 6.27 +1191 100 0 100 60 29.06 -37.41 12.37 +1192 100 20 100 60 26.18 -29.92 9.60 +1193 100 40 100 60 23.44 -22.34 6.91 +1194 100 70 100 60 19.37 -10.23 3.34 +1195 100 100 100 60 16.60 -1.05 1.33 +1196 0 0 0 80 37.53 -0.06 -2.55 +1197 0 40 0 80 29.92 10.36 -3.35 +1198 0 70 0 80 24.18 19.69 -2.63 +1199 0 100 0 80 19.71 27.26 -0.61 +1200 40 0 0 80 31.21 -5.53 -9.39 +1201 40 40 0 80 25.70 3.89 -8.72 +1202 40 70 0 80 20.81 12.60 -7.88 +1203 40 100 0 80 16.94 19.73 -6.36 +1204 70 0 0 80 26.43 -10.25 -15.17 +1205 70 40 0 80 21.93 -0.93 -13.86 +1206 70 70 0 80 18.12 7.02 -12.31 +1207 70 100 0 80 15.10 13.10 -10.62 +1208 100 0 0 80 22.35 -14.40 -20.14 +1209 100 40 0 80 18.57 -4.80 -18.53 +1210 100 70 0 80 15.78 2.53 -16.01 +1211 100 100 0 80 14.02 7.64 -13.62 +1212 0 0 40 80 35.69 -2.21 10.26 +1213 0 40 40 80 28.86 8.37 7.46 +1214 0 70 40 80 23.82 17.54 6.14 +1215 0 100 40 80 19.89 24.54 5.88 +1216 40 0 40 80 30.03 -8.47 2.93 +1217 40 40 40 80 24.87 1.18 1.98 +1218 40 70 40 80 20.40 9.52 0.93 +1219 40 100 40 80 17.01 16.13 0.53 +1220 70 0 40 80 25.39 -14.08 -3.15 +1221 70 40 40 80 21.09 -4.40 -3.40 +1222 70 70 40 80 17.71 3.56 -3.40 +1223 70 100 40 80 15.25 9.27 -3.33 +1224 100 0 40 80 21.63 -19.32 -8.44 +1225 100 40 40 80 18.18 -9.24 -8.20 +1226 100 70 40 80 15.76 -1.62 -7.35 +1227 100 100 40 80 14.15 3.69 -6.09 +1228 0 0 70 80 34.66 -3.35 21.33 +1229 0 40 70 80 28.30 7.22 16.41 +1230 0 70 70 80 23.37 16.02 12.92 +1231 0 100 70 80 20.10 22.62 10.78 +1232 40 0 70 80 29.20 -10.17 13.43 +1233 40 40 70 80 24.18 -0.45 10.29 +1234 40 70 70 80 20.17 7.85 7.65 +1235 40 100 70 80 17.21 14.02 5.52 +1236 70 0 70 80 24.64 -16.37 6.71 +1237 70 40 70 80 20.69 -6.51 4.67 +1238 70 70 70 80 17.54 1.42 2.92 +1239 70 100 70 80 15.35 7.13 1.69 +1240 100 0 70 80 21.23 -22.25 0.82 +1241 100 40 70 80 17.92 -11.69 -0.54 +1242 100 70 70 80 15.68 -4.13 -1.03 +1243 100 100 70 80 14.29 1.16 -0.78 +1244 0 0 100 80 34.00 -3.83 31.57 +1245 0 40 100 80 27.55 6.53 23.99 +1246 0 70 100 80 23.10 15.17 18.22 +1247 0 100 100 80 20.01 21.33 14.10 +1248 40 0 100 80 28.36 -10.98 22.26 +1249 40 40 100 80 23.69 -1.21 17.17 +1250 40 70 100 80 19.95 6.78 12.47 +1251 40 100 100 80 17.19 12.64 9.00 +1252 70 0 100 80 23.93 -17.55 14.31 +1253 70 40 100 80 20.38 -7.77 10.86 +1254 70 70 100 80 17.44 -0.03 7.75 +1255 70 100 100 80 15.48 5.45 5.62 +1256 100 0 100 80 20.74 -23.54 7.57 +1257 100 40 100 80 17.65 -13.21 4.98 +1258 100 70 100 80 15.64 -5.73 3.47 +1259 100 100 100 80 14.42 -0.52 2.89 +1260 0 0 0 100 16.00 0.07 -0.33 +1261 0 40 0 100 14.59 3.91 1.23 +1262 0 100 0 100 13.30 8.89 4.27 +1263 40 0 0 100 14.54 -1.51 -2.60 +1264 40 40 0 100 13.68 2.52 -0.92 +1265 40 100 0 100 12.53 7.53 2.57 +1266 100 0 0 100 12.18 -3.46 -6.20 +1267 100 40 0 100 12.05 0.86 -4.11 +1268 100 100 0 100 11.43 5.76 0.01 +1269 0 0 40 100 15.58 -1.33 2.32 +1270 0 40 40 100 14.55 2.15 3.20 +1271 0 100 40 100 13.65 6.43 5.33 +1272 40 0 40 100 14.44 -3.26 0.64 +1273 40 40 40 100 13.71 0.53 1.73 +1274 40 100 40 100 12.97 5.05 3.95 +1275 100 0 40 100 12.48 -5.55 -2.32 +1276 100 40 40 100 12.36 -1.39 -0.48 +1277 100 100 40 100 12.10 3.27 2.10 +1278 0 0 100 100 15.37 -3.20 6.36 +1279 0 40 100 100 14.60 -0.40 6.20 +1280 0 100 100 100 14.07 3.45 7.04 +1281 40 0 100 100 14.40 -5.36 4.99 +1282 40 40 100 100 13.92 -2.03 5.32 +1283 40 100 100 100 13.45 1.98 6.07 +1284 100 0 100 100 12.95 -8.05 3.02 +1285 100 40 100 100 12.80 -3.87 3.65 +1286 100 100 100 100 12.71 0.53 4.89 +1287 100 0 0 0 56.12 -34.90 -52.52 +1288 98 0 0 0 56.57 -34.55 -51.98 +1289 95 0 0 0 57.50 -33.86 -50.97 +1290 90 0 0 0 58.99 -32.23 -49.17 +1291 85 0 0 0 60.62 -30.20 -47.07 +1292 80 0 0 0 62.52 -28.10 -44.74 +1293 75 0 0 0 64.50 -26.08 -42.35 +1294 70 0 0 0 66.57 -24.03 -39.84 +1295 60 0 0 0 70.86 -20.12 -34.85 +1296 50 0 0 0 75.02 -16.20 -29.84 +1297 40 0 0 0 79.15 -12.57 -24.94 +1298 30 0 0 0 83.19 -9.04 -20.26 +1299 25 0 0 0 85.18 -7.33 -17.89 +1300 20 0 0 0 87.20 -5.64 -15.58 +1301 15 0 0 0 89.19 -3.96 -13.25 +1302 10 0 0 0 91.19 -2.28 -10.93 +1303 7 0 0 0 92.40 -1.23 -9.48 +1304 5 0 0 0 93.14 -0.51 -8.50 +1305 3 0 0 0 93.93 0.25 -7.56 +1306 2 0 0 0 94.35 0.55 -7.24 +1307 0 100 0 0 48.06 75.29 -5.18 +1308 0 98 0 0 48.58 74.48 -5.81 +1309 0 95 0 0 49.56 72.84 -6.62 +1310 0 90 0 0 51.30 69.51 -7.29 +1311 0 85 0 0 53.32 65.54 -7.71 +1312 0 80 0 0 55.59 61.24 -8.19 +1313 0 75 0 0 57.94 56.95 -8.67 +1314 0 70 0 0 60.42 52.69 -9.17 +1315 0 60 0 0 65.44 44.19 -9.58 +1316 0 50 0 0 70.47 36.07 -9.54 +1317 0 40 0 0 75.43 28.45 -9.24 +1318 0 30 0 0 80.33 21.39 -8.87 +1319 0 25 0 0 82.76 18.02 -8.63 +1320 0 20 0 0 85.20 14.67 -8.29 +1321 0 15 0 0 87.63 11.40 -7.90 +1322 0 10 0 0 90.08 8.15 -7.42 +1323 0 7 0 0 91.57 6.24 -7.19 +1324 0 5 0 0 92.53 5.00 -7.00 +1325 0 3 0 0 93.54 3.67 -6.73 +1326 0 2 0 0 94.02 3.03 -6.59 +1327 0 0 100 0 88.94 -4.04 92.37 +1328 0 0 98 0 89.05 -4.12 91.02 +1329 0 0 95 0 89.18 -4.15 88.37 +1330 0 0 90 0 89.33 -4.25 83.43 +1331 0 0 85 0 89.59 -4.30 78.11 +1332 0 0 80 0 89.85 -4.20 72.40 +1333 0 0 75 0 90.11 -4.17 66.82 +1334 0 0 70 0 90.44 -4.21 61.28 +1335 0 0 60 0 91.03 -3.89 50.35 +1336 0 0 50 0 91.62 -3.44 39.94 +1337 0 0 40 0 92.30 -2.85 30.21 +1338 0 0 30 0 92.93 -2.11 20.82 +1339 0 0 25 0 93.40 -1.69 16.51 +1340 0 0 20 0 93.66 -1.17 11.88 +1341 0 0 15 0 93.99 -0.63 7.37 +1342 0 0 10 0 94.39 -0.05 3.02 +1343 0 0 7 0 94.60 0.34 0.33 +1344 0 0 5 0 94.73 0.66 -1.45 +1345 0 0 3 0 94.88 0.93 -3.22 +1346 0 0 2 0 94.95 1.09 -4.07 +1347 0 0 0 100 16.00 0.07 -0.33 +1348 0 0 0 98 18.05 0.02 -0.43 +1349 0 0 0 95 21.52 -0.02 -0.81 +1350 0 0 0 90 27.02 -0.06 -1.52 +1351 0 0 0 85 32.37 -0.07 -2.07 +1352 0 0 0 80 37.53 -0.06 -2.55 +1353 0 0 0 75 42.24 -0.02 -2.96 +1354 0 0 0 70 46.75 0.02 -3.25 +1355 0 0 0 60 55.11 0.16 -3.90 +1356 0 0 0 50 62.72 0.31 -4.44 +1357 0 0 0 40 69.76 0.49 -4.90 +1358 0 0 0 30 76.38 0.70 -5.30 +1359 0 0 0 25 79.55 0.81 -5.46 +1360 0 0 0 20 82.71 0.94 -5.62 +1361 0 0 0 15 85.80 1.07 -5.72 +1362 0 0 0 10 88.87 1.20 -5.84 +1363 0 0 0 7 90.74 1.29 -5.91 +1364 0 0 0 5 91.93 1.35 -5.95 +1365 0 0 0 3 93.17 1.44 -6.02 +1366 0 0 0 2 93.76 1.45 -6.05 +1367 0 0 0 0 95.00 1.50 -6.00 +1368 100 85 85 0 26.30 -8.17 -4.54 +1369 80 65 65 0 36.49 -4.67 -4.60 +1370 60 45 45 0 50.74 -2.08 -4.61 +1371 40 27 27 0 66.01 -1.20 -5.85 +1372 20 12 12 0 80.96 -0.21 -6.62 +1373 10 6 6 0 88.02 0.65 -6.52 +1374 5 3 3 0 91.58 1.10 -6.43 +1375 40 27 27 10 61.99 -1.45 -5.47 +1376 20 12 12 10 75.81 -0.43 -6.33 +1377 10 6 6 10 82.35 0.39 -6.28 +1378 60 45 45 20 44.69 -2.51 -3.66 +1379 40 27 27 20 57.98 -1.61 -5.04 +1380 20 12 12 20 70.61 -0.59 -5.97 +1381 10 6 6 20 76.63 0.17 -5.98 +1382 80 65 65 40 27.71 -3.78 -2.51 +1383 60 45 45 40 38.04 -2.45 -2.75 +1384 40 27 27 40 49.24 -1.73 -4.05 +1385 20 12 12 40 59.61 -0.81 -5.04 +1386 10 6 6 40 64.59 -0.13 -5.13 +1387 100 85 85 60 17.70 -4.01 -0.61 +1388 80 65 65 60 22.63 -2.96 -1.16 +1389 60 45 45 60 30.36 -2.12 -1.67 +1390 40 27 27 60 39.06 -1.68 -2.95 +1391 20 12 12 60 47.01 -0.85 -3.91 +1392 10 6 6 60 50.89 -0.32 -4.09 +1393 100 85 85 80 14.88 -2.17 1.75 +1394 80 65 65 80 17.21 -1.53 0.63 +1395 60 45 45 80 21.59 -1.41 -0.19 +1396 40 27 27 80 26.96 -1.27 -1.44 +1397 20 12 12 80 32.13 -0.70 -2.44 +1398 10 6 6 80 34.71 -0.35 -2.66 +1399 100 85 85 100 12.62 0.12 4.12 +1400 80 65 65 100 12.68 0.09 2.71 +1401 60 45 45 100 13.10 0.10 1.39 +1402 40 27 27 100 13.98 0.00 0.32 +1403 20 12 12 100 15.06 -0.10 -0.36 +1404 10 6 6 100 15.59 -0.04 -0.46 +1405 100 0 0 70 27.49 -18.64 -25.44 +1406 0 100 0 70 23.52 35.19 -2.30 +1407 0 0 100 70 42.49 -4.09 42.01 +1408 100 100 0 70 15.42 9.13 -19.40 +1409 100 0 100 70 24.95 -31.00 10.13 +1410 0 100 100 70 23.56 29.25 17.99 +1411 40 40 0 70 31.54 4.94 -11.63 +1412 40 0 40 70 37.27 -10.46 3.88 +1413 0 40 40 70 35.66 10.84 9.34 +1414 3 3 0 0 92.55 2.20 -7.96 +1415 3 0 3 0 93.78 -0.25 -4.84 +1416 0 3 3 0 93.40 3.06 -4.03 +1417 3 3 3 0 92.34 1.87 -5.54 +1418 3 0 0 3 92.13 0.09 -7.49 +1419 0 3 0 3 91.79 3.43 -6.42 +1420 3 3 0 3 90.71 2.20 -8.14 +1421 0 0 3 3 93.04 0.91 -3.30 +1422 3 0 3 3 91.97 -0.36 -4.85 +1423 0 3 3 3 91.61 3.01 -4.04 +1424 3 3 3 3 90.56 1.72 -5.52 +1425 7 7 0 0 89.04 3.48 -10.58 +1426 7 0 7 0 91.94 -2.39 -3.22 +1427 0 7 7 0 91.18 5.14 -1.04 +1428 7 7 7 0 88.64 2.29 -4.41 +1429 7 0 0 7 88.25 -1.37 -9.15 +1430 0 7 0 7 87.49 5.71 -6.87 +1431 7 7 0 7 85.04 3.07 -10.21 +1432 0 0 7 7 90.32 0.22 0.07 +1433 7 0 7 7 87.81 -2.46 -3.19 +1434 0 7 7 7 87.07 4.70 -1.17 +1435 7 7 7 7 84.66 1.96 -4.38 +1436 40 3 0 0 77.93 -10.75 -25.27 +1437 3 40 0 0 74.61 26.77 -10.39 +1438 40 0 3 0 78.92 -13.18 -22.40 +1439 40 3 3 0 77.72 -11.43 -22.75 +1440 0 40 3 0 75.34 28.07 -7.02 +1441 3 40 3 0 74.45 26.59 -8.37 +1442 40 40 3 0 62.13 10.79 -23.92 +1443 3 0 40 0 91.15 -4.19 28.42 +1444 0 3 40 0 90.86 -0.60 29.02 +1445 3 3 40 0 89.76 -2.05 27.45 +1446 40 3 40 0 74.85 -17.75 8.07 +1447 3 40 40 0 72.48 23.76 18.99 +1448 40 0 0 3 77.67 -12.47 -24.39 +1449 40 3 0 3 76.42 -10.55 -24.92 +1450 0 40 0 3 74.02 27.71 -9.10 +1451 3 40 0 3 73.15 26.27 -10.51 +1452 40 40 0 3 61.12 11.14 -25.64 +1453 40 0 3 3 77.48 -13.20 -21.84 +1454 40 3 3 3 76.26 -11.22 -22.41 +1455 0 40 3 3 73.92 27.37 -6.91 +1456 3 40 3 3 73.05 25.93 -8.34 +1457 40 40 3 3 61.00 10.54 -23.50 +1458 0 0 40 3 90.45 -2.80 29.34 +1459 3 0 40 3 89.37 -4.26 27.78 +1460 40 0 40 3 74.61 -19.37 8.58 +1461 0 3 40 3 89.07 -0.67 28.27 +1462 3 3 40 3 88.00 -2.07 26.74 +1463 40 3 40 3 73.44 -17.46 7.77 +1464 0 40 40 3 71.98 24.68 19.89 +1465 3 40 40 3 71.07 23.12 18.45 +1466 40 40 40 3 58.83 5.61 1.84 +1467 3 0 0 40 68.97 -0.47 -5.92 +1468 0 3 0 40 68.68 1.98 -5.31 +1469 3 3 0 40 67.90 1.02 -6.38 +1470 40 3 0 40 57.49 -8.36 -18.26 +1471 3 40 0 40 54.94 18.59 -8.20 +1472 0 0 3 40 69.62 0.07 -2.86 +1473 3 0 3 40 68.82 -0.89 -3.94 +1474 40 0 3 40 58.20 -10.26 -16.04 +1475 0 3 3 40 68.53 1.58 -3.41 +1476 3 3 3 40 67.76 0.63 -4.46 +1477 40 3 3 40 57.36 -8.89 -16.42 +1478 0 40 3 40 55.43 19.26 -5.61 +1479 3 40 3 40 54.84 18.24 -6.56 +1480 40 40 3 40 46.48 7.16 -16.97 +1481 3 0 40 40 66.57 -3.98 19.51 +1482 0 3 40 40 66.31 -1.41 19.93 +1483 3 3 40 40 65.56 -2.43 18.78 +1484 40 3 40 40 55.13 -13.59 5.51 +1485 3 40 40 40 53.07 15.89 13.30 +1486 0 0 0 10 88.87 1.20 -5.84 +1487 0 0 10 10 88.24 -0.22 2.54 +1488 0 0 20 10 87.54 -1.22 10.66 +1489 0 0 40 10 86.23 -2.89 27.68 +1490 0 0 70 10 84.38 -4.29 56.70 +1491 0 10 0 10 84.30 7.28 -7.06 +1492 0 10 10 10 83.70 5.91 0.98 +1493 0 10 20 10 83.04 4.96 8.82 +1494 0 10 40 10 81.79 3.42 25.08 +1495 0 10 70 10 80.06 2.07 52.70 +1496 0 20 0 10 79.78 13.27 -7.75 +1497 0 20 10 10 79.19 12.05 -0.09 +1498 0 20 20 10 78.57 11.20 7.35 +1499 0 20 40 10 77.36 9.84 22.78 +1500 0 20 70 10 75.72 8.57 49.29 +1501 0 40 0 10 70.66 26.17 -8.83 +1502 0 40 10 10 70.20 25.09 -2.01 +1503 0 40 20 10 69.66 24.31 4.85 +1504 0 40 40 10 68.63 23.17 18.78 +1505 0 40 70 10 67.18 22.19 42.85 +1506 0 70 0 10 56.54 48.71 -8.78 +1507 0 70 10 10 56.16 48.22 -3.01 +1508 0 70 20 10 55.82 47.41 2.66 +1509 0 70 40 10 55.25 46.37 14.45 +1510 0 70 70 10 54.42 45.45 34.15 +1511 10 0 0 10 85.30 -2.40 -10.30 +1512 10 0 10 10 84.64 -3.94 -1.90 +1513 10 0 20 10 83.94 -5.11 6.25 +1514 10 0 40 10 82.58 -6.97 22.88 +1515 10 0 70 10 80.69 -8.74 50.84 +1516 10 10 0 10 80.92 3.59 -11.37 +1517 10 10 10 10 80.31 2.16 -3.42 +1518 10 10 20 10 79.64 1.02 4.36 +1519 10 10 40 10 78.32 -0.75 20.31 +1520 10 10 70 10 76.52 -2.40 47.48 +1521 10 20 0 10 76.55 9.49 -12.01 +1522 10 20 10 10 75.96 8.13 -4.43 +1523 10 20 20 10 75.34 7.07 3.10 +1524 10 20 40 10 74.08 5.48 18.28 +1525 10 20 70 10 72.37 3.91 44.21 +1526 10 40 0 10 67.78 22.03 -12.78 +1527 10 40 10 10 67.26 20.88 -6.02 +1528 10 40 20 10 66.70 19.95 0.71 +1529 10 40 40 10 65.67 18.52 14.59 +1530 10 40 70 10 64.17 17.26 38.14 +1531 10 70 0 10 53.96 44.28 -12.87 +1532 10 70 10 10 53.60 43.38 -7.17 +1533 10 70 20 10 53.24 42.67 -1.51 +1534 10 70 40 10 52.65 41.55 10.21 +1535 10 70 70 10 51.72 40.18 29.77 +1536 20 0 0 10 81.61 -5.48 -14.56 +1537 20 0 10 10 80.91 -7.17 -6.30 +1538 20 0 20 10 80.21 -8.56 1.77 +1539 20 0 40 10 78.80 -10.64 18.04 +1540 20 0 70 10 76.83 -12.75 45.48 +1541 20 10 0 10 77.43 0.32 -15.46 +1542 20 10 10 10 76.80 -1.33 -7.59 +1543 20 10 20 10 76.12 -2.57 0.04 +1544 20 10 40 10 74.74 -4.63 15.66 +1545 20 10 70 10 72.86 -6.62 42.38 +1546 20 20 0 10 73.23 6.03 -15.93 +1547 20 20 10 10 72.61 4.53 -8.46 +1548 20 20 20 10 71.98 3.31 -1.11 +1549 20 20 40 10 70.70 1.43 13.78 +1550 20 20 70 10 68.92 -0.45 39.35 +1551 20 40 0 10 64.72 18.15 -16.53 +1552 20 40 10 10 64.19 16.90 -9.85 +1553 20 40 20 10 63.62 15.86 -3.18 +1554 20 40 40 10 62.59 14.17 10.46 +1555 20 40 70 10 61.07 12.57 33.64 +1556 20 70 0 10 51.28 39.93 -16.57 +1557 20 70 10 10 50.93 38.94 -10.90 +1558 20 70 20 10 50.57 38.10 -5.41 +1559 20 70 40 10 49.96 36.56 6.09 +1560 20 70 70 10 49.00 35.14 25.36 +1561 40 0 0 10 74.18 -12.07 -23.20 +1562 40 0 10 10 73.40 -14.10 -15.36 +1563 40 0 20 10 72.65 -15.78 -7.61 +1564 40 0 40 10 71.21 -18.63 8.10 +1565 40 0 70 10 69.18 -21.62 34.72 +1566 40 10 0 10 70.30 -6.51 -23.88 +1567 40 10 10 10 69.62 -8.55 -16.29 +1568 40 10 20 10 68.92 -10.17 -8.86 +1569 40 10 40 10 67.54 -12.92 6.29 +1570 40 10 70 10 65.62 -15.82 31.84 +1571 40 20 0 10 66.44 -0.99 -24.08 +1572 40 20 10 10 65.79 -3.00 -16.85 +1573 40 20 20 10 65.12 -4.53 -9.77 +1574 40 20 40 10 63.82 -7.18 4.70 +1575 40 20 70 10 62.04 -9.90 29.26 +1576 40 40 0 10 58.51 10.38 -24.34 +1577 40 40 10 10 58.01 8.75 -17.80 +1578 40 40 20 10 57.40 7.44 -11.40 +1579 40 40 40 10 56.29 5.08 1.86 +1580 40 40 70 10 54.79 2.64 24.08 +1581 40 70 0 10 45.93 31.07 -24.24 +1582 40 70 10 10 45.59 29.75 -18.80 +1583 40 70 20 10 45.20 28.62 -13.36 +1584 40 70 40 10 44.43 26.65 -2.21 +1585 40 70 70 10 43.56 24.36 16.26 +1586 70 0 0 10 62.40 -23.02 -37.07 +1587 70 0 10 10 61.58 -25.88 -29.74 +1588 70 0 20 10 60.85 -28.45 -22.33 +1589 70 0 40 10 59.42 -32.83 -7.37 +1590 70 0 70 10 57.39 -38.02 17.38 +1591 70 10 0 10 59.10 -17.72 -37.33 +1592 70 10 10 10 58.41 -20.70 -30.10 +1593 70 10 20 10 57.69 -23.19 -23.01 +1594 70 10 40 10 56.34 -27.56 -8.62 +1595 70 10 70 10 54.39 -32.60 15.20 +1596 70 20 0 10 55.73 -12.82 -37.04 +1597 70 20 10 10 55.15 -15.56 -30.18 +1598 70 20 20 10 54.45 -17.96 -23.43 +1599 70 20 40 10 53.13 -22.13 -9.64 +1600 70 20 70 10 51.30 -27.04 13.19 +1601 70 40 0 10 48.89 -2.37 -36.71 +1602 70 40 10 10 48.38 -4.80 -30.47 +1603 70 40 20 10 47.76 -6.91 -24.27 +1604 70 40 40 10 46.66 -10.68 -11.66 +1605 70 40 70 10 45.12 -15.17 9.13 +1606 70 70 0 10 37.75 16.76 -36.11 +1607 70 70 10 10 37.46 14.56 -30.89 +1608 70 70 20 10 37.07 12.70 -25.68 +1609 70 70 40 10 36.35 9.41 -14.88 +1610 70 70 70 10 35.34 5.51 2.36 +1611 50 40 40 0 56.52 0.52 -2.91 +1612 100 0 0 10 52.62 -33.38 -48.95 +1613 0 100 0 10 44.79 70.33 -5.59 +1614 0 0 100 10 82.93 -4.35 86.26 +1615 0 100 100 10 44.53 64.54 41.83 +1616 100 0 100 10 46.36 -61.85 22.67 +1617 100 100 0 10 23.48 19.48 -44.21 +END_DATA diff --git a/crates/color/data/FOGRA52.txt b/crates/color/data/FOGRA52.txt new file mode 100644 index 0000000000..229c5b1c5f --- /dev/null +++ b/crates/color/data/FOGRA52.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA52" +ORIGINATOR "Fogra, www.fogra.org, developed with GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 5 = Wood-free uncoated, fluorescence high (> 14 DeltaB according to ISO 15397), 120 g/m2, tone value increase curves C (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 93.50 2.50 -10.00 +2 0 10 0 0 87.84 10.05 -10.46 +3 0 20 0 0 82.74 17.07 -10.66 +4 0 30 0 0 78.06 23.70 -10.61 +5 0 40 0 0 73.74 30.00 -10.32 +6 0 55 0 0 67.80 39.21 -9.60 +7 0 70 0 0 62.30 47.89 -8.22 +8 0 85 0 0 57.60 55.31 -6.22 +9 0 100 0 0 54.54 60.07 -4.30 +10 10 0 0 0 88.67 -1.16 -15.51 +11 10 10 0 0 83.36 5.91 -15.71 +12 10 20 0 0 78.55 12.48 -15.69 +13 10 30 0 0 74.13 18.69 -15.49 +14 10 40 0 0 70.02 24.58 -15.08 +15 10 55 0 0 64.43 33.15 -14.16 +16 10 70 0 0 59.19 41.31 -12.69 +17 10 85 0 0 54.66 48.36 -10.74 +18 10 100 0 0 51.67 52.96 -8.93 +19 20 0 0 0 84.29 -4.47 -20.44 +20 20 10 0 0 79.29 2.17 -20.40 +21 20 20 0 0 74.76 8.33 -20.19 +22 20 30 0 0 70.57 14.15 -19.84 +23 20 40 0 0 66.67 19.68 -19.34 +24 20 55 0 0 61.40 27.65 -18.21 +25 20 70 0 0 56.42 35.28 -16.64 +26 20 85 0 0 52.07 41.96 -14.69 +27 20 100 0 0 49.17 46.36 -12.96 +28 30 0 0 0 80.24 -7.50 -24.94 +29 30 10 0 0 75.53 -1.25 -24.68 +30 30 20 0 0 71.25 4.53 -24.30 +31 30 30 0 0 67.29 9.98 -23.81 +32 30 40 0 0 63.58 15.17 -23.20 +33 30 55 0 0 58.63 22.56 -21.87 +34 30 70 0 0 53.91 29.68 -20.18 +35 30 85 0 0 49.75 35.95 -18.21 +36 30 100 0 0 46.94 40.15 -16.52 +37 40 0 0 0 76.45 -10.28 -29.09 +38 40 10 0 0 72.02 -4.41 -28.63 +39 40 20 0 0 67.98 1.02 -28.09 +40 40 30 0 0 64.23 6.14 -27.46 +41 40 40 0 0 60.71 10.99 -26.76 +42 40 55 0 0 56.06 17.83 -25.22 +43 40 70 0 0 51.61 24.43 -23.39 +44 40 85 0 0 47.65 30.29 -21.37 +45 40 100 0 0 44.95 34.24 -19.69 +46 55 0 0 0 71.16 -14.26 -34.98 +47 55 10 0 0 67.16 -8.79 -34.07 +48 55 20 0 0 63.52 -3.74 -33.13 +49 55 30 0 0 60.12 1.02 -32.16 +50 55 40 0 0 56.92 5.55 -31.14 +51 55 55 0 0 52.80 11.83 -29.39 +52 55 70 0 0 48.83 17.92 -27.40 +53 55 85 0 0 45.28 23.39 -25.30 +54 55 100 0 0 42.84 27.13 -23.62 +55 70 0 0 0 66.13 -17.82 -40.45 +56 70 10 0 0 62.55 -12.77 -39.12 +57 70 20 0 0 59.27 -8.11 -37.83 +58 70 30 0 0 56.21 -3.72 -36.53 +59 70 40 0 0 53.32 0.45 -35.22 +60 70 55 0 0 49.74 6.14 -33.24 +61 70 70 0 0 46.26 11.70 -31.09 +62 70 85 0 0 43.12 16.72 -28.88 +63 70 100 0 0 40.96 20.19 -27.16 +64 85 0 0 0 61.71 -20.66 -45.11 +65 85 10 0 0 58.47 -16.02 -43.45 +66 85 20 0 0 55.52 -11.74 -41.84 +67 85 30 0 0 52.76 -7.72 -40.26 +68 85 40 0 0 50.15 -3.88 -38.69 +69 85 55 0 0 47.05 1.23 -36.52 +70 85 70 0 0 44.04 6.24 -34.20 +71 85 85 0 0 41.32 10.80 -31.87 +72 85 100 0 0 39.43 13.98 -30.09 +73 100 0 0 0 58.70 -22.35 -48.12 +74 100 10 0 0 55.71 -18.02 -46.24 +75 100 20 0 0 52.98 -14.03 -44.44 +76 100 30 0 0 50.42 -10.26 -42.69 +77 100 40 0 0 48.01 -6.69 -40.95 +78 100 55 0 0 45.25 -2.00 -38.66 +79 100 70 0 0 42.57 2.62 -36.22 +80 100 85 0 0 40.15 6.83 -33.80 +81 100 100 0 0 38.47 9.76 -31.96 +82 0 0 10 0 92.65 0.82 0.84 +83 0 10 10 0 87.02 8.58 -0.61 +84 0 20 10 0 81.96 15.80 -1.70 +85 0 30 10 0 77.31 22.61 -2.48 +86 0 40 10 0 73.02 29.08 -2.98 +87 0 55 10 0 67.21 38.37 -3.29 +88 0 70 10 0 61.83 47.13 -2.94 +89 0 85 10 0 57.23 54.62 -1.90 +90 0 100 10 0 54.24 59.43 -0.66 +91 10 0 10 0 87.76 -3.15 -5.03 +92 10 10 10 0 82.49 4.15 -6.14 +93 10 20 10 0 77.74 10.93 -6.96 +94 10 30 10 0 73.37 17.34 -7.53 +95 10 40 10 0 69.31 23.43 -7.87 +96 10 55 10 0 63.85 32.11 -7.97 +97 10 70 10 0 58.74 40.38 -7.50 +98 10 85 10 0 54.33 47.53 -6.49 +99 10 100 10 0 51.42 52.21 -5.36 +100 20 0 10 0 83.32 -6.77 -10.27 +101 20 10 10 0 78.39 0.13 -11.09 +102 20 20 10 0 73.92 6.52 -11.67 +103 20 30 10 0 69.80 12.55 -12.06 +104 20 40 10 0 65.96 18.29 -12.24 +105 20 55 10 0 60.84 26.41 -12.11 +106 20 70 10 0 56.00 34.18 -11.54 +107 20 85 10 0 51.78 40.98 -10.52 +108 20 100 10 0 48.95 45.49 -9.45 +109 30 0 10 0 79.22 -10.10 -15.07 +110 30 10 10 0 74.59 -3.58 -15.62 +111 30 20 10 0 70.40 2.45 -15.98 +112 30 30 10 0 66.51 8.13 -16.17 +113 30 40 10 0 62.87 13.54 -16.22 +114 30 55 10 0 58.08 21.11 -15.87 +115 30 70 10 0 53.51 28.39 -15.16 +116 30 85 10 0 49.49 34.83 -14.11 +117 30 100 10 0 46.77 39.14 -13.07 +118 40 0 10 0 75.39 -13.19 -19.50 +119 40 10 10 0 71.05 -7.03 -19.79 +120 40 20 10 0 67.11 -1.34 -19.94 +121 40 30 10 0 63.44 4.03 -19.97 +122 40 40 10 0 60.00 9.13 -19.88 +123 40 55 10 0 55.53 16.17 -19.31 +124 40 70 10 0 51.24 22.97 -18.44 +125 40 85 10 0 47.43 29.01 -17.31 +126 40 100 10 0 44.83 33.10 -16.29 +127 55 0 10 0 70.17 -17.38 -25.68 +128 55 10 10 0 66.26 -11.60 -25.50 +129 55 20 10 0 62.70 -6.27 -25.25 +130 55 30 10 0 59.38 -1.25 -24.92 +131 55 40 10 0 56.27 3.52 -24.51 +132 55 55 10 0 52.29 10.03 -23.64 +133 55 70 10 0 48.44 16.37 -22.55 +134 55 85 10 0 45.00 22.06 -21.29 +135 55 100 10 0 42.64 25.93 -20.20 +136 70 0 10 0 65.19 -21.21 -31.44 +137 70 10 10 0 61.70 -15.83 -30.84 +138 70 20 10 0 58.51 -10.86 -30.21 +139 70 30 10 0 55.53 -6.19 -29.54 +140 70 40 10 0 52.72 -1.75 -28.83 +141 70 55 10 0 49.23 4.22 -27.67 +142 70 70 10 0 45.84 10.04 -26.34 +143 70 85 10 0 42.79 15.30 -24.89 +144 70 100 10 0 40.68 18.93 -23.72 +145 85 0 10 0 60.80 -24.35 -36.38 +146 85 10 10 0 57.67 -19.34 -35.43 +147 85 20 10 0 54.80 -14.73 -34.48 +148 85 30 10 0 52.12 -10.39 -33.53 +149 85 40 10 0 49.59 -6.27 -32.54 +150 85 55 10 0 46.55 -0.84 -31.12 +151 85 70 10 0 43.60 4.47 -29.55 +152 85 85 10 0 40.92 9.31 -27.94 +153 85 100 10 0 39.07 12.66 -26.66 +154 100 0 10 0 57.83 -26.26 -39.62 +155 100 10 10 0 54.93 -21.54 -38.43 +156 100 20 10 0 52.28 -17.18 -37.28 +157 100 30 10 0 49.81 -13.10 -36.12 +158 100 40 10 0 47.47 -9.21 -34.97 +159 100 55 10 0 44.75 -4.17 -33.38 +160 100 70 10 0 42.10 0.77 -31.65 +161 100 85 10 0 39.70 5.27 -29.89 +162 100 100 10 0 38.04 8.40 -28.52 +163 0 0 20 0 91.90 -0.46 10.79 +164 0 10 20 0 86.29 7.45 8.46 +165 0 20 20 0 81.25 14.82 6.55 +166 0 30 20 0 76.63 21.78 5.01 +167 0 40 20 0 72.37 28.37 3.80 +168 0 55 20 0 66.68 37.70 2.53 +169 0 70 20 0 61.40 46.50 1.95 +170 0 85 20 0 56.90 54.03 2.11 +171 0 100 20 0 53.96 58.87 2.71 +172 10 0 20 0 86.95 -4.72 4.61 +173 10 10 20 0 81.72 2.76 2.67 +174 10 20 20 0 77.01 9.71 1.08 +175 10 30 20 0 72.68 16.27 -0.21 +176 10 40 20 0 68.66 22.50 -1.22 +177 10 55 20 0 63.33 31.26 -2.24 +178 10 70 20 0 58.34 39.59 -2.71 +179 10 85 20 0 54.03 46.81 -2.56 +180 10 100 20 0 51.18 51.54 -2.06 +181 20 0 20 0 82.46 -8.61 -0.93 +182 20 10 20 0 77.58 -1.53 -2.53 +183 20 20 20 0 73.17 5.05 -3.83 +184 20 30 20 0 69.10 11.26 -4.88 +185 20 40 20 0 65.31 17.16 -5.70 +186 20 55 20 0 60.32 25.37 -6.49 +187 20 70 20 0 55.62 33.24 -6.82 +188 20 85 20 0 51.51 40.14 -6.66 +189 20 100 20 0 48.76 44.71 -6.20 +190 30 0 20 0 78.31 -12.23 -6.00 +191 30 10 20 0 73.76 -5.50 -7.28 +192 30 20 20 0 69.62 0.73 -8.31 +193 30 30 20 0 65.80 6.61 -9.14 +194 30 40 20 0 62.23 12.20 -9.78 +195 30 55 20 0 57.58 19.89 -10.33 +196 30 70 20 0 53.16 27.29 -10.51 +197 30 85 20 0 49.26 33.85 -10.29 +198 30 100 20 0 46.62 38.25 -9.87 +199 40 0 20 0 74.44 -15.60 -10.68 +200 40 10 20 0 70.19 -9.21 -11.66 +201 40 20 20 0 66.32 -3.30 -12.44 +202 40 30 20 0 62.73 2.28 -13.06 +203 40 40 20 0 59.36 7.57 -13.53 +204 40 55 20 0 55.05 14.75 -13.84 +205 40 70 20 0 50.91 21.70 -13.85 +206 40 85 20 0 47.23 27.89 -13.56 +207 40 100 20 0 44.72 32.08 -13.13 +208 55 0 20 0 69.28 -19.99 -17.11 +209 55 10 20 0 65.45 -13.96 -17.62 +210 55 20 20 0 61.97 -8.40 -17.99 +211 55 30 20 0 58.73 -3.16 -18.24 +212 55 40 20 0 55.68 1.82 -18.38 +213 55 55 20 0 51.82 8.51 -18.34 +214 55 70 20 0 48.09 15.02 -18.05 +215 55 85 20 0 44.76 20.87 -17.55 +216 55 100 20 0 42.46 24.87 -17.02 +217 70 0 20 0 64.35 -24.06 -23.14 +218 70 10 20 0 60.94 -18.40 -23.20 +219 70 20 20 0 57.82 -13.18 -23.19 +220 70 30 20 0 54.91 -8.27 -23.09 +221 70 40 20 0 52.17 -3.61 -22.92 +222 70 55 20 0 48.77 2.56 -22.52 +223 70 70 20 0 45.46 8.60 -21.94 +224 70 85 20 0 42.48 14.06 -21.20 +225 70 100 20 0 40.42 17.82 -20.54 +226 85 0 20 0 60.01 -27.46 -28.34 +227 85 10 20 0 56.95 -22.15 -28.03 +228 85 20 20 0 54.16 -17.26 -27.69 +229 85 30 20 0 51.55 -12.67 -27.29 +230 85 40 20 0 49.09 -8.30 -26.85 +231 85 55 20 0 46.10 -2.62 -26.12 +232 85 70 20 0 43.19 2.95 -25.25 +233 85 85 20 0 40.56 8.00 -24.28 +234 85 100 20 0 38.73 11.50 -23.47 +235 100 0 20 0 57.06 -29.59 -31.76 +236 100 10 20 0 54.25 -24.54 -31.22 +237 100 20 20 0 51.67 -19.89 -30.66 +238 100 30 20 0 49.27 -15.52 -30.06 +239 100 40 20 0 47.00 -11.38 -29.43 +240 100 55 20 0 44.30 -6.06 -28.50 +241 100 70 20 0 41.68 -0.84 -27.41 +242 100 85 20 0 39.30 3.90 -26.26 +243 100 100 20 0 37.65 7.20 -25.35 +244 0 0 30 0 91.22 -1.45 20.12 +245 0 10 30 0 85.62 6.59 16.96 +246 0 20 30 0 80.60 14.07 14.29 +247 0 30 30 0 76.01 21.13 12.04 +248 0 40 30 0 71.77 27.83 10.16 +249 0 55 30 0 66.18 37.17 8.02 +250 0 70 30 0 60.99 45.97 6.55 +251 0 85 30 0 56.58 53.50 5.90 +252 0 100 30 0 53.70 58.36 5.90 +253 10 0 30 0 86.21 -5.97 13.64 +254 10 10 30 0 81.02 1.65 10.92 +255 10 20 30 0 76.34 8.73 8.62 +256 10 30 30 0 72.04 15.42 6.67 +257 10 40 30 0 68.06 21.77 5.03 +258 10 55 30 0 62.84 30.56 3.15 +259 10 70 30 0 57.96 38.92 1.82 +260 10 85 30 0 53.75 46.18 1.15 +261 10 100 30 0 50.96 50.94 1.07 +262 20 0 30 0 81.67 -10.12 7.82 +263 20 10 30 0 76.84 -2.88 5.50 +264 20 20 30 0 72.47 3.84 3.54 +265 20 30 30 0 68.45 10.19 1.86 +266 20 40 30 0 64.71 16.23 0.44 +267 20 55 30 0 59.85 24.49 -1.18 +268 20 70 30 0 55.26 32.42 -2.37 +269 20 85 30 0 51.26 39.38 -3.00 +270 20 100 30 0 48.58 44.02 -3.13 +271 30 0 30 0 77.48 -14.00 2.50 +272 30 10 30 0 72.99 -7.10 0.55 +273 30 20 30 0 68.91 -0.70 -1.11 +274 30 30 30 0 65.15 5.33 -2.53 +275 30 40 30 0 61.63 11.07 -3.73 +276 30 55 30 0 57.12 18.83 -5.10 +277 30 70 30 0 52.83 26.32 -6.12 +278 30 85 30 0 49.04 32.96 -6.69 +279 30 100 30 0 46.48 37.43 -6.83 +280 40 0 30 0 73.58 -17.64 -2.41 +281 40 10 30 0 69.40 -11.06 -4.03 +282 40 20 30 0 65.60 -4.97 -5.40 +283 40 30 30 0 62.07 0.78 -6.57 +284 40 40 30 0 58.78 6.24 -7.56 +285 40 55 30 0 54.61 13.52 -8.68 +286 40 70 30 0 50.61 20.57 -9.52 +287 40 85 30 0 47.05 26.88 -10.00 +288 40 100 30 0 44.62 31.15 -10.13 +289 55 0 30 0 68.47 -22.20 -9.07 +290 55 10 30 0 64.72 -15.97 -10.21 +291 55 20 30 0 61.30 -10.21 -11.15 +292 55 30 30 0 58.12 -4.79 -11.95 +293 55 40 30 0 55.14 0.37 -12.61 +294 55 55 30 0 51.39 7.19 -13.32 +295 55 70 30 0 47.77 13.83 -13.81 +296 55 85 30 0 44.52 19.81 -14.03 +297 55 100 30 0 42.29 23.90 -14.01 +298 70 0 30 0 63.60 -26.48 -15.34 +299 70 10 30 0 60.25 -20.60 -16.02 +300 70 20 30 0 57.20 -15.17 -16.58 +301 70 30 30 0 54.35 -10.06 -17.02 +302 70 40 30 0 51.68 -5.22 -17.36 +303 70 55 30 0 48.35 1.13 -17.66 +304 70 70 30 0 45.11 7.33 -17.78 +305 70 85 30 0 42.20 12.94 -17.71 +306 70 100 30 0 40.18 16.81 -17.53 +307 85 0 30 0 59.29 -30.13 -20.77 +308 85 10 30 0 56.31 -24.56 -21.08 +309 85 20 30 0 53.58 -19.44 -21.28 +310 85 30 30 0 51.03 -14.63 -21.42 +311 85 40 30 0 48.63 -10.07 -21.48 +312 85 55 30 0 45.68 -4.18 -21.40 +313 85 70 30 0 42.82 1.58 -21.18 +314 85 85 30 0 40.22 6.81 -20.82 +315 85 100 30 0 38.42 10.44 -20.46 +316 100 0 30 0 56.37 -32.45 -24.37 +317 100 10 30 0 53.63 -27.12 -24.43 +318 100 20 30 0 51.12 -22.22 -24.42 +319 100 30 30 0 48.77 -17.62 -24.35 +320 100 40 30 0 46.56 -13.26 -24.21 +321 100 55 30 0 43.89 -7.71 -23.87 +322 100 70 30 0 41.29 -2.27 -23.41 +323 100 85 30 0 38.93 2.68 -22.84 +324 100 100 30 0 37.28 6.11 -22.33 +325 0 0 40 0 90.59 -2.19 28.94 +326 0 10 40 0 85.01 5.94 25.01 +327 0 20 40 0 80.00 13.50 21.63 +328 0 30 40 0 75.42 20.65 18.71 +329 0 40 40 0 71.21 27.42 16.20 +330 0 55 40 0 65.70 36.74 13.23 +331 0 70 40 0 60.61 45.53 10.95 +332 0 85 40 0 56.28 53.05 9.51 +333 0 100 40 0 53.46 57.91 8.95 +334 10 0 40 0 85.53 -6.96 22.17 +335 10 10 40 0 80.36 0.76 18.73 +336 10 20 40 0 75.71 7.95 15.78 +337 10 30 40 0 71.44 14.74 13.20 +338 10 40 40 0 67.49 21.18 10.97 +339 10 55 40 0 62.38 29.97 8.27 +340 10 70 40 0 57.60 38.34 6.13 +341 10 85 40 0 53.48 45.62 4.70 +342 10 100 40 0 50.75 50.40 4.06 +343 20 0 40 0 80.94 -11.35 16.10 +344 20 10 40 0 76.16 -3.99 13.10 +345 20 20 40 0 71.83 2.85 10.52 +346 20 30 40 0 67.85 9.32 8.26 +347 20 40 40 0 64.15 15.46 6.29 +348 20 55 40 0 59.40 23.74 3.87 +349 20 70 40 0 54.93 31.70 1.88 +350 20 85 40 0 51.02 38.70 0.49 +351 20 100 40 0 48.41 43.37 -0.18 +352 30 0 40 0 76.71 -15.48 10.54 +353 30 10 40 0 72.27 -8.44 7.96 +354 30 20 40 0 68.25 -1.91 5.71 +355 30 30 40 0 64.54 4.26 3.75 +356 30 40 40 0 61.07 10.12 2.03 +357 30 55 40 0 56.69 17.92 -0.13 +358 30 70 40 0 52.52 25.46 -1.93 +359 30 85 40 0 48.84 32.17 -3.25 +360 30 100 40 0 46.35 36.68 -3.92 +361 40 0 40 0 72.77 -19.38 5.41 +362 40 10 40 0 68.66 -12.63 3.20 +363 40 20 40 0 64.92 -6.38 1.28 +364 40 30 40 0 61.46 -0.49 -0.40 +365 40 40 40 0 58.22 5.11 -1.89 +366 40 55 40 0 54.19 12.45 -3.78 +367 40 70 40 0 50.32 19.57 -5.38 +368 40 85 40 0 46.88 25.94 -6.59 +369 40 100 40 0 44.54 30.29 -7.25 +370 55 0 40 0 67.72 -24.08 -1.46 +371 55 10 40 0 64.03 -17.68 -3.18 +372 55 20 40 0 60.68 -11.76 -4.67 +373 55 30 40 0 57.55 -6.18 -5.97 +374 55 40 40 0 54.63 -0.88 -7.12 +375 55 55 40 0 50.98 6.03 -8.55 +376 55 70 40 0 47.46 12.76 -9.75 +377 55 85 40 0 44.31 18.84 -10.65 +378 55 100 40 0 42.14 23.01 -11.12 +379 70 0 40 0 62.90 -28.55 -7.94 +380 70 10 40 0 59.62 -22.48 -9.20 +381 70 20 40 0 56.62 -16.88 -10.29 +382 70 30 40 0 53.84 -11.61 -11.24 +383 70 40 40 0 51.21 -6.60 -12.06 +384 70 55 40 0 47.95 -0.13 -13.02 +385 70 70 40 0 44.78 6.19 -13.81 +386 70 85 40 0 41.93 11.92 -14.37 +387 70 100 40 0 39.95 15.88 -14.64 +388 85 0 40 0 58.63 -32.41 -13.59 +389 85 10 40 0 55.71 -26.64 -14.46 +390 85 20 40 0 53.04 -21.33 -15.20 +391 85 30 40 0 50.55 -16.34 -15.82 +392 85 40 40 0 48.20 -11.61 -16.36 +393 85 55 40 0 45.30 -5.55 -16.90 +394 85 70 40 0 42.47 0.36 -17.29 +395 85 85 40 0 39.90 5.75 -17.51 +396 85 100 40 0 38.12 9.48 -17.57 +397 100 0 40 0 55.74 -34.91 -17.35 +398 100 10 40 0 53.06 -29.37 -17.96 +399 100 20 40 0 50.61 -24.25 -18.48 +400 100 30 40 0 48.32 -19.46 -18.89 +401 100 40 40 0 46.16 -14.92 -19.23 +402 100 55 40 0 43.51 -9.18 -19.47 +403 100 70 40 0 40.92 -3.55 -19.58 +404 100 85 40 0 38.57 1.56 -19.55 +405 100 100 40 0 36.94 5.12 -19.44 +406 0 0 55 0 89.71 -2.76 41.59 +407 0 10 55 0 84.13 5.50 36.52 +408 0 20 55 0 79.14 13.19 32.10 +409 0 30 55 0 74.58 20.47 28.21 +410 0 40 55 0 70.39 27.37 24.77 +411 0 55 55 0 65.07 36.48 20.75 +412 0 70 55 0 60.15 45.10 17.39 +413 0 85 55 0 55.95 52.49 14.92 +414 0 100 55 0 53.21 57.28 13.60 +415 10 0 55 0 84.63 -7.77 34.17 +416 10 10 55 0 79.47 0.07 29.68 +417 10 20 55 0 74.83 7.37 25.75 +418 10 30 55 0 70.58 14.27 22.27 +419 10 40 55 0 66.65 20.82 19.18 +420 10 55 55 0 61.68 29.48 15.50 +421 10 70 55 0 57.03 37.74 12.35 +422 10 85 55 0 53.02 44.93 9.97 +423 10 100 55 0 50.37 49.66 8.64 +424 20 0 55 0 80.03 -12.41 27.49 +425 20 10 55 0 75.25 -4.94 23.52 +426 20 20 55 0 70.93 2.00 20.05 +427 20 30 55 0 66.97 8.57 16.95 +428 20 40 55 0 63.29 14.81 14.18 +429 20 55 55 0 58.64 23.03 10.82 +430 20 70 55 0 54.27 30.94 7.90 +431 20 85 55 0 50.45 37.89 5.63 +432 20 100 55 0 47.90 42.54 4.32 +433 30 0 55 0 75.79 -16.78 21.37 +434 30 10 55 0 71.36 -9.65 17.89 +435 30 20 55 0 67.35 -3.02 14.82 +436 30 30 55 0 63.65 3.24 12.08 +437 30 40 55 0 60.20 9.19 9.61 +438 30 55 55 0 55.88 16.99 6.59 +439 30 70 55 0 51.78 24.53 3.91 +440 30 85 55 0 48.16 31.24 1.77 +441 30 100 55 0 45.72 35.77 0.50 +442 40 0 55 0 71.84 -20.92 15.69 +443 40 10 55 0 67.74 -14.09 12.66 +444 40 20 55 0 64.01 -7.76 9.99 +445 40 30 55 0 60.56 -1.78 7.58 +446 40 40 55 0 57.34 3.91 5.41 +447 40 55 55 0 53.34 11.29 2.71 +448 40 70 55 0 49.51 18.48 0.28 +449 40 85 55 0 46.10 24.91 -1.69 +450 40 100 55 0 43.78 29.31 -2.91 +451 55 0 55 0 66.74 -25.80 8.22 +452 55 10 55 0 63.08 -19.29 5.76 +453 55 20 55 0 59.74 -13.26 3.58 +454 55 30 55 0 56.64 -7.58 1.63 +455 55 40 55 0 53.73 -2.18 -0.14 +456 55 55 55 0 50.13 4.78 -2.30 +457 55 70 55 0 46.66 11.57 -4.25 +458 55 85 55 0 43.55 17.70 -5.83 +459 55 100 55 0 41.41 21.92 -6.80 +460 70 0 55 0 61.87 -30.47 1.14 +461 70 10 55 0 58.62 -24.26 -0.79 +462 70 20 55 0 55.65 -18.53 -2.49 +463 70 30 55 0 52.89 -13.14 -4.02 +464 70 40 55 0 50.30 -8.02 -5.40 +465 70 55 55 0 47.10 -1.49 -7.01 +466 70 70 55 0 43.99 4.89 -8.46 +467 70 85 55 0 41.19 10.67 -9.62 +468 70 100 55 0 39.26 14.68 -10.34 +469 85 0 55 0 57.57 -34.54 -5.06 +470 85 10 55 0 54.68 -28.61 -6.53 +471 85 20 55 0 52.04 -23.14 -7.82 +472 85 30 55 0 49.59 -18.00 -8.98 +473 85 40 55 0 47.27 -13.13 -10.01 +474 85 55 55 0 44.44 -7.04 -11.11 +475 85 70 55 0 41.68 -1.06 -12.09 +476 85 85 55 0 39.19 4.38 -12.85 +477 85 100 55 0 37.45 8.16 -13.30 +478 100 0 55 0 54.64 -37.20 -9.23 +479 100 10 55 0 52.00 -31.47 -10.39 +480 100 20 55 0 49.59 -26.18 -11.41 +481 100 30 55 0 47.34 -21.23 -12.30 +482 100 40 55 0 45.22 -16.54 -13.10 +483 100 55 55 0 42.65 -10.75 -13.85 +484 100 70 55 0 40.14 -5.06 -14.48 +485 100 85 55 0 37.87 0.10 -14.94 +486 100 100 55 0 36.28 3.71 -15.19 +487 0 0 70 0 88.89 -2.96 53.84 +488 0 10 70 0 83.30 5.39 47.71 +489 0 20 70 0 78.31 13.18 42.32 +490 0 30 70 0 73.77 20.54 37.50 +491 0 40 70 0 69.60 27.52 33.18 +492 0 55 70 0 64.45 36.39 28.16 +493 0 70 70 0 59.68 44.80 23.75 +494 0 85 70 0 55.62 52.02 20.29 +495 0 100 70 0 52.97 56.72 18.22 +496 10 0 70 0 83.78 -8.21 45.81 +497 10 10 70 0 78.62 -0.30 40.34 +498 10 20 70 0 73.98 7.07 35.50 +499 10 30 70 0 69.74 14.05 31.16 +500 10 40 70 0 65.83 20.68 27.24 +501 10 55 70 0 60.99 29.16 22.61 +502 10 70 70 0 56.47 37.27 18.50 +503 10 85 70 0 52.57 44.34 15.19 +504 10 100 70 0 49.99 49.01 13.17 +505 20 0 70 0 79.17 -13.09 38.58 +506 20 10 70 0 74.38 -5.56 33.70 +507 20 20 70 0 70.07 1.44 29.37 +508 20 30 70 0 66.11 8.07 25.46 +509 20 40 70 0 62.44 14.38 21.92 +510 20 55 70 0 57.90 22.49 17.67 +511 20 70 70 0 53.62 30.30 13.86 +512 20 85 70 0 49.88 37.19 10.72 +513 20 100 70 0 47.39 41.80 8.77 +514 30 0 70 0 74.92 -17.70 31.92 +515 30 10 70 0 70.48 -10.52 27.60 +516 30 20 70 0 66.48 -3.85 23.74 +517 30 30 70 0 62.78 2.47 20.25 +518 30 40 70 0 59.34 8.48 17.07 +519 30 55 70 0 55.09 16.23 13.20 +520 30 70 70 0 51.04 23.74 9.67 +521 30 85 70 0 47.48 30.43 6.73 +522 30 100 70 0 45.08 34.96 4.87 +523 40 0 70 0 70.96 -22.09 25.73 +524 40 10 70 0 66.86 -15.22 21.93 +525 40 20 70 0 63.13 -8.85 18.53 +526 40 30 70 0 59.69 -2.82 15.43 +527 40 40 70 0 56.47 2.91 12.60 +528 40 55 70 0 52.50 10.32 9.10 +529 40 70 70 0 48.70 17.52 5.88 +530 40 85 70 0 45.32 23.99 3.16 +531 40 100 70 0 43.03 28.40 1.41 +532 55 0 70 0 65.81 -27.13 17.71 +533 55 10 70 0 62.15 -20.56 14.54 +534 55 20 70 0 58.83 -14.47 11.70 +535 55 30 70 0 55.74 -8.72 9.12 +536 55 40 70 0 52.85 -3.26 6.74 +537 55 55 70 0 49.29 3.71 3.87 +538 55 70 70 0 45.86 10.53 1.21 +539 55 85 70 0 42.79 16.70 -1.06 +540 55 100 70 0 40.69 20.94 -2.52 +541 70 0 70 0 60.89 -32.00 10.06 +542 70 10 70 0 57.66 -25.70 7.49 +543 70 20 70 0 54.71 -19.89 5.20 +544 70 30 70 0 51.98 -14.40 3.10 +545 70 40 70 0 49.40 -9.19 1.16 +546 70 55 70 0 46.26 -2.67 -1.07 +547 70 70 70 0 43.21 3.74 -3.16 +548 70 85 70 0 40.46 9.56 -4.93 +549 70 100 70 0 38.56 13.59 -6.08 +550 85 0 70 0 56.54 -36.28 3.33 +551 85 10 70 0 53.68 -30.23 1.28 +552 85 20 70 0 51.07 -24.65 -0.54 +553 85 30 70 0 48.65 -19.41 -2.20 +554 85 40 70 0 46.36 -14.42 -3.73 +555 85 55 70 0 43.60 -8.32 -5.39 +556 85 70 70 0 40.91 -2.31 -6.92 +557 85 85 70 0 38.48 3.15 -8.21 +558 85 100 70 0 36.78 6.95 -9.05 +559 100 0 70 0 53.58 -39.11 -1.22 +560 100 10 70 0 50.98 -33.23 -2.91 +561 100 20 70 0 48.60 -27.83 -4.42 +562 100 30 70 0 46.38 -22.74 -5.79 +563 100 40 70 0 44.30 -17.93 -7.04 +564 100 55 70 0 41.81 -12.12 -8.29 +565 100 70 70 0 39.38 -6.41 -9.42 +566 100 85 70 0 37.17 -1.22 -10.36 +567 100 100 70 0 35.64 2.40 -10.95 +568 0 0 85 0 88.16 -2.85 64.82 +569 0 10 85 0 82.57 5.54 57.79 +570 0 20 85 0 77.57 13.39 51.55 +571 0 30 85 0 73.04 20.81 45.93 +572 0 40 85 0 68.89 27.84 40.84 +573 0 55 85 0 63.89 36.46 34.94 +574 0 70 85 0 59.27 44.62 29.61 +575 0 85 85 0 55.32 51.66 25.22 +576 0 100 85 0 52.75 56.25 22.49 +577 10 0 85 0 83.04 -8.32 56.29 +578 10 10 85 0 77.86 -0.38 49.96 +579 10 20 85 0 73.22 7.03 44.34 +580 10 30 85 0 68.98 14.06 39.23 +581 10 40 85 0 65.09 20.72 34.60 +582 10 55 85 0 60.37 29.01 29.13 +583 10 70 85 0 55.95 36.95 24.14 +584 10 85 85 0 52.15 43.88 20.00 +585 10 100 85 0 49.64 48.46 17.36 +586 20 0 85 0 78.40 -13.42 48.57 +587 20 10 85 0 73.61 -5.88 42.90 +588 20 20 85 0 69.29 1.15 37.83 +589 20 30 85 0 65.34 7.82 33.22 +590 20 40 85 0 61.68 14.16 29.00 +591 20 55 85 0 57.22 22.14 23.96 +592 20 70 85 0 53.02 29.84 19.32 +593 20 85 85 0 49.36 36.62 15.41 +594 20 100 85 0 46.91 41.18 12.89 +595 30 0 85 0 74.14 -18.25 41.45 +596 30 10 85 0 69.70 -11.06 36.39 +597 30 20 85 0 65.69 -4.38 31.86 +598 30 30 85 0 61.99 1.96 27.70 +599 30 40 85 0 58.56 8.00 23.89 +600 30 55 85 0 54.36 15.68 19.27 +601 30 70 85 0 50.37 23.12 14.97 +602 30 85 85 0 46.86 29.77 11.31 +603 30 100 85 0 44.49 34.26 8.92 +604 40 0 85 0 70.17 -22.87 34.83 +605 40 10 85 0 66.07 -16.00 30.34 +606 40 20 85 0 62.34 -9.61 26.31 +607 40 30 85 0 58.90 -3.58 22.60 +608 40 40 85 0 55.69 2.17 19.19 +609 40 55 85 0 51.73 9.56 14.98 +610 40 70 85 0 47.95 16.77 11.03 +611 40 85 85 0 44.60 23.23 7.62 +612 40 100 85 0 42.32 27.65 5.38 +613 55 0 85 0 64.97 -28.05 26.32 +614 55 10 85 0 61.32 -21.46 22.53 +615 55 20 85 0 58.00 -15.34 19.12 +616 55 30 85 0 54.93 -9.56 15.96 +617 55 40 85 0 52.05 -4.06 13.05 +618 55 55 85 0 48.52 2.89 9.54 +619 55 70 85 0 45.13 9.70 6.22 +620 55 85 85 0 42.09 15.86 3.35 +621 55 100 85 0 40.01 20.11 1.44 +622 70 0 85 0 60.01 -33.09 18.18 +623 70 10 85 0 56.79 -26.75 15.05 +624 70 20 85 0 53.86 -20.89 12.23 +625 70 30 85 0 51.14 -15.35 9.62 +626 70 40 85 0 48.58 -10.09 7.21 +627 70 55 85 0 45.49 -3.58 4.39 +628 70 70 85 0 42.49 2.81 1.74 +629 70 85 85 0 39.78 8.63 -0.58 +630 70 100 85 0 37.91 12.67 -2.14 +631 85 0 85 0 55.61 -37.57 10.99 +632 85 10 85 0 52.78 -31.45 8.43 +633 85 20 85 0 50.20 -25.79 6.13 +634 85 30 85 0 47.79 -20.47 4.01 +635 85 40 85 0 45.53 -15.42 2.04 +636 85 55 85 0 42.83 -9.34 -0.11 +637 85 70 85 0 40.20 -3.35 -2.15 +638 85 85 85 0 37.82 2.12 -3.93 +639 85 100 85 0 36.16 5.94 -5.13 +640 100 0 85 0 52.63 -40.56 6.11 +641 100 10 85 0 50.05 -34.58 3.95 +642 100 20 85 0 47.70 -29.08 2.00 +643 100 30 85 0 45.51 -23.90 0.20 +644 100 40 85 0 43.45 -19.00 -1.45 +645 100 55 85 0 41.03 -13.21 -3.15 +646 100 70 85 0 38.67 -7.52 -4.74 +647 100 85 85 0 36.53 -2.33 -6.13 +648 100 100 85 0 35.04 1.31 -7.04 +649 0 0 100 0 87.66 -2.65 72.38 +650 0 10 100 0 82.06 5.78 64.76 +651 0 20 100 0 77.06 13.65 57.96 +652 0 30 100 0 72.52 21.10 51.81 +653 0 40 100 0 68.39 28.16 46.22 +654 0 55 100 0 63.50 36.57 39.70 +655 0 70 100 0 58.97 44.55 33.74 +656 0 85 100 0 55.11 51.44 28.74 +657 0 100 100 0 52.59 55.96 25.52 +658 10 0 100 0 82.52 -8.27 63.50 +659 10 10 100 0 77.33 -0.31 56.64 +660 10 20 100 0 72.69 7.12 50.49 +661 10 30 100 0 68.45 14.16 44.88 +662 10 40 100 0 64.56 20.85 39.76 +663 10 55 100 0 59.92 28.98 33.72 +664 10 70 100 0 55.59 36.78 28.13 +665 10 85 100 0 51.85 43.59 23.41 +666 10 100 100 0 49.39 48.11 20.33 +667 20 0 100 0 77.88 -13.51 55.48 +668 20 10 100 0 73.07 -5.97 49.29 +669 20 20 100 0 68.75 1.07 43.73 +670 20 30 100 0 64.80 7.74 38.65 +671 20 40 100 0 61.14 14.10 33.97 +672 20 55 100 0 56.74 21.96 28.38 +673 20 70 100 0 52.59 29.56 23.18 +674 20 85 100 0 48.98 36.27 18.73 +675 20 100 100 0 46.58 40.78 15.80 +676 30 0 100 0 73.60 -18.50 48.07 +677 30 10 100 0 69.16 -11.32 42.52 +678 30 20 100 0 65.14 -4.63 37.52 +679 30 30 100 0 61.44 1.71 32.93 +680 30 40 100 0 58.01 7.75 28.68 +681 30 55 100 0 53.84 15.36 23.55 +682 30 70 100 0 49.88 22.76 18.72 +683 30 85 100 0 46.41 29.34 14.55 +684 30 100 100 0 44.07 33.81 11.79 +685 40 0 100 0 69.63 -23.27 41.16 +686 40 10 100 0 65.52 -16.42 36.22 +687 40 20 100 0 61.79 -10.04 31.75 +688 40 30 100 0 58.34 -4.01 27.62 +689 40 40 100 0 55.13 1.74 23.81 +690 40 55 100 0 51.19 9.11 19.10 +691 40 70 100 0 47.42 16.29 14.66 +692 40 85 100 0 44.08 22.75 10.78 +693 40 100 100 0 41.82 27.15 8.20 +694 55 0 100 0 64.40 -28.54 32.33 +695 55 10 100 0 60.75 -21.95 28.12 +696 55 20 100 0 57.43 -15.83 24.31 +697 55 30 100 0 54.36 -10.05 20.78 +698 55 40 100 0 51.48 -4.54 17.49 +699 55 55 100 0 47.98 2.39 13.54 +700 55 70 100 0 44.61 9.17 9.78 +701 55 85 100 0 41.59 15.33 6.47 +702 55 100 100 0 39.53 19.57 4.25 +703 70 0 100 0 59.40 -33.69 23.86 +704 70 10 100 0 56.19 -27.34 20.36 +705 70 20 100 0 53.27 -21.45 17.17 +706 70 30 100 0 50.55 -15.90 14.21 +707 70 40 100 0 48.01 -10.62 11.47 +708 70 55 100 0 44.95 -4.14 8.27 +709 70 70 100 0 41.97 2.22 5.20 +710 70 85 100 0 39.30 8.03 2.50 +711 70 100 100 0 37.45 12.07 0.66 +712 85 0 100 0 54.97 -38.30 16.35 +713 85 10 100 0 52.15 -32.15 13.46 +714 85 20 100 0 49.58 -26.46 10.83 +715 85 30 100 0 47.19 -21.10 8.40 +716 85 40 100 0 44.94 -16.01 6.12 +717 85 55 100 0 42.28 -9.96 3.63 +718 85 70 100 0 39.69 -4.00 1.22 +719 85 85 100 0 37.35 1.45 -0.90 +720 85 100 100 0 35.72 5.26 -2.34 +721 100 0 100 0 51.97 -41.41 11.25 +722 100 10 100 0 49.41 -35.38 8.77 +723 100 20 100 0 47.07 -29.82 6.51 +724 100 30 100 0 44.90 -24.59 4.44 +725 100 40 100 0 42.86 -19.64 2.49 +726 100 55 100 0 40.49 -13.89 0.49 +727 100 70 100 0 38.17 -8.23 -1.42 +728 100 85 100 0 36.08 -3.04 -3.11 +729 100 100 100 0 34.61 0.58 -4.25 +730 0 0 0 20 79.36 2.03 -8.10 +731 0 10 0 20 74.95 7.78 -8.31 +732 0 20 0 20 70.96 13.13 -8.35 +733 0 40 0 20 63.82 22.99 -7.97 +734 0 70 0 20 54.68 36.65 -6.96 +735 0 100 0 20 48.15 46.40 -4.82 +736 10 0 0 20 75.61 -0.90 -11.96 +737 10 10 0 20 71.48 4.53 -12.03 +738 10 20 0 20 67.73 9.57 -11.96 +739 10 40 0 20 60.99 18.87 -11.45 +740 10 70 0 20 52.36 31.76 -10.17 +741 10 100 0 20 46.12 41.09 -8.02 +742 20 0 0 20 72.20 -3.57 -15.43 +743 20 10 0 20 68.31 1.57 -15.37 +744 20 20 0 20 64.78 6.33 -15.20 +745 20 40 0 20 58.42 15.11 -14.56 +746 20 70 0 20 50.28 27.27 -13.02 +747 20 100 0 20 44.31 36.19 -10.83 +748 40 0 0 20 66.02 -8.34 -21.55 +749 40 10 0 20 62.60 -3.73 -21.26 +750 40 20 0 20 59.48 0.54 -20.92 +751 40 40 0 20 53.82 8.39 -20.06 +752 40 70 0 20 46.61 19.16 -17.97 +753 40 100 0 20 41.22 27.19 -15.62 +754 70 0 0 20 57.80 -14.52 -30.30 +755 70 10 0 20 55.00 -10.44 -29.37 +756 70 20 0 20 52.44 -6.68 -28.45 +757 70 40 0 20 47.78 0.22 -26.59 +758 70 70 0 20 42.21 9.42 -23.89 +759 70 100 0 20 37.99 16.42 -21.28 +760 100 0 0 20 51.73 -18.65 -36.40 +761 100 10 0 20 49.38 -15.03 -35.04 +762 100 20 0 20 47.23 -11.69 -33.73 +763 100 40 0 20 43.30 -5.57 -31.16 +764 100 70 0 20 39.05 2.29 -28.00 +765 100 100 0 20 35.81 8.33 -25.10 +766 0 0 10 20 78.61 0.63 0.22 +767 0 10 10 20 74.20 6.53 -0.75 +768 0 20 10 20 70.22 12.00 -1.49 +769 0 40 10 20 63.10 22.10 -2.40 +770 0 70 10 20 54.20 35.88 -2.90 +771 0 100 10 20 47.85 45.74 -1.97 +772 10 0 10 20 74.81 -2.45 -3.96 +773 10 10 10 20 70.71 3.13 -4.73 +774 10 20 10 20 66.99 8.30 -5.31 +775 10 40 10 20 60.32 17.85 -5.99 +776 10 70 10 20 51.92 30.89 -6.17 +777 10 100 10 20 45.84 40.35 -5.20 +778 20 0 10 20 71.36 -5.26 -7.72 +779 20 10 10 20 67.54 0.03 -8.31 +780 20 20 10 20 64.06 4.94 -8.74 +781 20 40 10 20 57.80 13.98 -9.21 +782 20 70 10 20 49.87 26.30 -9.08 +783 20 100 10 20 44.07 35.35 -8.04 +784 40 0 10 20 65.13 -10.34 -14.38 +785 40 10 10 20 61.81 -5.55 -14.65 +786 40 20 10 20 58.77 -1.13 -14.81 +787 40 40 10 20 53.28 7.01 -14.88 +788 40 70 10 20 46.27 17.96 -14.14 +789 40 100 10 20 41.03 26.15 -12.88 +790 70 0 10 20 57.01 -16.78 -23.58 +791 70 10 10 20 54.30 -12.51 -23.19 +792 70 20 10 20 51.82 -8.57 -22.76 +793 70 40 10 20 47.31 -1.32 -21.81 +794 70 70 10 20 41.84 8.15 -20.23 +795 70 100 10 20 37.68 15.37 -18.52 +796 100 0 10 20 51.02 -21.19 -30.07 +797 100 10 10 20 48.75 -17.33 -29.23 +798 100 20 10 20 46.67 -13.78 -28.39 +799 100 40 10 20 42.89 -7.28 -26.72 +800 100 70 10 20 38.65 0.95 -24.49 +801 100 100 10 20 35.42 7.26 -22.34 +802 0 0 20 20 77.93 -0.47 7.88 +803 0 10 20 20 73.52 5.52 6.20 +804 0 20 20 20 69.54 11.09 4.82 +805 0 40 20 20 62.44 21.36 2.73 +806 0 70 20 20 53.76 35.22 0.86 +807 0 100 20 20 47.57 45.16 0.68 +808 10 0 20 20 74.09 -3.70 3.40 +809 10 10 20 20 70.02 1.99 1.99 +810 10 20 20 20 66.32 7.27 0.82 +811 10 40 20 20 59.71 17.00 -0.95 +812 10 70 20 20 51.51 30.13 -2.48 +813 10 100 20 20 45.59 39.68 -2.59 +814 20 0 20 20 70.60 -6.65 -0.63 +815 20 10 20 20 66.83 -1.24 -1.81 +816 20 20 20 20 63.40 3.77 -2.79 +817 20 40 20 20 57.23 13.02 -4.26 +818 20 70 20 20 49.50 25.44 -5.44 +819 20 100 20 20 43.84 34.59 -5.46 +820 40 0 20 20 64.32 -12.01 -7.77 +821 40 10 20 20 61.08 -7.09 -8.54 +822 40 20 20 20 58.13 -2.54 -9.17 +823 40 40 20 20 52.79 5.84 -10.10 +824 40 70 20 20 45.97 16.91 -10.59 +825 40 100 20 20 40.85 25.21 -10.33 +826 70 0 20 20 56.30 -18.70 -17.39 +827 70 10 20 20 53.67 -14.26 -17.48 +828 70 20 20 20 51.26 -10.17 -17.51 +829 70 40 20 20 46.88 -2.65 -17.40 +830 70 70 20 20 41.50 7.04 -16.83 +831 70 100 20 20 37.41 14.43 -15.96 +832 100 0 20 20 50.38 -23.36 -24.22 +833 100 10 20 20 48.18 -19.31 -23.85 +834 100 20 20 20 46.17 -15.59 -23.46 +835 100 40 20 20 42.51 -8.76 -22.59 +836 100 70 20 20 38.28 -0.23 -21.22 +837 100 100 20 20 35.05 6.31 -19.78 +838 0 0 40 20 76.72 -2.07 21.88 +839 0 10 40 20 72.31 4.05 18.94 +840 0 20 40 20 68.32 9.74 16.39 +841 0 40 40 20 61.23 20.23 12.16 +842 0 70 40 20 52.94 34.12 7.79 +843 0 100 40 20 47.06 44.14 5.58 +844 10 0 40 20 72.81 -5.56 16.87 +845 10 10 40 20 68.78 0.27 14.29 +846 10 20 40 20 65.12 5.69 12.05 +847 10 40 40 20 58.59 15.68 8.31 +848 10 70 40 20 50.77 28.85 4.35 +849 10 100 40 20 45.11 38.50 2.25 +850 20 0 40 20 69.26 -8.78 12.35 +851 20 10 40 20 65.56 -3.20 10.10 +852 20 20 40 20 62.21 1.96 8.14 +853 20 40 40 20 56.19 11.51 4.85 +854 20 70 40 20 48.82 23.99 1.29 +855 20 100 40 20 43.41 33.25 -0.67 +856 40 0 40 20 62.86 -14.67 4.32 +857 40 10 40 20 59.79 -9.55 2.65 +858 40 20 40 20 56.98 -4.80 1.18 +859 40 40 40 20 51.90 3.93 -1.30 +860 40 70 40 20 45.41 15.11 -4.03 +861 40 100 40 20 40.53 23.55 -5.62 +862 70 0 40 20 55.04 -21.77 -6.01 +863 70 10 40 20 52.55 -17.10 -6.98 +864 70 20 40 20 50.26 -12.78 -7.84 +865 70 40 40 20 46.12 -4.86 -9.23 +866 70 70 40 20 40.89 5.14 -10.55 +867 70 100 40 20 36.90 12.75 -11.20 +868 100 0 40 20 49.25 -26.89 -13.46 +869 100 10 40 20 47.18 -22.55 -13.95 +870 100 20 40 20 45.29 -18.56 -14.36 +871 100 40 40 20 41.84 -11.25 -14.98 +872 100 70 40 20 37.61 -2.24 -15.17 +873 100 100 40 20 34.37 4.65 -15.02 +874 0 0 70 20 74.77 -3.06 40.37 +875 0 10 70 20 70.51 3.15 35.90 +876 0 20 70 20 66.66 8.94 31.92 +877 0 40 70 20 59.85 19.65 25.08 +878 0 70 70 20 52.01 32.82 17.49 +879 0 100 70 20 46.41 42.41 12.57 +880 10 0 70 20 70.92 -6.83 34.43 +881 10 10 70 20 66.99 -0.93 30.43 +882 10 20 70 20 63.44 4.57 26.87 +883 10 40 70 20 57.12 14.75 20.71 +884 10 70 70 20 49.72 27.43 13.77 +885 10 100 70 20 44.36 36.79 9.18 +886 20 0 70 20 67.42 -10.33 29.04 +887 20 10 70 20 63.80 -4.69 25.49 +888 20 20 70 20 60.53 0.55 22.30 +889 20 40 70 20 54.66 10.25 16.76 +890 20 70 70 20 47.67 22.45 10.45 +891 20 100 70 20 42.54 31.57 6.20 +892 40 0 70 20 61.14 -16.75 19.42 +893 40 10 70 20 58.08 -11.59 16.64 +894 40 20 70 20 55.29 -6.80 14.14 +895 40 40 70 20 50.26 2.04 9.75 +896 40 70 70 20 44.07 13.33 4.65 +897 40 100 70 20 39.44 21.90 1.13 +898 70 0 70 20 53.36 -24.18 7.46 +899 70 10 70 20 50.92 -19.43 5.59 +900 70 20 70 20 48.68 -15.03 3.91 +901 70 40 70 20 44.62 -6.96 0.94 +902 70 70 70 20 39.75 3.10 -2.24 +903 70 100 70 20 36.03 10.86 -4.43 +904 100 0 70 20 47.61 -29.64 -1.32 +905 100 10 70 20 45.61 -25.18 -2.54 +906 100 20 70 20 43.77 -21.08 -3.63 +907 100 40 70 20 40.45 -13.56 -5.53 +908 100 70 70 20 36.62 -4.51 -7.18 +909 100 100 70 20 33.68 2.47 -8.23 +910 0 0 100 20 73.29 -3.19 54.36 +911 0 10 100 20 69.13 3.02 48.81 +912 0 20 100 20 65.39 8.82 43.84 +913 0 40 100 20 58.78 19.57 35.09 +914 0 70 100 20 51.28 31.99 25.11 +915 0 100 100 20 45.90 41.12 18.09 +916 10 0 100 20 69.48 -7.20 47.79 +917 10 10 100 20 65.63 -1.31 42.78 +918 10 20 100 20 62.15 4.20 38.28 +919 10 40 100 20 55.99 14.40 30.33 +920 10 70 100 20 48.89 26.53 21.16 +921 10 100 100 20 43.75 35.54 14.67 +922 20 0 100 20 66.02 -10.92 41.81 +923 20 10 100 20 62.46 -5.31 37.31 +924 20 20 100 20 59.22 -0.07 33.24 +925 20 40 100 20 53.46 9.63 26.03 +926 20 70 100 20 46.76 21.46 17.64 +927 20 100 100 20 41.85 30.35 11.64 +928 40 0 100 20 59.83 -17.80 31.04 +929 40 10 100 20 56.77 -12.67 27.46 +930 40 20 100 20 53.99 -7.90 24.20 +931 40 40 100 20 48.98 0.92 18.37 +932 40 70 100 20 43.01 12.17 11.48 +933 40 100 100 20 38.56 20.76 6.46 +934 70 0 100 20 52.08 -25.47 17.93 +935 70 10 100 20 49.67 -20.72 15.39 +936 70 20 100 20 47.46 -16.32 13.08 +937 70 40 100 20 43.45 -8.23 8.93 +938 70 70 100 20 38.84 1.77 4.32 +939 70 100 100 20 35.34 9.53 0.93 +940 100 0 100 20 46.35 -31.21 8.19 +941 100 10 100 20 44.39 -26.72 6.41 +942 100 20 100 20 42.61 -22.59 4.81 +943 100 40 100 20 39.36 -15.00 1.93 +944 100 70 100 20 35.84 -6.03 -0.84 +945 100 100 100 20 33.14 0.95 -2.83 +946 0 0 0 40 66.75 1.60 -6.39 +947 0 20 0 40 60.42 9.67 -6.27 +948 0 40 0 40 54.96 16.86 -5.81 +949 0 70 0 40 47.98 26.68 -5.51 +950 0 100 0 40 42.76 33.96 -4.58 +951 20 0 0 40 61.38 -2.76 -11.01 +952 20 20 0 40 55.83 4.59 -10.77 +953 20 40 0 40 51.02 11.11 -10.30 +954 20 70 0 40 44.81 20.17 -9.61 +955 20 100 0 40 40.13 26.98 -8.53 +956 40 0 0 40 56.70 -6.57 -14.89 +957 40 20 0 40 51.84 0.17 -14.57 +958 40 40 0 40 47.61 6.13 -14.09 +959 40 70 0 40 42.12 14.49 -13.05 +960 40 100 0 40 37.93 20.83 -11.79 +961 70 0 0 40 50.38 -11.37 -21.24 +962 70 20 0 40 46.34 -5.23 -20.05 +963 70 40 0 40 42.81 0.16 -18.84 +964 70 70 0 40 38.57 7.48 -17.40 +965 70 100 0 40 35.31 13.10 -15.93 +966 100 0 0 40 45.61 -14.85 -25.81 +967 100 20 0 40 42.17 -9.20 -24.02 +968 100 40 0 40 39.16 -4.24 -22.28 +969 100 70 0 40 35.92 2.20 -20.53 +970 100 100 0 40 33.42 7.19 -18.88 +971 0 0 20 40 65.47 -0.48 5.38 +972 0 20 20 40 59.08 7.86 3.36 +973 0 40 20 40 53.58 15.25 1.93 +974 0 70 20 40 47.06 25.24 0.26 +975 0 100 20 40 42.20 32.70 -0.40 +976 20 0 20 40 60.00 -4.95 -0.33 +977 20 20 20 40 54.63 2.66 -1.83 +978 20 40 20 40 49.97 9.41 -2.90 +979 20 70 20 40 44.06 18.55 -4.01 +980 20 100 20 40 39.59 25.46 -4.39 +981 40 0 20 40 55.25 -8.86 -5.17 +982 40 20 20 40 50.76 -1.87 -6.25 +983 40 40 20 40 46.86 4.31 -7.01 +984 40 70 20 40 41.52 12.67 -7.58 +985 40 100 20 40 37.43 19.04 -7.65 +986 70 0 20 40 49.12 -13.93 -12.19 +987 70 20 20 40 45.39 -7.47 -12.37 +988 70 40 20 40 42.12 -1.78 -12.39 +989 70 70 20 40 37.93 5.67 -12.20 +990 70 100 20 40 34.69 11.41 -11.77 +991 100 0 20 40 44.49 -17.65 -17.31 +992 100 20 20 40 41.30 -11.61 -16.87 +993 100 40 20 40 38.53 -6.30 -16.34 +994 100 70 20 40 35.24 0.42 -15.56 +995 100 100 20 40 32.70 5.62 -14.72 +996 0 0 40 40 64.36 -1.94 15.73 +997 0 20 40 40 57.90 6.51 11.84 +998 0 40 40 40 52.36 14.01 8.75 +999 0 70 40 40 46.24 24.06 5.38 +1000 0 100 40 40 41.70 31.63 3.33 +1001 20 0 40 40 58.80 -6.53 9.08 +1002 20 20 40 40 53.58 1.20 6.07 +1003 20 40 40 40 49.05 8.07 3.65 +1004 20 70 40 40 43.39 17.20 0.98 +1005 20 100 40 40 39.11 24.15 -0.68 +1006 40 0 40 40 53.99 -10.57 3.41 +1007 40 20 40 40 49.82 -3.45 1.14 +1008 40 40 40 40 46.20 2.87 -0.72 +1009 40 70 40 40 40.99 11.16 -2.71 +1010 40 100 40 40 36.98 17.51 -3.96 +1011 70 0 40 40 48.02 -15.86 -4.18 +1012 70 20 40 40 44.55 -9.21 -5.56 +1013 70 40 40 40 41.52 -3.34 -6.65 +1014 70 70 40 40 37.36 4.18 -7.57 +1015 70 100 40 40 34.13 9.98 -8.06 +1016 100 0 40 40 43.51 -19.79 -9.78 +1017 100 20 40 40 40.55 -13.50 -10.51 +1018 100 40 40 40 37.97 -7.97 -11.04 +1019 100 70 40 40 34.64 -1.06 -11.13 +1020 100 100 40 40 32.05 4.27 -10.99 +1021 0 0 70 40 62.23 -3.04 28.54 +1022 0 20 70 40 56.29 5.38 22.83 +1023 0 40 70 40 51.20 12.89 18.08 +1024 0 70 70 40 45.35 22.29 12.39 +1025 0 100 70 40 40.98 29.42 8.38 +1026 20 0 70 40 56.93 -7.84 20.64 +1027 20 20 70 40 51.97 -0.15 16.08 +1028 20 40 70 40 47.68 6.72 12.26 +1029 20 70 70 40 42.41 15.57 7.65 +1030 20 100 70 40 38.41 22.37 4.38 +1031 40 0 70 40 52.35 -12.07 13.84 +1032 40 20 70 40 48.24 -4.98 10.27 +1033 40 40 70 40 44.66 1.32 7.26 +1034 40 70 70 40 39.91 9.65 3.65 +1035 40 100 70 40 36.28 16.10 1.08 +1036 70 0 70 40 46.63 -17.38 5.25 +1037 70 20 70 40 43.25 -10.82 2.83 +1038 70 40 70 40 40.30 -5.01 0.79 +1039 70 70 70 40 36.60 2.53 -1.37 +1040 70 100 70 40 33.74 8.40 -2.89 +1041 100 0 70 40 42.31 -21.38 -1.20 +1042 100 20 70 40 39.47 -15.19 -2.77 +1043 100 40 70 40 36.99 -9.75 -4.05 +1044 100 70 70 40 34.12 -2.84 -5.09 +1045 100 100 70 40 31.91 2.53 -5.72 +1046 0 0 100 40 60.56 -3.52 38.39 +1047 0 20 100 40 55.02 4.78 31.35 +1048 0 40 100 40 50.29 12.24 25.39 +1049 0 70 100 40 44.65 21.00 17.93 +1050 0 100 100 40 40.40 27.71 12.38 +1051 20 0 100 40 55.47 -8.52 29.61 +1052 20 20 100 40 50.71 -0.93 23.89 +1053 20 40 100 40 46.60 5.87 19.01 +1054 20 70 100 40 41.63 14.40 12.94 +1055 20 100 100 40 37.85 21.01 8.41 +1056 40 0 100 40 51.06 -12.93 22.00 +1057 40 20 100 40 46.98 -5.93 17.43 +1058 40 40 100 40 43.43 0.30 13.52 +1059 40 70 100 40 39.05 8.59 8.70 +1060 40 100 100 40 35.71 15.06 5.10 +1061 70 0 100 40 45.55 -18.28 12.67 +1062 70 20 100 40 42.23 -11.83 9.44 +1063 70 40 100 40 39.33 -6.12 6.68 +1064 70 70 100 40 36.00 1.38 3.57 +1065 70 100 100 40 33.43 7.26 1.25 +1066 100 0 100 40 41.38 -22.32 5.60 +1067 100 20 100 40 38.63 -16.27 3.38 +1068 100 40 100 40 36.21 -10.94 1.50 +1069 100 70 100 40 33.72 -4.11 -0.24 +1070 100 100 100 40 31.80 1.25 -1.49 +1071 0 0 0 60 54.52 1.49 -4.08 +1072 0 20 0 60 50.60 7.24 -3.86 +1073 0 40 0 60 47.18 12.39 -3.47 +1074 0 70 0 60 42.00 19.32 -3.15 +1075 0 100 0 60 38.02 24.59 -2.51 +1076 20 0 0 60 50.85 -1.53 -7.37 +1077 20 20 0 60 47.25 3.71 -7.07 +1078 20 40 0 60 44.10 8.38 -6.65 +1079 20 70 0 60 39.68 14.80 -5.95 +1080 20 100 0 60 36.25 19.73 -5.10 +1081 40 0 0 60 47.62 -4.19 -10.19 +1082 40 20 0 60 44.31 0.61 -9.82 +1083 40 40 0 60 41.41 4.88 -9.36 +1084 40 70 0 60 37.66 10.82 -8.34 +1085 40 100 0 60 34.75 15.43 -7.28 +1086 70 0 0 60 43.30 -7.63 -14.70 +1087 70 20 0 60 40.52 -3.23 -13.73 +1088 70 40 0 60 38.07 0.66 -12.77 +1089 70 70 0 60 35.16 5.91 -11.45 +1090 70 100 0 60 32.88 10.02 -10.20 +1091 100 0 0 60 39.97 -10.24 -18.06 +1092 100 20 0 60 37.58 -6.16 -16.67 +1093 100 40 0 60 35.49 -2.56 -15.34 +1094 100 70 0 60 33.24 2.14 -13.78 +1095 100 100 0 60 31.49 5.81 -12.36 +1096 0 0 20 60 53.78 -0.05 3.94 +1097 0 20 20 60 49.60 5.81 2.72 +1098 0 40 20 60 45.96 11.05 1.82 +1099 0 70 20 60 41.37 18.15 0.80 +1100 0 100 20 60 37.85 23.63 0.32 +1101 20 0 20 60 50.07 -3.14 -0.02 +1102 20 20 20 60 46.46 2.25 -0.90 +1103 20 40 20 60 43.31 7.05 -1.55 +1104 20 70 20 60 39.17 13.56 -2.11 +1105 20 100 20 60 35.97 18.58 -2.29 +1106 40 0 20 60 46.81 -5.86 -3.43 +1107 40 20 20 60 43.71 -0.87 -4.03 +1108 40 40 20 60 40.99 3.56 -4.45 +1109 40 70 20 60 37.27 9.49 -4.59 +1110 40 100 20 60 34.37 14.12 -4.49 +1111 70 0 20 60 42.46 -9.38 -8.40 +1112 70 20 20 60 39.90 -4.78 -8.38 +1113 70 40 20 60 37.65 -0.70 -8.27 +1114 70 70 20 60 34.72 4.62 -7.87 +1115 70 100 20 60 32.41 8.78 -7.38 +1116 100 0 20 60 39.10 -12.05 -12.15 +1117 100 20 20 60 36.96 -7.75 -11.68 +1118 100 40 20 60 35.07 -3.95 -11.17 +1119 100 70 20 60 32.76 0.88 -10.34 +1120 100 100 20 60 30.94 4.66 -9.53 +1121 0 0 40 60 53.14 -1.23 11.06 +1122 0 20 40 60 48.72 4.68 8.55 +1123 0 40 40 60 44.86 9.94 6.51 +1124 0 70 40 60 40.81 17.16 4.32 +1125 0 100 40 60 37.70 22.77 2.87 +1126 20 0 40 60 49.39 -4.39 6.51 +1127 20 20 40 60 45.77 1.09 4.58 +1128 20 40 40 60 42.59 5.97 3.00 +1129 20 70 40 60 38.72 12.48 1.33 +1130 20 100 40 60 35.72 17.56 0.23 +1131 40 0 40 60 46.10 -7.18 2.58 +1132 40 20 40 60 43.18 -2.08 1.13 +1133 40 40 40 60 40.62 2.47 -0.05 +1134 40 70 40 60 36.93 8.36 -1.23 +1135 40 100 40 60 34.03 12.96 -1.99 +1136 70 0 40 60 41.72 -10.76 -2.81 +1137 70 20 40 60 39.36 -6.02 -3.61 +1138 70 40 40 60 37.29 -1.83 -4.24 +1139 70 70 40 60 34.32 3.52 -4.66 +1140 70 100 40 60 31.99 7.70 -4.85 +1141 100 0 40 60 38.33 -13.49 -6.88 +1142 100 20 40 60 36.40 -9.04 -7.21 +1143 100 40 40 60 34.71 -5.10 -7.42 +1144 100 70 40 60 32.32 -0.20 -7.26 +1145 100 100 40 60 30.45 3.64 -6.99 +1146 0 0 70 60 51.70 -2.29 19.92 +1147 0 20 70 60 47.66 3.61 16.19 +1148 0 40 70 60 44.15 8.91 13.06 +1149 0 70 70 60 39.95 15.64 9.18 +1150 0 100 70 60 36.71 20.89 6.33 +1151 20 0 70 60 48.05 -5.53 14.50 +1152 20 20 70 60 44.63 -0.09 11.56 +1153 20 40 70 60 41.64 4.77 9.05 +1154 20 70 70 60 37.85 11.09 5.96 +1155 20 100 70 60 34.91 16.04 3.68 +1156 40 0 70 60 44.85 -8.38 9.78 +1157 40 20 70 60 41.98 -3.35 7.51 +1158 40 40 70 60 39.45 1.14 5.57 +1159 40 70 70 60 36.04 7.08 3.19 +1160 40 100 70 60 33.38 11.74 1.43 +1161 70 0 70 60 40.76 -11.97 3.82 +1162 70 20 70 60 38.43 -7.32 2.30 +1163 70 40 70 60 36.38 -3.18 1.02 +1164 70 70 70 60 33.67 2.21 -0.37 +1165 70 100 70 60 31.54 6.44 -1.34 +1166 100 0 70 60 37.61 -14.72 -0.75 +1167 100 20 70 60 35.69 -10.34 -1.70 +1168 100 40 70 60 34.00 -6.46 -2.48 +1169 100 70 70 60 31.85 -1.54 -3.05 +1170 100 100 70 60 30.15 2.35 -3.41 +1171 0 0 100 60 50.56 -2.90 26.86 +1172 0 20 100 60 46.82 2.94 22.22 +1173 0 40 100 60 43.58 8.21 18.25 +1174 0 70 100 60 39.26 14.50 13.05 +1175 0 100 100 60 35.91 19.39 9.09 +1176 20 0 100 60 46.98 -6.23 20.79 +1177 20 20 100 60 43.72 -0.88 17.06 +1178 20 40 100 60 40.87 3.93 13.86 +1179 20 70 100 60 37.15 10.04 9.65 +1180 20 100 100 60 34.26 14.83 6.43 +1181 40 0 100 60 43.85 -9.17 15.49 +1182 40 20 100 60 41.01 -4.24 12.56 +1183 40 40 100 60 38.51 0.18 10.03 +1184 40 70 100 60 35.33 6.11 6.71 +1185 40 100 100 60 32.85 10.80 4.17 +1186 70 0 100 60 40.01 -12.77 9.09 +1187 70 20 100 60 37.69 -8.20 7.00 +1188 70 40 100 60 35.65 -4.15 5.21 +1189 70 70 100 60 33.14 1.23 3.08 +1190 70 100 100 60 31.17 5.48 1.47 +1191 100 0 100 60 37.05 -15.55 4.15 +1192 100 20 100 60 35.13 -11.26 2.72 +1193 100 40 100 60 33.44 -7.46 1.49 +1194 100 70 100 60 31.47 -2.53 0.32 +1195 100 100 100 60 29.92 1.36 -0.52 +1196 0 0 0 80 42.14 1.38 -1.76 +1197 0 40 0 80 39.20 7.94 -1.09 +1198 0 70 0 80 35.92 11.91 -0.55 +1199 0 100 0 80 33.33 15.01 -0.01 +1200 40 0 0 80 38.37 -1.82 -5.43 +1201 40 40 0 80 35.03 3.64 -4.55 +1202 40 70 0 80 33.06 7.15 -3.49 +1203 40 100 0 80 31.52 9.93 -2.54 +1204 70 0 0 80 36.11 -3.79 -7.95 +1205 70 40 0 80 33.21 1.25 -6.53 +1206 70 70 0 80 31.62 4.44 -5.33 +1207 70 100 0 80 30.37 6.98 -4.26 +1208 100 0 0 80 34.33 -5.37 -9.91 +1209 100 40 0 80 31.76 -0.65 -8.07 +1210 100 70 0 80 30.49 2.29 -6.75 +1211 100 100 0 80 29.49 4.62 -5.58 +1212 0 0 40 80 41.75 -0.52 6.46 +1213 0 40 40 80 37.20 5.94 4.35 +1214 0 70 40 80 35.29 10.23 3.46 +1215 0 100 40 80 33.79 13.68 2.84 +1216 40 0 40 80 38.03 -3.84 1.81 +1217 40 40 40 80 34.84 2.05 0.69 +1218 40 70 40 80 32.71 5.54 0.36 +1219 40 100 40 80 31.02 8.31 0.19 +1220 70 0 40 80 35.27 -5.73 -1.27 +1221 70 40 40 80 32.90 -0.32 -1.70 +1222 70 70 40 80 31.16 2.85 -1.63 +1223 70 100 40 80 29.76 5.37 -1.49 +1224 100 0 40 80 33.09 -7.21 -3.66 +1225 100 40 40 80 31.37 -2.19 -3.56 +1226 100 70 40 80 29.93 0.74 -3.18 +1227 100 100 40 80 28.78 3.06 -2.80 +1228 0 0 70 80 41.00 -1.42 11.31 +1229 0 40 70 80 36.93 5.04 8.07 +1230 0 70 70 80 34.47 9.01 6.15 +1231 0 100 70 80 32.52 12.21 4.67 +1232 40 0 70 80 37.15 -4.71 5.72 +1233 40 40 70 80 34.05 0.97 3.88 +1234 40 70 70 80 32.03 4.49 2.78 +1235 40 100 70 80 30.42 7.29 1.95 +1236 70 0 70 80 34.75 -6.63 2.48 +1237 70 40 70 80 32.31 -1.37 1.31 +1238 70 70 70 80 30.61 1.86 0.72 +1239 70 100 70 80 29.24 4.44 0.31 +1240 100 0 70 80 32.84 -8.14 -0.07 +1241 100 40 70 80 30.93 -3.19 -0.73 +1242 100 70 70 80 29.48 -0.22 -0.89 +1243 100 100 70 80 28.32 2.16 -0.96 +1244 0 0 100 80 40.40 -2.08 15.17 +1245 0 40 100 80 36.72 4.36 11.06 +1246 0 70 100 80 33.81 8.06 8.30 +1247 0 100 100 80 31.49 11.01 6.15 +1248 40 0 100 80 36.45 -5.36 8.88 +1249 40 40 100 80 33.41 0.13 6.45 +1250 40 70 100 80 31.48 3.65 4.74 +1251 40 100 100 80 29.93 6.48 3.38 +1252 70 0 100 80 34.33 -7.31 5.50 +1253 70 40 100 80 31.83 -2.17 3.72 +1254 70 70 100 80 30.16 1.07 2.62 +1255 70 100 100 80 28.81 3.66 1.76 +1256 100 0 100 80 32.64 -8.84 2.85 +1257 100 40 100 80 30.57 -3.98 1.56 +1258 100 70 100 80 29.11 -0.97 0.96 +1259 100 100 100 80 27.93 1.44 0.49 +1260 0 0 0 100 32.69 1.24 0.11 +1261 0 40 0 100 33.02 4.60 0.85 +1262 0 100 0 100 29.84 7.72 2.31 +1263 40 0 0 100 31.27 -0.08 -1.70 +1264 40 40 0 100 30.06 2.72 -0.80 +1265 40 100 0 100 29.01 5.74 1.26 +1266 100 0 0 100 30.08 -1.53 -3.38 +1267 100 40 0 100 28.90 0.97 -2.30 +1268 100 100 0 100 27.93 3.85 -0.23 +1269 0 0 40 100 33.03 0.02 3.17 +1270 0 40 40 100 31.27 2.99 2.86 +1271 0 100 40 100 30.91 6.74 3.22 +1272 40 0 40 100 31.77 -1.40 1.34 +1273 40 40 40 100 30.32 1.70 1.32 +1274 40 100 40 100 28.67 4.75 2.00 +1275 100 0 40 100 29.11 -2.55 -0.93 +1276 100 40 40 100 28.78 0.03 -0.42 +1277 100 100 40 100 27.46 2.65 0.55 +1278 0 0 100 100 32.62 -1.23 6.32 +1279 0 40 100 100 31.43 1.66 5.61 +1280 0 100 100 100 28.21 4.77 4.26 +1281 40 0 100 100 30.73 -2.44 3.83 +1282 40 40 100 100 29.42 0.14 3.72 +1283 40 100 100 100 27.68 3.22 2.91 +1284 100 0 100 100 29.26 -3.87 1.98 +1285 100 40 100 100 28.33 -1.37 1.71 +1286 100 100 100 100 26.36 1.50 1.35 +1287 100 0 0 0 58.70 -22.35 -48.12 +1288 98 0 0 0 59.01 -22.19 -47.82 +1289 95 0 0 0 59.47 -21.94 -47.37 +1290 90 0 0 0 60.41 -21.42 -46.43 +1291 85 0 0 0 61.71 -20.66 -45.11 +1292 80 0 0 0 63.03 -19.85 -43.73 +1293 75 0 0 0 64.56 -18.87 -42.12 +1294 70 0 0 0 66.13 -17.82 -40.45 +1295 60 0 0 0 69.47 -15.49 -36.84 +1296 50 0 0 0 72.89 -12.97 -33.07 +1297 40 0 0 0 76.45 -10.28 -29.09 +1298 30 0 0 0 80.24 -7.50 -24.94 +1299 25 0 0 0 82.25 -6.00 -22.71 +1300 20 0 0 0 84.29 -4.47 -20.44 +1301 15 0 0 0 86.46 -2.83 -18.00 +1302 10 0 0 0 88.67 -1.16 -15.51 +1303 7 0 0 0 90.11 -0.07 -13.87 +1304 5 0 0 0 91.08 0.66 -12.77 +1305 3 0 0 0 92.04 1.39 -11.67 +1306 2 0 0 0 92.53 1.76 -11.12 +1307 0 100 0 0 54.54 60.07 -4.30 +1308 0 98 0 0 54.84 59.61 -4.52 +1309 0 95 0 0 55.31 58.89 -4.85 +1310 0 90 0 0 56.27 57.40 -5.47 +1311 0 85 0 0 57.60 55.31 -6.22 +1312 0 80 0 0 58.99 53.12 -6.91 +1313 0 75 0 0 60.61 50.56 -7.61 +1314 0 70 0 0 62.30 47.89 -8.22 +1315 0 60 0 0 65.93 42.15 -9.23 +1316 0 50 0 0 69.73 36.19 -9.91 +1317 0 40 0 0 73.74 30.00 -10.32 +1318 0 30 0 0 78.06 23.70 -10.61 +1319 0 25 0 0 80.38 20.40 -10.66 +1320 0 20 0 0 82.74 17.07 -10.66 +1321 0 15 0 0 85.26 13.57 -10.59 +1322 0 10 0 0 87.84 10.05 -10.46 +1323 0 7 0 0 89.52 7.78 -10.35 +1324 0 5 0 0 90.66 6.26 -10.26 +1325 0 3 0 0 91.79 4.76 -10.16 +1326 0 2 0 0 92.36 4.01 -10.11 +1327 0 0 100 0 87.66 -2.65 72.38 +1328 0 0 98 0 87.71 -2.67 71.61 +1329 0 0 95 0 87.79 -2.71 70.44 +1330 0 0 90 0 87.95 -2.77 68.05 +1331 0 0 85 0 88.16 -2.85 64.82 +1332 0 0 80 0 88.38 -2.91 61.53 +1333 0 0 75 0 88.63 -2.95 57.72 +1334 0 0 70 0 88.89 -2.96 53.84 +1335 0 0 60 0 89.43 -2.86 45.69 +1336 0 0 50 0 90.00 -2.61 37.42 +1337 0 0 40 0 90.59 -2.19 28.94 +1338 0 0 30 0 91.22 -1.45 20.12 +1339 0 0 25 0 91.55 -0.99 15.48 +1340 0 0 20 0 91.90 -0.46 10.79 +1341 0 0 15 0 92.27 0.15 5.84 +1342 0 0 10 0 92.65 0.82 0.84 +1343 0 0 7 0 92.90 1.29 -2.41 +1344 0 0 5 0 93.07 1.62 -4.58 +1345 0 0 3 0 93.24 1.96 -6.74 +1346 0 0 2 0 93.33 2.14 -7.83 +1347 0 0 0 100 32.69 1.24 0.11 +1348 0 0 0 98 33.41 1.25 -0.04 +1349 0 0 0 95 34.48 1.28 -0.28 +1350 0 0 0 90 36.58 1.31 -0.70 +1351 0 0 0 85 39.33 1.34 -1.23 +1352 0 0 0 80 42.14 1.38 -1.76 +1353 0 0 0 75 45.19 1.40 -2.33 +1354 0 0 0 70 48.31 1.44 -2.91 +1355 0 0 0 60 54.52 1.49 -4.08 +1356 0 0 0 50 60.65 1.55 -5.23 +1357 0 0 0 40 66.75 1.60 -6.39 +1358 0 0 0 30 72.92 1.81 -7.22 +1359 0 0 0 25 76.13 1.92 -7.66 +1360 0 0 0 20 79.36 2.03 -8.10 +1361 0 0 0 15 82.74 2.14 -8.55 +1362 0 0 0 10 86.16 2.25 -9.01 +1363 0 0 0 7 88.36 2.33 -9.31 +1364 0 0 0 5 89.84 2.38 -9.51 +1365 0 0 0 3 91.30 2.42 -9.70 +1366 0 0 0 2 92.03 2.45 -9.80 +1367 0 0 0 0 93.50 2.50 -10.00 +1368 100 85 85 0 36.53 -2.33 -6.13 +1369 80 65 65 0 42.78 -2.14 -7.05 +1370 60 45 45 0 51.99 -1.00 -7.01 +1371 40 27 27 0 63.31 -0.49 -8.22 +1372 20 12 12 0 77.32 1.07 -9.52 +1373 10 6 6 0 84.94 1.93 -9.69 +1374 5 3 3 0 89.15 2.29 -9.77 +1375 40 27 27 10 59.43 -0.41 -7.08 +1376 20 12 12 10 71.80 0.91 -8.28 +1377 10 6 6 10 78.56 1.68 -8.53 +1378 60 45 45 20 46.79 -0.60 -5.29 +1379 40 27 27 20 55.82 -0.34 -6.02 +1380 20 12 12 20 66.69 0.75 -7.12 +1381 10 6 6 20 72.66 1.46 -7.47 +1382 80 65 65 40 36.25 -0.61 -3.70 +1383 60 45 45 40 42.09 -0.28 -3.71 +1384 40 27 27 40 49.05 -0.22 -4.04 +1385 20 12 12 40 57.16 0.48 -4.97 +1386 10 6 6 40 61.67 1.04 -5.49 +1387 100 85 85 60 30.68 0.14 -1.47 +1388 80 65 65 60 33.43 0.03 -2.04 +1389 60 45 45 60 37.69 0.30 -2.11 +1390 40 27 27 60 42.56 0.29 -2.44 +1391 20 12 12 60 48.14 0.74 -3.13 +1392 10 6 6 60 51.18 1.12 -3.48 +1393 100 85 85 80 28.59 0.75 0.00 +1394 80 65 65 80 30.50 0.66 -0.29 +1395 60 45 45 80 33.13 0.84 -0.43 +1396 40 27 27 80 35.87 0.77 -0.77 +1397 20 12 12 80 38.92 0.98 -1.24 +1398 10 6 6 80 40.50 1.19 -1.45 +1399 100 85 85 100 26.92 1.19 1.21 +1400 80 65 65 100 28.18 1.11 1.17 +1401 60 45 45 100 29.54 1.21 0.94 +1402 40 27 27 100 30.65 1.11 0.58 +1403 20 12 12 100 31.80 1.11 0.29 +1404 10 6 6 100 32.30 1.20 0.20 +1405 100 0 0 70 37.13 -7.82 -14.02 +1406 0 100 0 70 35.65 19.79 -1.31 +1407 0 0 100 70 45.47 -2.51 20.99 +1408 100 100 0 70 30.49 5.19 -8.99 +1409 100 0 100 70 34.84 -12.16 3.48 +1410 0 100 100 70 33.68 15.17 7.55 +1411 40 40 0 70 38.22 4.25 -6.95 +1412 40 0 40 70 42.06 -5.49 2.18 +1413 0 40 40 70 41.03 7.91 5.42 +1414 3 3 0 0 90.36 3.61 -11.81 +1415 3 0 3 0 91.78 0.83 -8.44 +1416 0 3 3 0 91.53 4.24 -6.99 +1417 3 3 3 0 90.10 3.06 -8.67 +1418 3 0 0 3 89.89 1.35 -11.29 +1419 0 3 0 3 89.64 4.60 -9.85 +1420 3 3 0 3 88.27 3.49 -11.42 +1421 0 0 3 3 91.04 1.91 -6.56 +1422 3 0 3 3 89.63 0.81 -8.19 +1423 0 3 3 3 89.39 4.10 -6.80 +1424 3 3 3 3 88.01 2.96 -8.40 +1425 7 7 0 0 86.30 4.97 -14.09 +1426 7 0 7 0 89.48 -1.43 -6.45 +1427 0 7 7 0 88.94 6.68 -3.24 +1428 7 7 7 0 85.70 3.73 -7.13 +1429 7 0 0 7 85.25 -0.05 -12.76 +1430 0 7 0 7 84.70 7.15 -9.59 +1431 7 7 0 7 81.75 4.56 -12.93 +1432 0 0 7 7 87.79 1.20 -2.36 +1433 7 0 7 7 84.65 -1.31 -5.98 +1434 0 7 7 7 84.14 6.11 -3.09 +1435 7 7 7 7 81.17 3.40 -6.57 +1436 40 3 0 0 75.11 -8.52 -28.96 +1437 3 40 0 0 72.61 28.36 -11.77 +1438 40 0 3 0 76.13 -11.19 -26.21 +1439 40 3 3 0 74.80 -9.40 -26.15 +1440 0 40 3 0 73.52 29.71 -8.11 +1441 3 40 3 0 72.40 28.05 -9.57 +1442 40 40 3 0 60.49 10.41 -24.69 +1443 3 0 40 0 89.06 -3.62 26.89 +1444 0 3 40 0 88.90 0.24 27.73 +1445 3 3 40 0 87.40 -1.23 25.73 +1446 40 3 40 0 71.53 -17.36 4.73 +1447 3 40 40 0 70.08 25.54 14.61 +1448 40 0 0 3 74.83 -9.99 -27.91 +1449 40 3 0 3 73.54 -8.29 -27.79 +1450 0 40 0 3 72.20 28.90 -9.96 +1451 3 40 0 3 71.11 27.33 -11.34 +1452 40 40 0 3 59.64 10.58 -25.71 +1453 40 0 3 3 74.51 -10.84 -25.14 +1454 40 3 3 3 73.23 -9.12 -25.09 +1455 0 40 3 3 71.98 28.61 -7.83 +1456 3 40 3 3 70.90 27.01 -9.23 +1457 40 40 3 3 59.43 10.03 -23.73 +1458 0 0 40 3 88.43 -2.17 27.83 +1459 3 0 40 3 86.95 -3.55 25.86 +1460 40 0 40 3 71.23 -18.64 5.23 +1461 0 3 40 3 86.79 0.16 26.67 +1462 3 3 40 3 85.35 -1.24 24.75 +1463 40 3 40 3 70.04 -16.69 4.58 +1464 0 40 40 3 69.65 26.29 15.56 +1465 3 40 40 3 68.58 24.49 14.04 +1466 40 40 40 3 57.24 4.93 -1.80 +1467 3 0 0 40 65.91 0.92 -7.12 +1468 0 3 0 40 65.75 2.85 -6.39 +1469 3 3 0 40 64.93 2.16 -7.12 +1470 40 3 0 40 55.93 -5.52 -14.86 +1471 3 40 0 40 54.34 15.95 -6.52 +1472 0 0 3 40 66.55 1.24 -4.55 +1473 3 0 3 40 65.70 0.56 -5.31 +1474 40 0 3 40 56.47 -6.96 -13.37 +1475 0 3 3 40 65.55 2.51 -4.61 +1476 3 3 3 40 64.72 1.80 -5.36 +1477 40 3 3 40 55.72 -5.90 -13.37 +1478 0 40 3 40 54.75 16.59 -4.60 +1479 3 40 3 40 54.14 15.68 -5.32 +1480 40 40 3 40 47.49 5.84 -12.99 +1481 3 0 40 40 63.48 -2.65 14.68 +1482 0 3 40 40 63.34 -0.62 15.10 +1483 3 3 40 40 62.50 -1.36 14.07 +1484 40 3 40 40 53.33 -9.46 3.04 +1485 3 40 40 40 51.83 13.08 7.94 +1486 0 0 0 10 86.16 2.25 -9.01 +1487 0 0 10 10 85.35 0.72 0.51 +1488 0 0 20 10 84.64 -0.47 9.26 +1489 0 0 40 10 83.38 -2.13 25.25 +1490 0 0 70 10 81.55 -3.02 46.81 +1491 0 10 0 10 81.15 8.87 -9.35 +1492 0 10 10 10 80.36 7.51 -0.69 +1493 0 10 20 10 79.66 6.45 7.27 +1494 0 10 40 10 78.41 4.95 21.83 +1495 0 10 70 10 76.65 4.21 41.55 +1496 0 20 0 10 76.62 15.01 -9.46 +1497 0 20 10 10 75.86 13.81 -1.60 +1498 0 20 20 10 75.17 12.87 5.64 +1499 0 20 40 10 73.93 11.53 18.88 +1500 0 20 70 10 72.26 10.95 36.89 +1501 0 40 0 10 68.59 26.34 -9.11 +1502 0 40 10 10 67.87 25.43 -2.69 +1503 0 40 20 10 67.22 24.71 3.22 +1504 0 40 40 10 66.02 23.66 14.08 +1505 0 40 70 10 64.53 23.40 28.94 +1506 0 70 0 10 58.33 42.04 -7.60 +1507 0 70 10 10 57.85 41.28 -2.96 +1508 0 70 20 10 57.41 40.64 1.33 +1509 0 70 40 10 56.61 39.59 9.25 +1510 0 70 70 10 55.67 38.56 20.44 +1511 10 0 0 10 81.89 -1.02 -13.66 +1512 10 0 10 10 81.04 -2.78 -4.48 +1513 10 0 20 10 80.27 -4.19 3.97 +1514 10 0 40 10 78.92 -6.23 19.40 +1515 10 0 70 10 77.10 -7.50 39.88 +1516 10 10 0 10 77.19 5.19 -13.79 +1517 10 10 10 10 76.38 3.62 -5.41 +1518 10 10 20 10 75.65 2.36 2.31 +1519 10 10 40 10 74.34 0.50 16.41 +1520 10 10 70 10 72.58 -0.64 35.18 +1521 10 20 0 10 72.93 10.96 -13.75 +1522 10 20 10 10 72.16 9.56 -6.11 +1523 10 20 20 10 71.46 8.43 0.94 +1524 10 20 40 10 70.21 6.76 13.83 +1525 10 20 70 10 68.51 5.76 31.00 +1526 10 40 0 10 65.34 21.60 -13.20 +1527 10 40 10 10 64.65 20.51 -6.90 +1528 10 40 20 10 64.01 19.63 -1.09 +1529 10 40 40 10 62.87 18.31 9.57 +1530 10 40 70 10 61.31 17.57 23.83 +1531 10 70 0 10 55.63 36.34 -11.41 +1532 10 70 10 10 55.19 35.44 -6.85 +1533 10 70 20 10 54.78 34.67 -2.63 +1534 10 70 40 10 54.04 33.40 5.17 +1535 10 70 70 10 52.94 32.14 16.00 +1536 20 0 0 10 78.01 -4.00 -17.83 +1537 20 0 10 10 77.11 -5.98 -8.95 +1538 20 0 20 10 76.31 -7.59 -0.78 +1539 20 0 40 10 74.88 -10.01 14.14 +1540 20 0 70 10 73.07 -11.66 33.61 +1541 20 10 0 10 73.59 1.86 -17.78 +1542 20 10 10 10 72.76 0.08 -9.65 +1543 20 10 20 10 72.00 -1.38 -2.16 +1544 20 10 40 10 70.66 -3.58 11.53 +1545 20 10 70 10 68.89 -5.12 29.42 +1546 20 20 0 10 69.58 7.29 -17.60 +1547 20 20 10 10 68.80 5.69 -10.15 +1548 20 20 20 10 68.10 4.39 -3.29 +1549 20 20 40 10 66.84 2.39 9.27 +1550 20 20 70 10 65.12 0.96 25.69 +1551 20 40 0 10 62.39 17.30 -16.86 +1552 20 40 10 10 61.73 16.04 -10.67 +1553 20 40 20 10 61.12 15.00 -4.96 +1554 20 40 40 10 60.02 13.40 5.53 +1555 20 40 70 10 58.40 12.21 19.23 +1556 20 70 0 10 53.23 31.12 -14.78 +1557 20 70 10 10 52.81 30.08 -10.29 +1558 20 70 20 10 52.44 29.18 -6.13 +1559 20 70 40 10 51.75 27.69 1.55 +1560 20 70 70 10 50.52 26.21 12.05 +1561 40 0 0 10 71.04 -9.28 -25.17 +1562 40 0 10 10 70.06 -11.70 -16.84 +1563 40 0 20 10 69.19 -13.73 -9.17 +1564 40 0 40 10 67.63 -16.91 4.83 +1565 40 0 70 10 65.86 -19.30 22.44 +1566 40 10 0 10 67.13 -4.06 -24.80 +1567 40 10 10 10 66.26 -6.26 -17.12 +1568 40 10 20 10 65.47 -8.10 -10.04 +1569 40 10 40 10 64.05 -11.02 2.90 +1570 40 10 70 10 62.30 -13.33 19.17 +1571 40 20 0 10 63.57 0.76 -24.36 +1572 40 20 10 10 62.78 -1.23 -17.28 +1573 40 20 20 10 62.07 -2.89 -10.75 +1574 40 20 40 10 60.80 -5.56 1.22 +1575 40 20 70 10 59.07 -7.78 16.24 +1576 40 40 0 10 57.14 9.63 -23.28 +1577 40 40 10 10 56.52 8.03 -17.29 +1578 40 40 20 10 55.96 6.67 -11.76 +1579 40 40 40 10 54.95 4.49 -1.59 +1580 40 40 70 10 53.26 2.46 11.12 +1581 40 70 0 10 49.01 21.69 -20.59 +1582 40 70 10 10 48.67 20.37 -16.22 +1583 40 70 20 10 48.35 19.21 -12.17 +1584 40 70 40 10 47.78 17.25 -4.69 +1585 40 70 70 10 46.30 15.34 5.23 +1586 70 0 0 10 61.80 -16.14 -35.18 +1587 70 0 10 10 60.94 -18.92 -27.36 +1588 70 0 20 10 60.17 -21.27 -20.16 +1589 70 0 40 10 58.82 -25.01 -6.95 +1590 70 0 70 10 56.98 -27.91 8.69 +1591 70 10 0 10 58.63 -11.59 -34.06 +1592 70 10 10 10 57.86 -14.12 -26.87 +1593 70 10 20 10 57.17 -16.25 -20.24 +1594 70 10 40 10 55.95 -19.67 -8.06 +1595 70 10 70 10 54.16 -22.42 6.49 +1596 70 20 0 10 55.72 -7.39 -32.96 +1597 70 20 10 10 55.04 -9.68 -26.35 +1598 70 20 20 10 54.42 -11.62 -20.24 +1599 70 20 40 10 53.33 -14.74 -9.02 +1600 70 20 70 10 51.59 -17.35 4.51 +1601 70 40 0 10 50.44 0.32 -30.74 +1602 70 40 10 10 49.91 -1.54 -25.19 +1603 70 40 20 10 49.43 -3.11 -20.06 +1604 70 40 40 10 48.58 -5.70 -10.60 +1605 70 40 70 10 46.93 -8.02 1.04 +1606 70 70 0 10 44.16 10.50 -27.36 +1607 70 70 10 10 43.77 9.05 -23.18 +1608 70 70 20 10 43.41 7.78 -19.30 +1609 70 70 40 10 42.77 5.64 -12.13 +1610 70 70 70 10 41.42 3.41 -2.69 +1611 50 40 40 0 55.80 1.09 -5.42 +1612 100 0 0 10 55.07 -20.50 -42.06 +1613 0 100 0 10 51.18 53.01 -4.66 +1614 0 0 100 10 80.18 -2.95 63.01 +1615 0 100 100 10 49.06 48.28 21.54 +1616 100 0 100 10 49.05 -36.09 9.64 +1617 100 100 0 10 37.09 9.00 -28.41 +END_DATA diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 8122229b21..c74942fa5e 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -5,7 +5,9 @@ //! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB; //! the desktop canvas converts it into the display's own profile last, in the app. //! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model -//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers); +//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from +//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old +//! profile-free formula (kept for exact legacy numbers); //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). //! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with //! the profiles [`use_document_profiles`] last put in place of the working spaces; @@ -16,6 +18,7 @@ pub mod generic; pub mod icc; pub mod lab; +pub mod measured; use std::cell::{Cell, RefCell}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3"; pub const PROPHOTO_RGB: &str = "ProPhoto RGB"; /// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile. pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)"; +/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on +/// premium coated paper, see [`measured`]). +pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)"; +/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on +/// wood-free uncoated paper, see [`measured`]). +pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)"; /// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers. pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)"; /// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen). @@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)"; /// Built-in RGB and CMYK working spaces, in menu order. const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB]; -const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK]; +const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]; /// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents /// and commands that still use an old name get the current profile. @@ -239,6 +248,21 @@ fn generic() -> Arc { G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone() } +/// The working space of `condition`, computed from its data once and kept. +fn measured_space(condition: &measured::Condition) -> Result, CmsError> { + static SPACES: [OnceLock>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()]; + let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i)); + slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone()) + .ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference))) +} + +/// The registered printing condition a built-in CMYK working space characterizes: its reference +/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs +/// to (by its current or legacy name). `None` for every other profile. +pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> { + measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY)) +} + static USER: RwLock>> = RwLock::new(Vec::new()); /// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]). static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0); @@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option> { } fn cmyk_space(name: &str) -> Result { - match canonical_name(name) { + let canonical = canonical_name(name); + if let Some(c) = measured::condition(canonical) { + return measured_space(c).map(CmykSpace::Generic); + } + match canonical { GENERIC_CMYK => Ok(CmykSpace::Generic(generic())), DEVICE_CMYK => Ok(CmykSpace::Device), _ => match user_profile(name) { @@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { CmykSpace::Generic(g) => g.paper_xyz(), CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, }; + let copyright = match measured::condition(name) { + Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference), + None => icc::NO_COPYRIGHT.to_string(), + }; let to_lab = |c| cms.cmyk_to_lab(c); let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); - icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + icc::encode(&icc::cmyk_profile(name, paper, ©right, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } @@ -496,7 +528,8 @@ impl Cms { /// directly into the RGB profile: not through display sRGB, which would clip colours a wider /// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the /// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before - /// (Generic CMYK compensates in its own model). + /// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the + /// paper colour shows. pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] { let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0)); let src = match &self.cmyk { @@ -509,7 +542,7 @@ impl Cms { }; src.zip(dest) .and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc)) - .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false))) + .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric))) } /// Display sRGB → working CMYK with `intent`. pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] { @@ -1315,3 +1348,5 @@ pub(crate) fn cmyk_is_device() -> bool { mod tests; #[cfg(test)] mod tests_icc; +#[cfg(test)] +mod tests_measured; diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 16f251054b..57d9d9d329 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -30,6 +30,7 @@ use std::sync::OnceLock; use super::Intent; use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb}; +use super::measured::Lattice; /// Black generation. #[derive(Clone, Copy, Debug, PartialEq)] @@ -129,6 +130,9 @@ pub struct GenericCmyk { paper_xyz: [f32; 3], /// Media-relative XYZ of the black point (for black-point compensation). black_rel: [f32; 3], + /// A media-relative Lab correction added to the model, fitted to measured data + /// ([`super::measured`]). + correction: Option, gbd: OnceLock, } @@ -139,6 +143,15 @@ impl GenericCmyk { } pub fn new(params: GenericCmykParams) -> Self { + Self::build(params, None) + } + + /// The model of `params` with `correction` added to its media-relative Lab. + pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self { + Self::build(params, Some(correction)) + } + + fn build(params: GenericCmykParams, correction: Option) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) { @@ -149,7 +162,7 @@ impl GenericCmyk { let g = params.tvi50[i]; if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 } }); - let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() }; + let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() }; g.black_rel = g.to_xyz_rel(g.black_point_build()); g } @@ -218,6 +231,14 @@ impl GenericCmyk { /// Media-relative XYZ (paper = D50 white). pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] { + match &self.correction { + Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)), + None => self.neugebauer(cmyk), + } + } + + /// Media-relative XYZ of the Neugebauer model alone. + fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] { let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i])); let mut out = [0.0f32; 3]; for (i, p) in self.prim.iter().enumerate() { @@ -236,7 +257,14 @@ impl GenericCmyk { } pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab { - xyz_to_lab(self.to_xyz_rel(cmyk)) + let lab = xyz_to_lab(self.neugebauer(cmyk)); + match &self.correction { + Some(c) => { + let d = c.at(cmyk); + Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2]) + } + None => lab, + } } pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab { xyz_to_lab(self.to_xyz(cmyk)) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8fc287ae23..e83b0c1449 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option { Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())])) } +/// The copyright text of profiles made here: they carry no copyright claim. +pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely"; + /// Profiles made here carry their name and no copyright claim. -fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile { +fn labelled(p: ColorProfile, name: &str) -> ColorProfile { + with_copyright(p, name, NO_COPYRIGHT) +} + +fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile { p.description = text_tag(name); - p.copyright = text_tag("No copyright, use freely"); + p.copyright = text_tag(copyright); p } @@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9; /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK /// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which -/// the ICC-absolute colorimetric intent reproduces. +/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`. pub(super) fn cmyk_profile( name: &str, paper: [f32; 3], + copyright: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, mapped: impl Fn(lab::Lab) -> [f32; 4], colorimetric: impl Fn(lab::Lab) -> [f32; 4], @@ -520,7 +528,7 @@ pub(super) fn cmyk_profile( p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); - labelled(p, name) + with_copyright(p, name, copyright) } /// The grey space of greyscale exports: sRGB's tone curve, D50 white. diff --git a/crates/color/src/cms/measured.rs b/crates/color/src/cms/measured.rs new file mode 100644 index 0000000000..9394b69394 --- /dev/null +++ b/crates/color/src/cms/measured.rs @@ -0,0 +1,378 @@ +//! CMYK working spaces computed from published characterization data. +//! +//! Fogra publishes the measured colors of its reference printing conditions +//! () and allows the data to be +//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and +//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the +//! first time it is used: +//! +//! * The paper is the measured blank patch. The 15 solids and overprints of the +//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve +//! is fitted to its single-ink ramp. +//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed +//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The +//! smoothing carries the fit into regions the patch set does not sample, such as dark builds +//! with more than 60% black. +//! +//! The total ink limit and the black generation are VectorCraft's own values. + +use super::generic::{GenericCmyk, GenericCmykParams, swop_like}; +use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab}; + +/// A printing condition with published characterization data. +#[derive(Clone, Copy, Debug)] +pub struct Condition { + /// The working space's name. + pub name: &'static str, + /// The reference name of the characterization data, which a PDF/X output intent uses as + /// its `/OutputConditionIdentifier`. + pub reference: &'static str, + /// The characterization data file, as published. + pub data: &'static [u8], + /// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value. + pub tac: f32, +} + +/// The registry that the reference names of [`CONDITIONS`] belong to +/// (). +pub const REGISTRY: &str = "http://www.color.org"; + +/// The printing conditions VectorCraft computes working spaces for. +pub const CONDITIONS: [Condition; 2] = [ + Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 }, + Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 }, +]; + +/// The condition a working space of [`CONDITIONS`] is computed for. +pub fn condition(name: &str) -> Option<&'static Condition> { + CONDITIONS.iter().find(|c| c.name == name) +} + +/// One measured patch: nominal inks (0..1) and absolute Lab (D50). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Patch { + pub cmyk: [f32; 4], + pub lab: Lab, +} + +/// The most patches [`parse`] reads. +const MAX_PATCHES: usize = 20_000; + +/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`, +/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a +/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the +/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is +/// not the number of rows. +pub fn parse(data: &[u8]) -> Option> { + let text = std::str::from_utf8(data).ok()?; + let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| { + let mut words = l.split_whitespace(); + (words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"'))) + }); + let sets = match sets { + Some(n) => Some(n?.parse::().ok()?), + None => None, + }; + let mut lines = text.lines().map(str::trim); + lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?; + let mut fields = vec![]; + for line in lines.by_ref() { + if line == "END_DATA_FORMAT" { + break; + } + fields.extend(line.split_whitespace()); + } + let at = |f: &str| fields.iter().position(|x| *x == f); + let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?]; + lines.by_ref().find(|l| *l == "BEGIN_DATA")?; + let mut out = vec![]; + let mut ended = false; + for line in lines { + if line == "END_DATA" { + ended = true; + break; + } + if line.is_empty() { + continue; + } + if out.len() >= MAX_PATCHES { + return None; + } + let row: Vec<&str> = line.split_whitespace().collect(); + let mut v = [0f32; 7]; + for (slot, &col) in v.iter_mut().zip(&cols) { + *slot = row.get(col)?.parse::().ok().filter(|x| x.is_finite())?; + } + if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) { + return None; + } + out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) }); + } + (ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out) +} + +/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white). +fn relative(lab: Lab, paper: [f32; 3]) -> Lab { + let x = lab_to_xyz(lab); + xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i])) +} + +/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ. +fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option { + let mut sum = [0f32; 3]; + let mut n = 0; + for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) { + let x = lab_to_xyz(p.lab); + for i in 0..3 { + sum[i] += x[i]; + } + n += 1; + } + (n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32))) +} + +/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the +/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the +/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area +/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most +/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ). +fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> { + let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?; + let span = D50[ch] - solid[ch]; + if span.abs() < 1e-4 { + return None; + } + let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64); + for p in patches { + let a = p.cmyk[ink]; + let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0); + if !alone || a <= 0.0 || a >= 1.0 { + continue; + } + let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span; + let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0))); + let d = f64::from(e - a); + s11 += b1 * b1; + s12 += b1 * b2; + s22 += b2 * b2; + r1 += b1 * d; + r2 += b2 * d; + } + let det = s11 * s22 - s12 * s12; + if det.abs() < 1e-12 { + return None; + } + let u = ((r1 * s22 - r2 * s12) / det) as f32; + let v = ((s11 * r2 - s12 * r1) / det) as f32; + let tvi50 = u.clamp(0.0, 0.45); + let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45); + Some((tvi50, tvi40)) +} + +/// Absolute Lab → media-relative XYZ. +fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] { + let x = lab_to_xyz(lab); + [0, 1, 2].map(|i| x[i] * D50[i] / paper[i]) +} + +/// The press model of `condition`, computed from its data. `None` when the data does not parse, +/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not +/// positive and finite. +pub fn model(condition: &Condition) -> Option { + fit(condition, &parse(condition.data)?, SMOOTHING) +} + +/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in +/// the cases [`model`] lists). +pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option { + let paper = mean_lab(patches, [0.0; 4])?; + let paper_xyz = lab_to_xyz(paper); + if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) { + return None; + } + let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15]; + for (i, slot) in primaries.iter_mut().enumerate() { + let bits = i + 1; + let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 }); + *slot = relative(mean_lab(patches, inks)?, paper_xyz); + } + let mut tvi50 = [0f32; 4]; + let mut tvi40 = [0f32; 4]; + for ink in 0..4 { + let solid = lab_to_xyz(primaries[(1 << ink) - 1]); + (tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?; + } + let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg }; + let base = GenericCmyk::new(params.clone()); + let points: Vec<([f32; 4], [f32; 3])> = patches + .iter() + .map(|p| { + let want = relative(p.lab, paper_xyz); + let got = base.to_lab_rel(p.cmyk); + (p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b]) + }) + .collect(); + Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing))) +} + +/// Weight of the lattice's smoothness against its fit to the patches. +pub(crate) const SMOOTHING: f64 = 0.02; + +/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps. +const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0]; +const N: usize = KNOTS.len(); +const NODES: usize = N * N * N * N; + +/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`]. +#[derive(Clone, Debug)] +pub struct Lattice { + values: Vec<[f32; 3]>, +} + +/// The cell of `v` along an axis and its position in it. +fn locate(v: f32) -> (usize, f32) { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2); + let (lo, hi) = (KNOTS[i], KNOTS[i + 1]); + (i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0)) +} + +/// The 16 nodes around `cmyk` with their interpolation weights. +fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] { + let cells = cmyk.map(locate); + let mut out = [(0, 0.0); 16]; + for (corner, slot) in out.iter_mut().enumerate() { + let mut index = 0; + let mut w = 1.0; + for (axis, (cell, t)) in cells.iter().enumerate() { + let up = corner & (1 << axis) != 0; + index = index * N + cell + usize::from(up); + w *= if up { *t } else { 1.0 - t }; + } + *slot = (index, w); + } + out +} + +/// Index strides of the four axes (C is the slowest). +const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1]; + +impl Lattice { + /// The correction at `cmyk`. + pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] { + let mut out = [0f32; 3]; + for (i, w) in corners(cmyk) { + if w == 0.0 { + continue; + } + let v = self.values.get(i).copied().unwrap_or_default(); + for c in 0..3 { + out[c] += w * v[c]; + } + } + out + } + + /// The lattice that best fits `points` (inks, correction) in the least-squares sense, with + /// `smoothing` times the squared second differences of the nodes along each axis added to the + /// error. The node at no ink stays 0, so the paper keeps the model's color (white, media- + /// relative). Solved by conjugate gradients, one Lab channel at a time. + pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice { + let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect(); + // The divided second difference at interior knot j, scaled to a unit spacing of 1/8. + let curvature: Vec<[f64; 3]> = (1..N - 1) + .map(|j| { + let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j])); + let s = 0.125f64 * 0.125; + [2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s] + }) + .collect(); + let apply = |x: &[f64], out: &mut [f64]| { + out.fill(0.0); + for w in &weights { + let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, w) in w { + if let Some(o) = out.get_mut(*i) { + *o += f64::from(*w) * v; + } + } + } + for node in 0..NODES { + let mut rest = node; + for stride in STRIDES { + let j = rest / stride; + rest %= stride; + // Only interior knots (1 to N − 2) have a second difference. + let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue }; + let idx = [node - stride, node, node + stride]; + let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, c) in idx.iter().zip(c) { + if let Some(o) = out.get_mut(*i) { + *o += smoothing * c * d; + } + } + } + } + for (o, v) in out.iter_mut().zip(x) { + *o += 1e-9 * v; + } + // The paper's node is held: with its right-hand side 0 it stays 0 in every iterate. + if let (Some(o), Some(v)) = (out.first_mut(), x.first()) { + *o = *v; + } + }; + let mut values = vec![[0f32; 3]; NODES]; + for ch in 0..3 { + let mut b = vec![0f64; NODES]; + for (w, (_, r)) in weights.iter().zip(points) { + for (i, w) in w { + if let Some(o) = b.get_mut(*i) { + *o += f64::from(*w) * f64::from(r[ch]); + } + } + } + if let Some(o) = b.first_mut() { + *o = 0.0; + } + let x = conjugate_gradients(&apply, &b, 4000); + for (v, x) in values.iter_mut().zip(&x) { + v[ch] = *x as f32; + } + } + Lattice { values } + } +} + +/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by. +fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec { + let n = b.len(); + let mut x = vec![0f64; n]; + let mut r = b.to_vec(); + let mut p = r.clone(); + let mut ap = vec![0f64; n]; + let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::(); + let mut rr = dot(&r, &r); + let stop = rr * 1e-20; + for _ in 0..max_iterations { + if rr <= stop || rr == 0.0 { + break; + } + apply(&p, &mut ap); + let pap = dot(&p, &ap); + if pap <= 0.0 || !pap.is_finite() { + break; + } + let alpha = rr / pap; + for i in 0..n { + x[i] += alpha * p[i]; + r[i] -= alpha * ap[i]; + } + let next = dot(&r, &r); + let beta = next / rr; + rr = next; + for i in 0..n { + p[i] = r[i] + beta * p[i]; + } + } + x +} diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs new file mode 100644 index 0000000000..7bf5735c7a --- /dev/null +++ b/crates/color/src/cms/tests_measured.rs @@ -0,0 +1,250 @@ +use super::*; +use sha2::{Digest, Sha256}; + +fn hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The data files ship exactly as Fogra publishes them in +/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip. +#[test] +fn characterization_data_is_the_published_files() { + let want = [ + ("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111), + ("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781), + ]; + for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) { + assert_eq!(c.reference, reference); + assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}"); + } +} + +#[test] +fn the_data_parses_into_its_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + assert_eq!(patches.len(), 1617, "{}", c.reference); + assert_eq!(patches[0].cmyk, [0.0; 4]); + } + let p = measured::parse(measured::CONDITIONS[0].data).unwrap(); + assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0)); + assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]); + assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42)); +} + +#[test] +fn malformed_data_is_refused() { + let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n"); + let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B"; + let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"); + assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2)); + for bad in [ + file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"), + file(fields, "1 0 0 0 0 95 1"), + file(fields, "1 0 0 0 0 95 NaN -6"), + file(fields, "1 0 0 0 0 95 x -6"), + file(fields, "1 0 0 0 101 95 1 -6"), + file(fields, "1 -1 0 0 0 95 1 -6"), + file(fields, ""), + "BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(), + ] { + assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}"); + } + assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None); + // The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them. + let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"; + let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n"); + assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA"); + for (sets, len) in [ + ("NUMBER_OF_SETS\t2", Some(2)), + ("NUMBER_OF_SETS\t3", None), + ("NUMBER_OF_SETS\t1", None), + ("NUMBER_OF_SETS\tx", None), + ("NUMBER_OF_SETS", None), + ] { + assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}"); + } +} + +/// A paper measured as black has no XYZ to make the other patches relative to. +#[test] +fn a_paper_without_light_is_refused() { + let c = &measured::CONDITIONS[0]; + let mut patches = measured::parse(c.data).unwrap(); + for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) { + p.lab = Lab::new(0.0, 0.0, 0.0); + } + assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none()); +} + +/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max). +fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) { + let errors: Vec = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect(); + (errors.iter().sum::() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max)) +} + +#[test] +fn the_working_spaces_reproduce_the_measured_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let start = std::time::Instant::now(); + let g = measured::model(c).unwrap(); + let took = start.elapsed(); + let (mean, max) = accuracy(&g, &patches); + println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference); + assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference); + // The paper is the measured blank patch. + assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05); + } +} + +/// A model fitted without every fourth patch (the paper and the solids and overprints stay in) +/// predicts the patches it left out. The data repeats some builds, and every row of a build is +/// on the side of the build's first row, so the fit never sees a left-out build. +#[test] +fn the_fit_predicts_patches_it_left_out() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); + let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0); + let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p)); + assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); + let kept: Vec = kept.into_iter().copied().collect(); + let left: Vec = left.into_iter().copied().collect(); + let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap(); + let (mean, max) = accuracy(&g, &left); + println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len()); + assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference); + } +} + +/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches +/// (black above 60%, and builds over the ink limit). +#[test] +fn more_ink_lightens_a_build_by_less_than_0_3_l() { + let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); + let coarse = [0.0, 0.25, 0.5, 0.75, 1.0]; + for c in &measured::CONDITIONS { + let g = measured::model(c).unwrap(); + let mut worst = 0f32; + for ink in 0..4 { + for a in coarse { + for b in coarse { + for d in coarse { + let mut others = [a, b, d].into_iter(); + let mut build = [0f32; 4]; + for (i, slot) in build.iter_mut().enumerate() { + if i != ink { + *slot = others.next().unwrap(); + } + } + let mut last = f32::INFINITY; + for &v in &steps { + build[ink] = v; + let l = g.to_lab_rel(build).l; + worst = worst.max(l - last); + last = l; + } + } + } + } + } + println!("{}: largest L* rise with more ink {worst:.3}", c.reference); + assert!(worst < 0.3, "{}: {worst}", c.reference); + } +} + +#[test] +fn the_working_spaces_follow_generic_cmyk_in_the_list() { + let cmyk: Vec = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect(); + assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]); + assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK); + assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org"))); + assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org"))); + assert_eq!(characterization(GENERIC_CMYK), None); + assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_)))); +} + +#[test] +fn colors_separate_and_come_back_in_the_measured_spaces() { + for name in [FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + // A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure + // L* 11.43 and 26.36), so it comes back whatever the gamut check says. + let gray = [0.5, 0.5, 0.5]; + for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] { + let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric); + assert!(inks.iter().sum::() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}"); + if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD { + let back = cms.cmyk_to_srgb(inks, false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back)); + assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})"); + } + } + // White is paper with no ink, and black is the darkest build within the ink limit. + assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]); + let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + assert!(black[3] > 0.8 && black.iter().sum::() <= 3.0 + 1e-3, "{name}: {black:?}"); + } + // The coated paper prints a larger gamut than the uncoated one. + let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 }; + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap(); + assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue)); +} + +/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces. +fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab { + match &cms.cmyk { + CmykSpace::Generic(g) => g.to_lab_abs(cmyk), + CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"), + } +} + +#[test] +fn absolute_cmyk_to_rgb_shows_the_paper() { + for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric); + assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}"); + assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}"); + } +} + +#[test] +fn absolute_cmyk_conversion_keeps_the_source_paper() { + // Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6), + // so printing it on FOGRA51 paper takes ink. + let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric) + else { + panic!("a CMYK colour converts to CMYK"); + }; + let inks = [c, m, y, k]; + assert!(inks.iter().sum::() > 0.01, "{inks:?}"); + let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4])); + assert!(de < 2.0, "{inks:?}: ΔE {de}"); +} + +#[test] +fn the_profiles_carry_the_paper_and_the_data_source() { + for c in &measured::CONDITIONS { + let start = std::time::Instant::now(); + let bytes = icc_bytes(c.name).unwrap(); + println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed()); + let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap(); + assert_eq!( + (p.profile_class, p.color_space, p.pcs), + (moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab) + ); + assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some()); + let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab); + let white = p.media_white_point.unwrap(); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference); + } + let text = format!("{:?}", p.copyright); + assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}"); + } +} diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index ca8db5ae30..adf4e9ee47 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4; pub const POWERLESS_CHROMA: f64 = 0.000_004; /// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. -const GAMUT_SLACK: f64 = 1e-4; +const GAMUT_SLACK: f64 = 1e-5; /// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they /// are. The hue is in 0..360, and 0 while the chroma is powerless. @@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 { /// /// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of /// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, -/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic /// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The /// search finds each such chroma between the cubic's turning points and takes the largest one that /// fits. @@ -112,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec { /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: /// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that -/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and +/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as +/// lowered. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; + if l == 0.0 || l == 1.0 { + return ([l as f32; 3], c > 0.0); + } let exact = oklch_to_srgb(l, c, h); let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) @@ -239,12 +244,10 @@ mod tests { } /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at - /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from - /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + /// every hue and at lightnesses near black too. #[test] fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); - assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { let max = max_chroma(l, h); @@ -262,4 +265,26 @@ mod tests { assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); } + + /// The lightness endpoints give exactly black and white at any chroma and hue, and report a + /// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel. + #[test] + fn the_lightness_endpoints_give_exact_black_and_white() { + assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true)); + assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false)); + assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true)); + assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false)); + } + + /// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that + /// fits, not clipped at its own chroma. + #[test] + fn a_channel_just_below_zero_is_outside_the_gamut() { + assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0))); + let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0); + assert!(lowered, "{rgb:?}"); + let [_, c, _] = to_oklch(rgb); + assert!(c < 0.01, "{c}"); + assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0))); + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5c52b167a1..dfe6e22e73 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3519986512..a1bfaefe7d 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); + b += e.attrs.as_deref().map_or(0, attrs_bytes); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e .color_mask @@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize { ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } +/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and +/// tags. +fn attrs_bytes(a: &crate::ObjectAttributes) -> usize { + let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::(); + a.url.capacity() + + a.note.capacity() + + pairs(&a.data) + + pairs(&a.events) + + vec_bytes(&a.classes) + + a.classes.iter().map(String::capacity).sum::() + + vec_bytes(&a.foreign) + + a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::() + + vec_bytes(&a.tags) + + a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::() +} + /// A vector's buffer (not what its elements own). fn vec_bytes(v: &Vec) -> usize { if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::() } @@ -490,6 +507,21 @@ mod tests { assert!((400..1200).contains(&per), "{per} bytes per moved rectangle"); } + /// An object's attributes count with their text: a version of a rectangle with a long tag and + /// a long note keeps both. + #[test] + fn tags_and_notes_count() { + let before = doc_with_rects(1); + let mut after = before.clone(); + let id = after.layers[0].children().unwrap()[0].id; + after.node_mut(id).unwrap().edit_attrs(|a| { + a.note = "n".repeat(30_000); + a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) }); + }); + let bytes = after.retained_bytes(&before); + assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes"); + } + #[test] fn a_grouped_object_is_found_shared() { let before = doc_with_rects(100); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 79ce594212..87b9a375db 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -24,7 +24,7 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 6f573a61aa..67d3d02308 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -38,6 +38,141 @@ pub struct ObjectAttributes { /// with it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub foreign: Vec, + /// The object's tags, in order: name and value pairs that scripts read and write + /// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and + /// value at most [`MAX_TAG_TEXT`] bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, +} + +/// The most tags one object has. +pub const MAX_TAGS: usize = 64; + +/// The longest name or value a tag has, in bytes. +pub const MAX_TAG_TEXT: usize = 64 * 1024; + +/// A tag on an object: a name and a value, with an id that tells it apart from the object's other +/// tags while its name and value change. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObjectTag { + /// Distinct among the object's tags: a new tag takes an id from + /// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id, + /// so a deleted tag's id is not given out again. + #[serde(default, deserialize_with = "lenient_tag_id")] + pub id: u64, + #[serde(default)] + pub name: String, + #[serde(default)] + pub value: String, +} + +/// Reading a native file never fails over a tag id that is not a whole number from 0 to +/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and +/// [`crate::Document::tidy_tags`] gives the tag a new id. +fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0)) +} + +impl ObjectAttributes { + /// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most + /// [`MAX_TAG_TEXT`] bytes. → whether any was dropped. + pub fn tidy_tags(&mut self) -> bool { + let before = self.tags.len(); + self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT); + self.tags.truncate(MAX_TAGS); + self.tags.len() != before + } +} + +impl crate::Document { + /// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of + /// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag + /// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier + /// tag of the object has it. Every other tag gets a new id: from the next node id on, above + /// every kept id, when those ids stay below that limit; otherwise the smallest id the object's + /// other tags do not have. The next node id is then raised past every tag id below the limit. + /// It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn tidy_tags(&mut self) { + fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool { + (1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id) + } + // The limits, the largest kept id and the number of new ids first, so that a new id never + // meets a kept one. + let mut next = self.peek_next_id(); + let mut fresh = 0u64; + self.each_tagged(&mut |a| { + a.tidy_tags(); + for (i, t) in a.tags.iter().enumerate() { + if keeps(t, &a.tags[..i]) { + next = next.max(t.id.saturating_add(1)); + } else { + fresh = fresh.saturating_add(1); + } + } + }); + if fresh == 0 { + self.raise_next_id(next); + return; + } + let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID; + self.each_tagged(&mut |a| { + let kept: Vec = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect(); + let mut used: Vec = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect(); + for (i, k) in kept.iter().enumerate() { + if *k { + continue; + } + let id = if in_range { + next = next.saturating_add(1); + next - 1 + } else { + (1..).find(|c| !used.contains(c)).unwrap_or(1) + }; + a.tags[i].id = id; + used.push(id); + } + }); + self.raise_next_id(next); + } + + /// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the + /// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the + /// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an + /// id below it could be a deleted tag's. + pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option { + let used: Vec = + self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default(); + for _ in 0..=used.len() { + if self.peek_next_id() >= crate::limits::MAX_NEXT_ID { + return None; + } + let tag = self.alloc_id().0; + if !used.contains(&tag) { + return Some(tag); + } + } + None + } + + /// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads. + fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) { + let mut fix = |n: &mut Node| { + if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) { + n.edit_attrs(&mut *f); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + } } /// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter= diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 071d3c3b64..02cf4b6205 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } +/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in +/// effects). +pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { + catalog_index().get(id).map(|e| (e.id, e.label)) +} + /// Catalogue entry for `id` (built-in, or an installed plug-in effect). pub fn effect_info(id: &str) -> Option { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 555610f206..216e541caf 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -125,7 +125,9 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; +pub use catalog::{ + EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range, +}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{ Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with, diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 74a10d337f..587f60eb11 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -102,6 +102,7 @@ pub mod swatchlib; pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; +pub(crate) mod tags; mod textedit; pub use textedit::effective_kerning; @@ -376,6 +377,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(library::specs()); v.extend(expand::specs()); v.extend(attributes::specs()); + v.extend(tags::specs()); v.extend(interactivity::specs()); v.extend(spelling::specs()); v.extend(svgfilter::specs()); @@ -845,7 +847,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{fold_source, print_hidden}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; /// Document Info's category titles, the Objects category's count labels, and how its image rows /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; @@ -924,6 +926,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; +/// Retype's search of the installed fonts, made off the UI thread. +pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; + /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{fold_source, print_hidden}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8bf1e00d16..c12eb2fa64 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); let swatches = |name: &str| kinds.get(name).copied(); - recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) + s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))) } /// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -2,13 +2,16 @@ //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each //! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold -//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu -//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set +//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins › +//! Packaging Tools) and its Fold Lines panel are the UI's. +mod angle; mod check; mod fold; mod roles; +pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -17,6 +20,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..f38645774f --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -0,0 +1,266 @@ +//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease, +//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of +//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a +//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side. + +use std::collections::HashSet; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::kept_angle; + +use super::super::super::edit::refuse_symbol_part; +use super::super::super::overprint::edit_counted; +use super::super::super::pathops::number_given; +use super::super::super::{CommandSpec, bad, cmd, switch_or}; +use super::check::kind; +use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots}; +use crate::{Result, Session}; + +/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export +/// leaves `vc-` keys out. +pub(crate) const KEY: &str = "vc-fold-angle"; + +const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The range a fold angle may take, in degrees. +const RANGE: std::ops::RangeInclusive = -180.0..=180.0; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.setFoldAngle", + "Set Fold Angle…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}", + has_fold_line, + set_fold_angle + )] +} + +/// Why Set Fold Angle has nothing to change. +const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + +/// The last answer of [`has_fold_line`], with what it was for. +struct Answer { + /// The document (a weak reference keeps another document from taking the same address). + doc: Weak, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + found: bool, +} + +thread_local! { + /// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the + /// document, its revision and the objects looked at. + static LAST_ANSWER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object. +fn has_fold_line(s: &Session) -> std::result::Result<(), String> { + refuse_symbol_part(s).map_err(|e| e.to_string())?; + let st = s.doc().map_err(|e| e.to_string())?; + let objects = &st.selection.objects; + let kept = LAST_ANSWER.with_borrow(|last| match last { + Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found), + _ => None, + }); + let found = kept.unwrap_or_else(|| { + // An id of no object (given as `ids`) is left to the command, which names it. + let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects); + LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found })); + found + }); + if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) } +} + +/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through +/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`] +/// takes them, an object inside another one given is left out (a crease in a selected layer counts +/// no more than the layer does), a layer is left out, and a path of a compound path stands for the +/// compound path, which holds its role, unless it is locked or hidden. +fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool { + fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool { + match &n.kind { + // A group's clipping path draws no stroke. + NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)), + _ => hit(n), + } + } + let table = RoleTable::of(d); + let editable = d.editable(); + let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id); + let given: HashSet = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + let a = d.ancestry(id)?; + let (_, up) = a.split_last()?; + if up.iter().any(|p| given.contains(p)) { + return None; + } + match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) { + // A locked or hidden path of a compound path is left out, as `editable_members` leaves it. + Some(_) if !editable(id) => None, + Some(compound) => Some(compound), + None => Some(id), + } + }; + // An object given twice is looked through once. + let mut seen = HashSet::new(); + roots + .iter() + .filter_map(|id| outer(*id)) + .filter(|id| seen.insert(*id)) + .filter_map(|id| d.node(id)) + .filter(|n| !n.is_layer()) + .any(|n| find(n, &hit)) +} + +/// The text `n`'s data holds under [`KEY`], if any. +fn stored(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from +/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as +/// no angle of its own. +pub(super) fn own_angle(n: &Node) -> Option { + stored(n)?.trim().parse::().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle) +} + +/// Whether a line with `role` folds: every role but Cut. +pub(super) fn folds(role: Role) -> bool { + kind(role).fold_angle().is_some() +} + +/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed. +fn store(d: &mut Document, id: NodeId, angle: Option) -> bool { + // `+ 0.0` turns -0 into 0, so a line set to 0° reads "0". + let text = angle.map(|a| format!("{}", a + 0.0)); + // Read first: taking the node to change it copies it, its geometry included. An angle stored + // as other text for the same number ("45.0") is kept; a reset removes any stored text. + let same = |n: &Node| match angle { + Some(a) => own_angle(n) == Some(a), + None => stored(n).is_none(), + }; + if d.node(id).is_none_or(same) { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.edit_attrs(|a| match text { + Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = text, + None => a.data.push((KEY.into(), text)), + }, + None => a.data.retain(|(k, _)| k != KEY), + }); + true +} + +fn set_fold_angle(s: &mut Session, p: &Value) -> Result { + let angle = number_given(p, "angle", SET_FOLD_ANGLE)?; + let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?; + let angle = match (angle, reset) { + (Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")), + (None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")), + (Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")), + // Kept to the millionth of a degree, the angle the line folds at. + (a, _) => a.map(kept_angle), + }; + let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?; + let d = &s.doc()?.doc; + let (targets, skipped) = role_targets(d, &roots, false); + let mut skipped = skipped + named; + let mut ids = folding(d, &RoleTable::of(d), &targets); + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + skipped += targets.len() - ids.len(); + if ids.is_empty() { + return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE)); + } + let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" }; + let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order. +fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect() +} + +/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip +/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FoldAngles { + /// How many lines that fold it can change. + pub lines: usize, + /// The angle they all fold at (their own or their role's); `None` when they differ or there + /// are none. + pub angle: Option, + /// How many of them have an angle of their own. + pub own: usize, + /// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away. + pub stored: usize, +} + +/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them +/// with no `ids` (nothing, while it would refuse the selection). +pub fn selection_fold_angles(s: &Session) -> FoldAngles { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots), + _ => FoldAngles::default(), + } +} + +/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes +/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the +/// lines it changes. +pub fn selection_fold_lines(s: &Session) -> Vec { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(), + _ => Vec::new(), + } +} + +/// The [`FoldAngles`] of the outermost objects `roots` of `d`. +pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { + let mut f = FoldAngles::default(); + for (n, role) in changeable(d, roots) { + f.add(n, role); + } + f +} + +/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change, +/// with their roles, in order. +fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> { + let table = RoleTable::of(d); + let editable = d.editable(); + let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0; + // The role first: whether an object can be edited can take its bounds to find out. + targets + .iter() + .filter_map(|id| d.node(*id)) + .filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r))) + .collect() +} + +impl FoldAngles { + /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. + pub(super) fn add(&mut self, n: &Node, role: Role) { + let Some(default) = kind(role).fold_angle() else { return }; + let own = own_angle(n); + let a = own.unwrap_or(default); + self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) }; + self.lines += 1; + self.own += usize::from(own.is_some()); + self.stored += usize::from(stored(n).is_some()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -0,0 +1,409 @@ +//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it. + +use serde_json::{Value, json}; + +use super::{KEY, fold_angles, own_angle}; +use crate::*; + +const SET: &str = "addon.packaging.setFoldAngle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(SET, &p).unwrap_err().to_string() +} + +/// The text object `id`'s data holds under the fold angle key. +fn stored(s: &Session, id: u64) -> Option { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone())) +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases: top, right, bottom, left). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of +/// its outline's points (absolute moves and lines only) is above the base. +fn top_wall(p: &Value) -> bool { + let d = p["outline"].as_str().unwrap(); + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + (ys.0 + ys.1) / 2.0 < 140.0 +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +#[test] +fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + assert_eq!(steps(&s), before + 1, "one undo step"); + // The same angle again changes nothing and records no undo step. + let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // An angle is kept to the millionth of a degree, so one closer to 45 than that is 45. + let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}"); + s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap(); + assert_eq!(stored(&s, creases[3]).as_deref(), Some("180")); + s.execute("edit.undo", &json!({})).unwrap(); + // A number as text, and the selection when ids is left out; -0 is kept as 0. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + let r = s.execute(SET, &json!({"angle": "-0"})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "{r}"); + assert_eq!(stored(&s, creases[1]).as_deref(), Some("0")); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}"); + assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None)); + // Nothing left to reset: no undo step. + let at = steps(&s); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at)); + // Undo brings the angle back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); +} + +#[test] +fn bad_angles_and_targets_are_refused() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let plain = path(&mut s, "M10 10 L50 50"); + let before = steps(&s); + let ids = json!([creases[0]]); + assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`")); + assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both")); + assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false")); + // A cut line and a path without a role do not fold. + assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation")); + // An id of no object is named as such, alone or beside a crease. + assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999")); + assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); + // The ends of the range are allowed; cut lines and plain paths among fold lines are skipped. + let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}"); + s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("180")); + assert_eq!(stored(&s, outline), None); +} + +#[test] +fn set_fold_angle_is_dimmed_without_a_line_it_can_change() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok(); + assert!(!enabled(&s), "nothing selected"); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!(!enabled(&s), "a cut line does not fold"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap(); + assert!(enabled(&s)); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed"); + // A group holding a crease is enough. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + assert!(enabled(&s)); + // A layer selected with a crease in it: the crease is inside the layer, which is left out, as + // Set Fold Angle itself leaves them out. + let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap(); + s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert!(!enabled(&s), "dimmed as the command refuses it"); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); + // With nothing selected the counts are the document's, but Set Fold Angle takes no line. + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute(SET, &json!({"angle": 30})).is_err()); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!(r["scope"].as_str(), Some("document"), "{r}"); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}"); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); +} + +#[test] +fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold"); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(1), "{r}"); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line"); +} + +#[test] +fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap(); + let f = crate::cmd::selection_fold_angles(&s); + assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}"); +} + +#[test] +fn a_locked_crease_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(stored(&s, creases[1]), None); +} + +#[test] +fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320")); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + role(&mut s, "crease", &[compound]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(NodeId(a)) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation")); + // Named twice, it is skipped once. + let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, compound), None); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + assert_eq!(stored(&s, compound), None); + // With its compound, given or selected, the locked path is part of the compound, not skipped. + let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute("select.set", &json!({"ids": [compound, a]})).unwrap(); + let r = s.execute(SET, &json!({"angle": 25})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap(); + // The compound named by id takes the angle; its other path, not locked, names it too. + let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap(); + assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}"); + assert_eq!(stored(&s, compound).as_deref(), Some("30")); +} + +#[test] +fn a_damaged_angle_reads_as_none_of_its_own() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap(); + for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] { + n.edit_attrs(|a| { + a.data.retain(|(k, _)| k != KEY); + a.data.push((KEY.into(), text.into())); + }); + assert_eq!(own_angle(&n), want, "{text:?}"); + } +} + +#[test] +fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let id = NodeId(creases[0]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into()))); + } + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0")); + s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]), None); + // A reset also removes text that is not an angle. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}"); +} + +#[test] +fn a_line_keeps_its_own_angle_through_a_role_change() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + role(&mut s, "partialCut", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); + role(&mut s, "none", &[creases[0]]); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + role(&mut s, "crease", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); +} + +#[test] +fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned()); + assert!(svg.contains(" = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + assert!(angles.contains(&120.0), "{r}"); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // The top wall (y 100 to 140) folds at 45°. + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut angles: Vec = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + angles.sort_by(f64::total_cmp); + assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]); + for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) { + let z = vector(&p["frame"]["z"]); + let top = top_wall(p); + let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}"); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut up = 0; + for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) { + // The top wall folds toward the print, so its printed side faces back over the base + // (toward -y in the y-up frame); the other walls stand square to the base as before. + let top = top_wall(p); + let z = vector(&p["frame"]["z"]); + if top { + assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}"); + up += 1; + } else { + assert!(z[2].abs() < 1e-9, "{p}"); + } + } + assert_eq!(up, 1); +} + +#[test] +fn roles_reports_the_angle_the_selected_fold_lines_share() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}"); + s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap(); + assert!(r["foldAngle"].is_null(), "{r}"); + // A partial cut folds at -90° unless it has an angle of its own. + role(&mut s, "partialCut", &[creases[2]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}"); +} + +#[test] +fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap(); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}"); + assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}"); + // So Reset has nothing to change, as the panel shows it. + let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + let (lines, angle, own) = { + let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]); + (f.lines, f.angle, f.own) + }; + assert_eq!((lines, angle, own), (1, Some(90.0), 0)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::angle::own_angle; use super::roles::{Role, RoleTable, can_carry, role_targets}; use crate::{Result, Session}; @@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) } -fn kind(role: Role) -> LineKind { +/// The kind of fold line a line with `role` is. +pub(super) fn kind(role: Role) -> LineKind { match role { Role::Cut => LineKind::Cut, Role::Crease => LineKind::Crease, @@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) }); } Lines { scope, lines, non_printing } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..3543591944 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fold", [], None, - "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", has_doc, fold_command )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use super::super::super::edit::{outermost, refuse_symbol_part, roots_of}; use super::super::super::overprint::edit_counted; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{Result, Session}; @@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool { } } +/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of +/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that +/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out +/// before it stands for its compound, and how many such paths were left out, each once. +pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec, usize)> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + let roots = checked_ids_or_selection(s, p, command)?; + return Ok(editable_members(&s.doc()?.doc, roots)); + } + refuse_symbol_part(s)?; + let st = s.doc()?; + // An object inside another selected one is left out first, as it is from `ids`. + let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc))); + Ok((roots_of(&st.doc, kept), left)) +} + +/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or +/// hidden group or layer, or on a locked artboard), and how many different ones were left out. +pub(super) fn editable_members(d: &Document, ids: Vec) -> (Vec, usize) { + let ok = d.editable(); + let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let mut left = std::collections::HashSet::new(); + let kept = ids + .into_iter() + .filter(|id| { + let out = member(*id) && !ok(*id); + if out { + left.insert(*id); + } + !out + }) + .collect(); + (kept, left.len()) +} + /// The objects under the outermost objects `roots` that can carry a role, through groups and clip /// groups, each once, and /// how many of `roots` and their members can't (text, images, symbol instances and other objects). @@ -257,7 +293,7 @@ pub fn specs() -> Vec { "Make Fold Line", ["Object", "Plug-ins", "Packaging Tools"], None, - "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", has_selection, set_role ), @@ -266,7 +302,7 @@ pub fn specs() -> Vec { "Fold Lines", [], None, - "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes", has_doc, roles ), @@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai fn set_role(s: &mut Session, p: &Value) -> Result { let role = role_param(p, SET_ROLE, true)?; let overprint = switch_or(p, "overprint", true, SET_ROLE)?; - let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (roots, left) = taken_roots(s, p, SET_ROLE)?; let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + let skipped = skipped + left; if ids.is_empty() { return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); } @@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result { fn roles(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, ROLES)?; - let d = &s.doc()?.doc; + // The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand + // for its compound there. They are the objects the counts are of unless such a path was left + // out, and only then are those found apart. + let (taken, left) = taken_roots(s, p, ROLES)?; + let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) }; + let st = s.doc()?; + let d = &st.doc; let (scope, ids) = match (given, roots.is_empty()) { (true, _) => ("ids", role_targets(d, &roots, false).0), (false, false) => ("selection", role_targets(d, &roots, false).0), (false, true) => ("document", document_targets(d)), }; + let whole = scope == "document"; + // The lines Set Fold Angle can change are those of the objects it takes: with nothing selected, + // or a selection that holds no such object (only a layer and what is in it), it takes none, + // though the counts are the document's. + let angles_of_all = given || !roots.is_empty(); let table = RoleTable::of(d); let mut counts = [0usize; 4]; - for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + let editable = d.editable(); + let mut angles = super::angle::FoldAngles::default(); + for n in ids.iter().filter_map(|id| d.node(*id)) { + let Some(r) = table.role_of(n) else { continue }; if let Some(c) = counts.get_mut(r.index()) { *c += 1; } + if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) { + angles.add(n, r); + } + } + if !whole && left > 0 { + angles = super::angle::fold_angles(d, &angle_roots); } let rows: Vec = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) }) .collect(); - Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) + Ok(json!({ + "roles": rows, "scope": scope, "selected": roots.len(), + "foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored, + })) } fn set_role_swatch(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() { let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // A locked member named by id is skipped, and its compound keeps its role. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(a) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden")); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden")); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // Named twice, it is skipped once. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}"); } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index d0c5447c42..14a462d79f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -20,7 +20,7 @@ use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; -use super::super::typecmd::refresh_bounds; +use super::super::typecmd::{refresh_bounds, refresh_with_given_leading}; use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; t.runs = tweak(std::mem::take(&mut t.runs), changes); - refresh_bounds(t); + // With Block on, the first changed character's leading goes to the frame's line gap. + match changes.first().filter(|_| key == "leading") { + Some(&(at, _)) => refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c6c1da2980..610498f56a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", + "{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), @@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); // The swatches as the paste brings them: converted from another profile when it converts. - let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + const CMD: &str = "clipboard.conflicts"; + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 42ee145c94..0d25a6e57a 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 9e28b5805c..7a4a4dea07 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Curvature Circle", [], None, - "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + "{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", has_doc, curvature_circle ), @@ -548,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result>> { } /// A live ellipse that touches a path at a point with the path's curvature there -/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor +/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is. fn curvature_circle(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.curvatureCircle"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -559,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`t` must be from 0 to 1")); } let convex = switch_or(p, "convex", false, C)?; + let arcs = switch_or(p, "constantRadius", true, C)?; + let key = "anchors"; + let at_touch = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("touch")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))), + }; let found = { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -570,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { if seg >= sp.segment_count() { return Err(bad(C, "no such segment")); } - curvature::curvature_circle_on(sp, seg, t, convex) + curvature::curvature_circle_on_with(sp, seg, t, convex, arcs) }; let circle = found.map_err(|e| match e { NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), @@ -579,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { })?; let (center, radius) = (circle.center, circle.radius); let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + let (path, live) = if at_touch { + (shapes::circle_with_anchors_at(center, radius, &[circle.at]), None) + } else { + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + (live.to_path(), Some(live)) + }; + // The bounds of the path drawn: started where it touches, its cubics reach a little past the + // circle. + if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) { return Err(bad(C, "the circle that matches the path there would reach past the canvas")); } - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays on the path. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 33455ea9d9..3922a8e1f0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -809,6 +809,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); @@ -845,6 +846,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 25d7d38321..cc5c19adea 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -514,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { - let gid = s.edit(&label, |d, sel| { - let gid = super::object::group_nodes(d, &loose)?; - d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); - sel.set([gid]); - Ok(gid) + let gid = s.edit_effect(id, |s| { + s.edit(&label, |d, sel| { + let gid = super::object::group_nodes(d, &loose)?; + d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); + sel.set([gid]); + Ok(gid) + }) })?; return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } @@ -549,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { - fx.push(effect.clone()); - true + let ids = s.edit_effect(id, |s| { + edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { + fx.push(effect.clone()); + true + }) })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. @@ -892,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { - let Some(e) = fx.get_mut(index) else { return false }; - if let Some(id) = &warp_id { - e.id.clone_from(id); - } - if let Some(to) = kind - && e.id != to - { - e.params = effects::three_d_params_as(&e.id, &e.params, to); - e.id = to.to_string(); - } - if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { - if !cur.is_object() { - *cur = effects::merged_params(&e.id, &Value::Null); + // The effect edited, when every target has one at `index` and all are the same: a dialog's + // preview names its step after it. + let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + let ids = s.edit_effect(&one, |s| { + edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { + let Some(e) = fx.get_mut(index) else { return false }; + if let Some(id) = &warp_id { + e.id.clone_from(id); } - // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take - // their current form first, so the new values replace them and the rest is kept. - *cur = effects::upgrade_params(&e.id, cur); - if let Value::Object(m) = cur { - m.extend(new); + if let Some(to) = kind + && e.id != to + { + e.params = effects::three_d_params_as(&e.id, &e.params, to); + e.id = to.to_string(); } - } - if let Some(v) = visible { - e.visible = v; - } - true + if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { + if !cur.is_object() { + *cur = effects::merged_params(&e.id, &Value::Null); + } + // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take + // their current form first, so the new values replace them and the rest is kept. + *cur = effects::upgrade_params(&e.id, cur); + if let Value::Object(m) = cur { + m.extend(new); + } + } + if let Some(v) = visible { + e.visible = v; + } + true + }) })?; Ok(json!({ "ids": ids_json(&ids) })) } diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 8e080e8d80..4dc5c5e75e 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent; FOGRA51 or FOGRA52 for the built-in profiles computed from that data, with registry http://www.color.org unless registry is given), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 1178906459..da5bbea659 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// front, the Appearance panel's active item and the tool the proxy in front shows the default /// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, /// picking a part of the instance, toggling the proxy, picking another item or choosing such a -/// tool or leaving it leaves no stop selected. +/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint +/// diamond by it as well ([`Session::gradient_owner`]). #[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct StopOwner { - doc: Option, +pub struct StopOwner { + /// The active document's uid, which stays the same when its tab moves. + doc: Option, object: Option, /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) /// first in the selection shows the next object's. @@ -106,7 +108,7 @@ impl StopOwner { pub(crate) fn of(s: &Session) -> Self { let st = s.active(); Self { - doc: s.active, + doc: st.map(|d| d.uid), object: st.and_then(|d| d.selection.objects.first().copied()), source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), @@ -140,6 +142,11 @@ impl Session { pub fn selected_stop(&self) -> Option { self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i) } + + /// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]). + pub fn gradient_owner(&self) -> StopOwner { + StopOwner::of(self) + } } type Parsed = std::result::Result; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 182dc0601f..47190a2cdf 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index a4cec6253c..12a92b9193 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live +/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. +fn takes_rounding(live: Option<&LiveShape>) -> bool { + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) +} + /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about /// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { @@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { + if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -291,10 +297,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { && picked.iter().all(|k| { *k < c.base.anchor_count() // A radius stored in document units can be larger than it draws; a relative - // one is a fraction, so it is compared as drawn. + // one is compared as the fraction `set_corners` would store for it, to a + // precision of 1e-9 pt on a corner whose maximum is 1 pt or more. && radius.is_none_or(|r| { - let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) }; - (now - r.max(0.0)).abs() < 1e-9 + let r = r.max(0.0); + if c.radii_relative() { + let max = c.corner(*k).map_or(0.0, |c| c.max_radius()); + let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 }; + (c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9 + } else { + (c.radius(*k) - r).abs() < 1e-9 + } }) && kind.is_none_or(|kd| c.kind(*k) == kd) }) diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index e88f348085..a93c4da50d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -715,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[ "document.exportForScreens", "document.exportForWeb", "document.exportForWeb.preview", + "document.exportForWeb.saveColorTable", "document.exportPdf", "document.find", "document.inspect", @@ -820,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.loadColorTable", "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index b93db7b8a2..bb8d3372ae 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -50,6 +50,10 @@ //! also given the parts of the active document it names in `_context.document`, whether or not //! anything is selected: the settings, artboards, layers and swatches, as plain values //! ([`context`]). +//! +//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}` +//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the +//! plug-in store keeps the two as one module. use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; @@ -124,6 +128,10 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if let Some(script) = p.script() { + v["runtime"] = json!(m.runtime.name()); + v["script"] = json!(script); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -1008,8 +1016,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -/// The `.wasm` extension plug-in files have (File › Open installs them). -pub const EXTS: &[&str] = &["wasm"]; +/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a +/// JavaScript plug-in's manifest. +pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT]; /// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a /// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). @@ -1389,12 +1398,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result { }) } -/// The plug-in in the `.wasm` file `path`, and its module. +/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file +/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text +/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too. #[cfg(not(target_arch = "wasm32"))] fn load_path(path: &str) -> Result<(Plugin, Vec)> { crate::file_access::check_read(path).map_err(EngineError::Other)?; let limits = vectorcraft_plugins::Limits::default(); - let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?; + let file = std::path::Path::new(path); + let bytes = if registry::is_js_package(file) { + let allow = |script: &std::path::Path| match script.to_str() { + Some(script) => crate::file_access::check_read(script), + None => Err(format!("automation path rejected: {} isn't valid text", script.display())), + }; + registry::read_js_package(file, &allow).map_err(err)? + } else { + crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)? + }; Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes)) } @@ -1958,7 +1978,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1985,7 +2005,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1994,7 +2014,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), @@ -2021,7 +2041,7 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}", always, reload ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 9a715abf11..3d5723b7d3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", @@ -403,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.tag.add", + "object.tag.remove", + "object.tag.removeAll", + "object.tag.set", + "object.tags", "object.textWrap.make", "object.textWrap.options", "object.textWrap.release", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 7c271a326a..27d38e158f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), + p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 8a68798aed..efbdb10a20 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out), installed: {read (installed faces compared), skipped (installed faces those limits left out)}}; an error, with no unmatched list, when no shape becomes type, when tolerance is not a number from 0 to 0.05, or when installed is not true, false or null", has_selected_path, retype )] @@ -56,6 +56,10 @@ pub fn specs() -> Vec { #[path = "retype_fonts.rs"] pub(super) mod fonts; +#[path = "retype_installed.rs"] +mod installed; + +pub use installed::{RetypeFound, RetypeRun, RetypeSearch}; /// A shape to match: a path or compound path, in document space. struct Piece { @@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool { ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) } -/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier +/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); d.walk(|n| { @@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break; } @@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { }) } +/// `type.retype`'s `fonts` param: the family names it lists. +fn fonts_param(p: &Value) -> Result> { + const C: &str = "type.retype"; + match p.get("fonts") { + None => Ok(vec![]), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect() + } + Some(_) => Err(bad(C, "fonts must be a list of family names")), + } +} + +/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted. +fn tolerance_param(p: &Value) -> Result { + const C: &str = "type.retype"; + match p.get("tolerance") { + None => Ok(0.0), + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t), + _ => Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + } +} + +/// The shapes of the selected objects, in paint order, and whether shapes past the limits were +/// left out; an error when the selection holds none. +fn selected_pieces(s: &Session) -> Result<(Vec, bool)> { + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + Ok((pieces, truncated)) +} + /// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line /// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape /// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the @@ -1675,26 +1723,70 @@ fn lookup_keys<'a>( (wanted, near_wanted) } +/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split +/// shape, either way round), or, when there are none and `near` is set, the near ones within +/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that +/// paint the area `path` paints under that rule are kept. +fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option, tolerance: f64) -> Vec { + let painted = |index: &RetypeIndex, ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact: Vec = + indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect(); + if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact } +} + +/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour +/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is +/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as +/// several objects would ([`paints_once`]). +fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec> { + let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance); + // Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact + // one; only a part that matches nearly brings the tolerance in. The glyphs of a split may + // become separate objects: when the shape does not paint its overlaps as several objects + // would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not + // overlap, which the parts read by the even-odd rule against them all joined show. + let together = |runs: &[BezPath], near: bool| { + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + }; + parts(path, groups, &find, &together) +} + +/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that +/// keeps its outline or matches nothing. `groups` holds each piece's contour groups. +fn match_pieces(pieces: &[Piece], groups: &[Vec], indexes: &[&RetypeIndex], tolerance: f64) -> Vec>> { + pieces + .iter() + .zip(groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance) + }) + .collect() +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; - let fonts: Vec = match p.get("fonts") { - None => vec![], - Some(Value::Array(a)) => { - a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? - } - Some(_) => return Err(bad(C, "fonts must be a list of family names")), - }; - let tolerance = match p.get("tolerance") { - None => 0.0, - Some(v) => match v.as_f64() { - Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, - _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), - }, - }; + let fonts = fonts_param(p)?; + let tolerance = tolerance_param(p)?; + let search_installed = installed::wanted(C, p)?; + let handed = installed::handed(s); let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; - let (lines, unmatched, truncated) = { + let (lines, unmatched, truncated, installed) = { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut truncated = false; @@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result { let (wanted, near_wanted) = lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() && near_wanted.is_empty() { - RetypeIndex::default() - } else { - RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) + let keyed = !(wanted.is_empty() && near_wanted.is_empty()); + let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] }; + let mut compared: Vec = cands.iter().map(|f| f.id()).collect(); + let build = |faces: Vec>| { + if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() } }; - // Exact matches first; near ones, when allowed, only for a path with none. - // With a visible fill, a glyph is kept only when it paints the area the shape paints under - // the shape's fill rule (`fill` is `Some(nonzero)`). - let find = |path: &BezPath, part: bool, near: bool, fill: Option| { - let painted = |ms: Vec, tol: f64| -> Vec { - match fill { - Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), - None => ms, - } - }; - let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); - if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } - }; - // Each shape's parts (one, unless it holds several glyphs), each with its candidates. - let found: Vec>> = pieces - .iter() - .zip(&groups) - .map(|(pc, g)| { - if pc.keeps_outline { - return vec![]; - } - let fill = pc.filled.then_some(pc.nonzero); - // Parts that all match exactly are checked at tolerance 0, in the near phase as in - // the exact one; only a part that matches nearly brings the tolerance in. - // The glyphs of a split may become separate objects: when the shape does not paint - // its overlaps as several objects would (translucent, another blend, a gradient or - // pattern fill, a stroke), its parts must not overlap, which the parts read by the - // even-odd rule against them all joined show. - let once = paints_once(pc.opacity, pc.blend, &pc.appearance); - let together = |runs: &[BezPath], near: bool| { - if fill.is_none() && once { - return true; - } - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - let tol = if nearly { tolerance } else { 0.0 }; - fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) - && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + let index = build(cands.clone()); + // Exact matches first; near ones, when allowed, only for a path with none. With a visible + // fill, a glyph is kept only when it paints the area the shape paints under the shape's + // fill rule. Each shape's parts (one, unless it holds several glyphs), each with its + // candidates. + let mut found = match_pieces(&pieces, &groups, &[&index], tolerance); + // Shapes no face matched are compared with the other loaded faces, then with the installed + // fonts not loaded yet; or with what a search made off the UI thread found for them. + let left = left_shapes(&pieces, &groups, &found); + // A split shape's glyphs may be spread over the candidates and the other faces. Near + // matching spends an index's comparison budget, so with a tolerance the candidates are + // indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone())); + let (more, installed) = match handed { + Some(handed) => { + let mut more = handed.faces.clone(); + compared.extend(handed.faces.iter().map(|f| f.id())); + // The shapes still left are compared with the loaded faces the search did not + // compare: none, unless a face was loaded after it looked. + compared.extend(handed.scanned.iter().copied()); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0); + (more, handed) + } + None => { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let installed = if search_installed { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + installed::search_beside(db, &left, &beside, tolerance, false)? + } else { + installed::Installed::default() }; - parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) - }) - .collect(); + more.extend(installed.faces.iter().cloned()); + (more, installed) + } + }; + // The faces found join the candidates, the way the loaded ones are matched (near matches + // and split shapes included), and every shape is matched again with them all, so a shape + // that matched already can take the face its neighbors found. + let mut extra: Vec> = vec![]; + for f in more { + if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) { + extra.push(f); + } + } + if !extra.is_empty() { + // Near matching spends an index's comparison budget, so with a tolerance the + // candidates are indexed again for this pass. + let first = if tolerance > 0.0 { build(cands) } else { index }; + let others: Vec = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect(); + let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect(); + found = match_pieces(&pieces, &groups, &all, tolerance); + } // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit // them closest in all (the least leftover distance summed over those shapes), so every @@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room // for small blocks. let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); - (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); @@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, + "installed": installed.json(), })) } +/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its +/// contour groups from `groups`. +fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec], found: &[Vec>]) -> Vec> { + pieces + .iter() + .zip(groups) + .zip(found) + .filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty()) + .map(|((pc, g), _)| installed::Sought { + path: &pc.path, + groups: g, + fill: pc.filled.then_some(pc.nonzero), + once: paints_once(pc.opacity, pc.blend, &pc.appearance), + }) + .collect() +} + #[cfg(test)] #[path = "retype_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index a901ac7e12..e0af549da6 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -3,22 +3,25 @@ //! (, //! ). //! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with -//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same -//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the +//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype` +//! (exact matches only). Of two versions of one font, only the version its //! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many -//! of the shapes it matches, then by how closely, on average, and then by name. The query changes -//! nothing. +//! of the shapes it matches, then by how closely, on average, and then by name. The query does not +//! change the document; the installed fonts that match are loaded. use std::collections::BTreeSet; use std::sync::Arc; +use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_text::FontDb; +use vectorcraft_doc::Document; use vectorcraft_text::retype::{RetypeIndex, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; -use super::super::edit::selected_roots; -use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; -use super::{candidate_faces, collect}; +use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path}; +use super::installed::Installed; +use super::{candidate_faces, selected_pieces}; pub(in crate::cmd) fn specs() -> Vec { vec![cmd!( @@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error", has_selected_path, retype_fonts )] @@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10; pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; /// One font that matched some of the shapes. -struct Ranked { +pub(super) struct Ranked { face: Arc, /// How many shapes it matched. matched: usize, @@ -49,62 +52,99 @@ struct Ranked { } impl Ranked { + /// The font. + pub(super) fn face(&self) -> &Arc { + &self.face + } + fn mean(&self) -> f64 { self.residual / self.matched.max(1) as f64 } } -pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { - retype_fonts_in(s, p, FontDb::global()) -} - -/// [`retype_fonts`] with the fonts of `db`. -fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { - const C: &str = "type.retypeFonts"; - let count = match p.get("count") { - None | Some(Value::Null) => DEFAULT_COUNT, +/// The `count` param: how many fonts to list. +pub(super) fn count_param(p: &Value) -> Result { + match p.get("count") { + None | Some(Value::Null) => Ok(DEFAULT_COUNT), Some(v) => v .as_u64() .and_then(|n| usize::try_from(n).ok()) .filter(|n| (1..=MAX_COUNT).contains(n)) - .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, - }; - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; - let mut pieces = vec![]; - let (mut barrier, mut truncated) = (true, false); - for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); - } + .ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")), } - if pieces.is_empty() { - return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); - } - // Only glyphs with a selected shape's key (segments per contour) can match one. - let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); - // A font is chosen by its family and style, which set the version the name gives: of two - // versions of one font, only that one is compared. The other versions do not take the places - // of fonts loaded after them. - let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); - let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); +} + +/// Is `f` the version of its font that its family and style name gives? A font is chosen by its +/// family and style, which set that version: of two versions of one font, only that one is +/// compared, and the other versions do not take the places of fonts loaded after them. +fn by_name(db: &FontDb, f: &FontFace) -> bool { + db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()) +} + +/// The loaded faces the list compares: those of the document's live type first, then the other +/// loaded faces, each the version its name gives, at most [`MAX_COUNT`]. +pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec> { + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect(); for f in db.loaded_faces() { - if faces.len() >= vectorcraft_text::retype::MAX_FACES { + if faces.len() >= MAX_COUNT { break; } - if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) { faces.push(f); } } + faces +} + +/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of +/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that +/// match), with what that search read. With `handed` (what a search made off the UI thread found, +/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not +/// read again. +pub(super) fn rank_fonts( + db: &FontDb, + faces: Vec>, + shapes: &[&BezPath], + search_installed: bool, + handed: Option, +) -> Result<(Vec, Installed)> { + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); // No shape has a key: no font is read. let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; - // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. let mut ranked: Vec = vec![]; - for pc in &pieces { + rank(&index, shapes, &mut ranked); + // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their + // family and style name gives, up to 96 fonts listed in all. A font that matches only as + // combining marks is not listed, so it takes no place. + let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count()); + let found = if let Some(handed) = handed { + handed + } else if !search_installed { + Installed::default() + } else if room == 0 { + // The list is full: the installed faces a search would compare count as skipped, none + // when no shape would start one. + let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 }; + Installed { skipped, ..Default::default() } + } else { + super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? + }; + // A face found earlier (handed in) may be loaded and ranked already: it counts once. + let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect(); + if !more.is_empty() { + rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked); + } + Ok((ranked, found)) +} + +/// Adds to `ranked` the fonts of `index` that match `shapes`. +fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec) { + for shape in shapes { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64, bool)> = vec![]; - for m in index.all_matches(&pc.path) { + let mut best: Vec<(Arc, f64, bool)> = vec![]; + for m in index.all_matches(shape) { let character = !vectorcraft_text::retype::is_combining_mark(m.ch); match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { Some(b) => { @@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = count_param(p)?; + let search_installed = super::installed::wanted(C, p)?; + let handed = super::installed::handed(s); + let (pieces, truncated) = selected_pieces(s)?; + let d = &s.doc()?.doc; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect(); + let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?; // A font whose glyphs match the shapes only as combining marks would retype none of them, as // type.retype starts no line with a mark: it is not listed. ranked.retain(|r| r.character); @@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { "shapes": pieces.len(), "more": more, "truncated": truncated, + "installed": found.json(), })) } diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index ac7723d82a..60218b8b4a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() { let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [rect]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // Live type alone holds no shape to compare. let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [t]})).unwrap(); @@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() { let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // After a base, the mark counts with it. let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); @@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); } +#[test] +fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed"); + let file = dir.join("RetypeListed-Regular.ttf"); + std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + // Left out: the installed copy is not read, and stays unloaded. + let r = query(&mut s, json!({"count": 96, "installed": false}), &db); + assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}"); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); + // Compared: the copy of Inter matches every shape, as Inter does, and is loaded. + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}"); + assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}"); + assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}"); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); +} + +#[test] +fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() { + use vectorcraft_text::test_fonts::named_copy; + let copy = |family: &str| { + let postscript = format!("{}-Regular", family.replace(' ', "")); + (named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript) + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + // Loaded copies that match fill most of the list. + let loaded = FontDb::with_font_dirs(vec![]); + for i in 0..super::MAX_COUNT { + loaded.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len(); + assert!(listed < super::MAX_COUNT, "{listed}"); + // Installed copies, two more than the places left. + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full"); + for i in 0..super::MAX_COUNT - listed + 2 { + let (data, postscript) = copy(&format!("Installed {i:02}")); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..super::MAX_COUNT { + db.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}"); + assert_eq!(r["more"], json!(false), "no font past the list is found: {r}"); + assert_eq!(r["installed"]["skipped"], json!(2), "{r}"); + assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded"); +} + #[test] fn shapes_that_stay_outlines_still_name_their_font() { // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs new file mode 100644 index 0000000000..4c3aeff0b9 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed.rs @@ -0,0 +1,773 @@ +//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are +//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from +//! (). +//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded +//! as it was read, without the family's other files. Files are read smallest first, within a budget +//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app +//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one +//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts +//! when every glyph it splits into matches, in one face or in several. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use kurbo::BezPath; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; + +use super::super::{EngineError, Result, Session, bad}; + +/// How much one search reads. +#[derive(Clone, Copy)] +struct Limits { + /// Font files (a suitcase font's resource fork) longer than this are not read. + file: u64, + /// The bytes of font files read, in all. + read: u64, + /// The glyphs of installed faces drawn, in all, to tell which can match a shape. + glyphs: usize, + /// The faces found: the faces after the last one found are not compared. + faces: usize, +} + +const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES }; + +/// The `installed` param: whether to look in the installed fonts (default true). +pub(super) fn wanted(cmd: &str, p: &Value) -> Result { + match p.get("installed") { + None | Some(Value::Null) => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, "`installed` must be true, false or null")), + } +} + +/// What a search of the installed fonts found and read. +#[derive(Default)] +pub(super) struct Installed { + /// The faces whose glyphs match a shape, loaded now, in the order they were read. + pub(super) faces: Vec>, + /// Faces read and compared. + pub(super) read: usize, + /// Faces left out by the limits ([`LIMITS`]). + pub(super) skipped: usize, + /// For a search made away from its command, the ids of the loaded faces it compared: the + /// command does not compare them again. + pub(super) scanned: Vec, +} + +impl Installed { + /// As a command's result reports it. + pub(super) fn json(&self) -> Value { + json!({"read": self.read, "skipped": self.skipped}) + } +} + +/// A shape to look for: its path, the contour groups it splits into when it may hold several +/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill +/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as +/// `type.retype` reads them. +#[derive(Clone, Copy)] +pub(super) struct Sought<'a> { + pub(super) path: &'a BezPath, + pub(super) groups: &'a [BezPath], + pub(super) fill: Option, + pub(super) once: bool, +} + +impl<'a> Sought<'a> { + /// `path` split into `groups`, with no paint check. + pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self { + Sought { path, groups, fill: None, once: true } + } +} + +/// `shapes`, each matched whole only. +fn whole<'a>(shapes: &[&'a BezPath]) -> Vec> { + shapes.iter().map(|path| Sought::unpainted(path, &[])).collect() +} + +/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]). +fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet, Vec) { + super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance) +} + +/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar), +/// with a key to look glyphs up by? A shape without one matches no face. +fn starts(s: &Sought, tolerance: f64) -> bool { + if is_plain(s.path) { + return false; + } + let (keys, near) = keys_of(std::slice::from_ref(s), tolerance); + !keys.is_empty() || !near.is_empty() +} + +/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does +/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])? +fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool { + !super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty() +} + +/// [`search_for`] of `shapes` matched whole, exactly. +#[cfg(test)] +pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result { + search_within(db, shapes, every, LIMITS, &|_| true) +} + +/// [`search_beside`] with no loaded faces. +#[cfg(test)] +pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result { + search_beside(db, shapes, &[], tolerance, every) +} + +/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found +/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a +/// face is found when it matches such a shape, or completes the glyphs of a split one with the +/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or +/// read before it (a face read before whose glyphs it completes is found with it), and the search +/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is +/// compared, and found when it matches a shape on its own. No file is read when every shape is +/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped. +/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces +/// found too, so the command compares them with it. +pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result { + search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true) +} + +/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face +/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`. +pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) +} + +/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them +/// not plain, with a glyph's key ([`shape_key`])? +pub(super) fn starts_search(shapes: &[&BezPath]) -> bool { + shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some()) +} + +/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only. +#[cfg(test)] +pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result>> { + Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0) +} + +/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares +/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance` +/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of +/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces +/// among `compared`). With them, whether each shape was found, and the indexes of the latest +/// groups that hold glyphs of the shapes while a split shape is not found (at most +/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those +/// groups. +pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result { + let mut done = vec![false; shapes.len()]; + let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect(); + let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance); + let mut out: Vec> = vec![]; + if keys.is_empty() && near.is_empty() { + return Ok((out, done, vec![])); + } + let rest: Vec> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect(); + // The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found + // yet: the latest [`MAX_KEPT_GROUPS`]. + let mut kept: Vec = vec![]; + for group in rest.chunks(MAX_FACES) { + vectorcraft_doc::cancel::check()?; + let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near); + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect(); + for (k, s) in &looked { + // A split shape not found yet is matched with the faces before the group too (one pass, + // as near matching spends an index's budget); any other shape with the group alone. + let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true); + let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] }; + let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance); + if parts.is_empty() { + continue; + } + if let Some(d) = done.get_mut(*k) { + *d = true; + } + for m in parts.into_iter().flatten() { + if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) { + out.push(m.face); + } + } + } + let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)); + if open && !index.is_empty() { + // The latest groups are kept: the oldest goes when the cap is reached. + if kept.len() >= MAX_KEPT_GROUPS { + kept.remove(0); + } + kept.push(index); + } + } + if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) { + kept.clear(); + } + Ok((out, done, kept)) +} + +/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept +/// for the search of the installed fonts. +type LoadedRest = (Vec>, Vec, Vec); + +/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces +/// complete a split shape's glyphs with, at most: the latest ones. +const MAX_KEPT_GROUPS: usize = 4; + +/// An installed font file: its path, its length and the (family, style) of the faces wanted from it. +type File = (std::path::PathBuf, u64, Vec<(String, String)>); + +/// [`search`] within `limits`, keeping in its faces only those `listed` accepts. +#[cfg(test)] +fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed) +} + +/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts. +fn search_sought( + db: &FontDb, + shapes: &[Sought], + beside: &[&RetypeIndex], + tolerance: f64, + every: bool, + limits: Limits, + listed: &dyn Fn(&FontFace) -> bool, +) -> Result { + let mut out = Installed::default(); + // A shape without a glyph's key matches no face: the search does not wait for it. + let shapes: Vec = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect(); + let (keys, near) = keys_of(&shapes, tolerance); + if keys.is_empty() && near.is_empty() { + return Ok(out); + } + let (keys, near) = (&keys, near.as_slice()); + // The indexes of the faces found, which the glyphs of a split shape may be spread over. + let mut found: Vec = vec![]; + // The faces read, not loaded, that hold glyphs of the shapes without completing one, with their + // indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`]. + let mut partial: Vec<(Arc, RetypeIndex)> = vec![]; + // The faces wanted from each file, smallest file first. + let mut files: Vec = vec![]; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for f in db.unloaded_installed_faces() { + match at.get(&f.path).and_then(|i| files.get_mut(*i)) { + Some(file) => file.2.push((f.family, f.style)), + None => { + at.insert(f.path.clone(), files.len()); + files.push((f.path, f.len, vec![(f.family, f.style)])); + } + } + } + files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + let mut matched = vec![false; shapes.len()]; + // Is a split shape not found yet: only then are faces kept in `partial`. + let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty()); + let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); + let total = files.len() as u64; + for (i, (path, len, styles)) in files.iter().enumerate() { + vectorcraft_doc::cancel::check()?; + vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts"); + // A file too long for what is left, or read when no glyph is left to draw, is not read. + if *len > limits.file || *len > bytes_left || glyphs_left == 0 { + out.skipped += styles.len(); + continue; + } + // A file that grew since the scan is read only within what is left. + let file = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read, those of a file that grew past the limits too. + bytes_left = bytes_left.saturating_sub(file.bytes); + if file.too_long { + out.skipped += styles.len(); + continue; + } + let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + let faces: Vec> = file.faces.into_iter().filter(|f| wanted(f)).collect(); + for (j, face) in faces.iter().enumerate() { + if out.faces.len() >= limits.faces { + // The faces not compared past the cap: the rest of this file's and the later files'. + out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + let n = encoded_glyphs(face); + if n > glyphs_left { + out.skipped += 1; + continue; + } + glyphs_left -= n; + out.read += 1; + let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near); + if index.is_empty() { + continue; + } + // With `every`, a face fits a shape it matches on its own; otherwise a shape not found + // yet that it completes with the loaded faces of `beside`, the faces found before it and + // the faces read before it that hold some of its glyphs (`partial`). + let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect(); + let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec> { + let Some(s) = shapes.get(k) else { return vec![] }; + if every { + return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance); + } + if matched.get(k).copied().unwrap_or(true) { + return vec![]; + } + // A shape matched whole only takes one glyph: the faces read before it do not hold it. + let extra = if s.groups.is_empty() { &[] } else { extra }; + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect(); + super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance) + }; + let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty(); + let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k); + // Each shape it fits, with the glyphs it matches: one pass, as near matching spends an + // index's budget. + let first: Vec<(usize, Vec>)> = + (0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect(); + let fits: Vec = first.iter().map(|(k, _)| *k).collect(); + if fits.is_empty() { + // The face holds glyphs of a shape without completing one: a later face may, while + // a split shape is not found. The latest are kept: the oldest goes when the cap is + // reached. + if !every && open(&matched) { + #[cfg(test)] + KEPT_PARTIAL.with(|n| n.set(n.get() + 1)); + if partial.len() >= MAX_FACES { + partial.remove(0); + } + partial.push((face.clone(), index)); + } + continue; + } + let loaded = load(db, face); + let same = loaded.id() == face.id(); + let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit); + if fits.is_empty() { + continue; + } + // The faces read before whose glyphs the shapes it fits use, loaded with it: those + // that leave room under the cap, or else only the shapes it fits without them. A face + // loaded in place of the one read is matched again for them. + let matches: Vec> = if same { + first.into_iter().flat_map(|(_, p)| p).collect() + } else { + fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect() + }; + let held: Vec<&Arc> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect(); + let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial); + if out.faces.len() + used.len() + with_loaded.len() >= limits.faces { + let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance))); + used.clear(); + with_loaded.clear(); + if fits.is_empty() { + continue; + } + } + let mut shadowed = false; + let mut promoted: Vec> = vec![]; + for at in used.into_iter().rev() { + let (read, ix) = partial.remove(at); + let loaded = load(db, &read); + let ix = if loaded.id() == read.id() { + ix + } else { + shadowed = true; + RetypeIndex::build_near(db, [loaded.clone()], keys, near) + }; + promoted.insert(0, loaded); + found.push(ix); + } + // A face loaded in place of one read may have other glyphs: the shapes are checked again. + if shadowed { + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance))); + if fits.is_empty() { + continue; + } + } + // The faces it completes shapes with, once the match holds. + out.faces.extend(with_loaded); + for loaded in promoted { + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + } + // A face `listed` turns down (another version shadows it) is not compared ahead of others. + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + found.push(index); + for k in fits { + if let Some(m) = matched.get_mut(k) { + *m = true; + } + } + if !every && matched.iter().all(|m| *m) { + return Ok(out); + } + // With every split shape found, the faces kept for them are dropped. + if !open(&matched) { + partial.clear(); + } + } + // The cap reached with the file's last face: the later files are not compared. + if out.faces.len() >= limits.faces { + out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + } + Ok(out) +} + +#[cfg(test)] +thread_local! { + /// How many times a search on this thread kept a face it read in `partial`. + static KEPT_PARTIAL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of, +/// one face that does: a loaded face of `beside` (the command compares it with the face found), +/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the +/// loaded faces. +fn companions( + parts: &[Vec], + held: &[&Arc], + beside: &[&RetypeIndex], + partial: &[(Arc, RetypeIndex)], +) -> (Vec, Vec>) { + let (mut used, mut loaded) = (BTreeSet::new(), Vec::>::new()); + for part in parts { + let has = |f: &Arc| part.iter().any(|m| m.face.id() == f.id()); + let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f)); + if held.iter().copied().chain(&loaded).chain(chosen).any(has) { + continue; + } + let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id()))); + if let Some(m) = of_beside { + loaded.push(m.face.clone()); + } else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) { + used.insert(at); + } + } + (used.into_iter().collect(), loaded) +} + +/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the +/// latest first: at most [`MAX_FACES`]. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces. +fn remember(db: &FontDb, face: &FontFace) { + let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let at = (db.id(), face.id()); + kept.retain(|k| *k != at); + kept.insert(0, at); + kept.truncate(MAX_FACES); +} + +/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A +/// later Retype compares them ahead of the other loaded faces. +pub(super) fn found(db: &FontDb) -> Vec> { + let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect() +} + +/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`, +/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index` +/// when it is `read` itself. Another face of the same family, style and version, loaded from +/// another file, may have other glyphs; it is indexed by `keys` and `near`. +#[allow(clippy::too_many_arguments)] +fn still_fit( + db: &FontDb, + read: &FontFace, + loaded: &Arc, + index: RetypeIndex, + keys: &BTreeSet, + near: &[NearKey], + fits: Vec, + fit: &dyn Fn(&RetypeIndex, usize) -> bool, +) -> (Vec, RetypeIndex) { + if loaded.id() == read.id() { + return (fits, index); + } + let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near); + let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect(); + (fits, index) +} + +/// `face` (read from an installed file and not loaded) loaded into `db` as it was read +/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again. +fn load(db: &FontDb, face: &Arc) -> Arc { + db.load_read_face(face.clone()) +} + +/// A search of the installed fonts made away from its command, so the app can run it off the UI +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the +/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded +/// faces to compare, compares them and searches the installed fonts on any thread, loading the +/// faces that match; and +/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with +/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the +/// installed fonts again. +pub struct RetypeRun { + params: Value, + /// The document ([`crate::DocState::uid`]), its content and the selection the search is for. + doc: u64, + content: Arc, + selection: Vec, + search: Arc, +} + +/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another +/// thread ([`RetypeRun::search`]). +pub struct RetypeSearch { + command: &'static str, + /// The document it is for ([`crate::DocState::uid`]). + doc: u64, + /// The shapes to match, and the loaded faces they are compared with first. + shapes: Vec, + faces: Faces, + /// `type.retype`'s tolerance (0 for `type.retypeFonts`). + tolerance: f64, +} + +/// The loaded faces a [`RetypeSearch`] compares first. +enum Faces { + /// These faces. + #[cfg(test)] + Given(Vec>), + /// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of + /// those families and of the document's live type ([`super::candidate_faces`]), and without, the + /// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the + /// search's thread, since a family not loaded yet is read from its files. + Of { doc: Arc, fonts: Option> }, +} + +impl Faces { + fn get(&self, db: &FontDb) -> Vec> { + match self { + #[cfg(test)] + Faces::Given(faces) => faces.clone(), + Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts), + Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc), + } + } +} + +/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its +/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible +/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]). +struct Shape { + path: BezPath, + groups: Vec, + fill: Option, + once: bool, +} + +impl Shape { + /// `path`, matched whole, with no paint check. + fn whole(path: BezPath) -> Self { + Shape { path, groups: vec![], fill: None, once: true } + } + + fn sought(&self) -> Sought<'_> { + Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once } + } +} + +/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the +/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match, +/// loaded, and the loaded faces it compared; and what it read of the installed fonts. +pub struct RetypeFound { + doc: u64, + installed: Installed, +} + +impl RetypeFound { + /// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as + /// its own search of the installed fonts would, in the document the search was made for. Any + /// such command takes it; one in another document compares only what is loaded. + pub fn hand_in(self, s: &mut Session) { + s.retype_hand_off = Some(self); + } + + /// Drop what was handed in and no command took, as when the command failed before it took + /// it: a later command searches for itself. + pub fn drop_handed(s: &mut Session) { + s.retype_hand_off = None; + } + + /// What it read, as the commands report it. + pub fn json(&self) -> Value { + self.installed.json() + } +} + +/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]). +/// It is taken whatever the document, so it is used once. +pub(super) fn handed(s: &mut Session) -> Option { + let found = s.retype_hand_off.take()?; + let doc = s.doc().ok()?.uid; + (found.doc == doc).then_some(found.installed) +} + +impl RetypeRun { + /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the + /// active document. None when it reads no installed font: `installed` is false, or no shape + /// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection. + /// The faces to compare are picked when the search runs. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { + let (command, fonts, tolerance) = match command { + "type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?), + "type.retypeFonts" => { + super::fonts::count_param(p)?; + ("type.retypeFonts", None, 0.0) + } + other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))), + }; + // The keys the command refuses (an unknown one) fail here too, before any search. + s.check_params(command, p)?; + if !wanted(command, p)? { + return Ok(None); + } + let (pieces, _) = super::selected_pieces(s)?; + let st = s.doc()?; + // Retype compares the shapes that may become type, split as it splits them; the list + // compares every shape whole. + let shapes: Vec = if fonts.is_some() { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + pieces + .into_iter() + .filter(|pc| !pc.keeps_outline) + .map(|pc| Shape { + groups: super::split_groups(&pc.path, &mut budget), + fill: pc.filled.then_some(pc.nonzero), + once: super::paints_once(pc.opacity, pc.blend, &pc.appearance), + path: pc.path, + }) + .collect() + } else { + pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect() + }; + if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) { + return Ok(None); + } + let faces = Faces::Of { doc: st.doc.clone(), fonts }; + Ok(Some(RetypeRun { + params: p.clone(), + doc: st.uid, + content: st.doc.clone(), + selection: st.selection.objects.clone(), + search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }), + })) + } + + /// `type.retype` or `type.retypeFonts`. + pub fn command(&self) -> &'static str { + self.search.command + } + + /// What it compares and searches, for another thread. + pub fn search(&self) -> Arc { + self.search.clone() + } + + /// The command's params: those it was prepared with. + pub fn params(&self) -> &Value { + &self.params + } + + /// Does it still apply: is the document it was prepared in active, with the same content and + /// the same objects selected? + pub fn current(&self, s: &Session) -> bool { + s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + #[cfg(test)] + fn run_in(&self, db: &FontDb) -> Result { + self.search.run_in(db) + } +} + +impl RetypeSearch { + /// Compare the shapes with the loaded faces, then search the installed fonts as the command + /// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a + /// cancel stopped it). It touches no document, so it can run on any thread. + pub fn run(&self) -> Result { + self.run_in(FontDb::global()) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + fn run_in(&self, db: &FontDb) -> Result { + let picked = self.faces.get(db); + let installed = if self.command == "type.retypeFonts" { + let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect(); + let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?; + // The loaded faces that match are handed in too, ahead of the installed ones found: + // loading those can move a loaded face past the 96 the command lists. + let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); + for f in std::mem::take(&mut found.faces) { + if !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + found.faces = faces; + found + } else { + // The shapes are matched as the command matches them first. + let tolerance = self.tolerance; + let sought: Vec = self.shapes.iter().map(Shape::sought).collect(); + let (keys, near) = keys_of(&sought, tolerance); + let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near); + let parts: Vec>> = + self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect(); + let left: Vec = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect(); + // The first faces that match are handed in too: loading the faces found can move one + // past the first 96 the command compares. + let mut first: Vec> = vec![]; + for m in parts.into_iter().flatten().flatten() { + if !first.iter().any(|f| f.id() == m.face.id()) { + first.push(m.face); + } + } + // The loaded faces past the ones compared first, then the installed fonts for what + // none of them matches; the command takes both from what is handed in. + let compared: Vec = picked.iter().map(|f| f.id()).collect(); + // Every face loaded now is compared, among the first ones or with the rest. + let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); + // A split shape's glyphs may be spread over the faces compared first and the others. + // Near matching spends an index's comparison budget, so with a tolerance the faces + // compared first are indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near)); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { + kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect() + } else { + kept + }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + let mut found = search_beside(db, &left, &beside, tolerance, false)?; + found.faces.splice(0..0, first.into_iter().chain(rest)); + found.scanned = scanned; + found + }; + Ok(RetypeFound { doc: self.doc, installed }) + } +} + +#[cfg(test)] +#[path = "retype_installed_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs new file mode 100644 index 0000000000..4945d9c259 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -0,0 +1,833 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +use kurbo::{Affine, BezPath, Shape}; +use serde_json::json; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::shape_key; + +use super::{Limits, search, search_within}; +use crate::Session; + +/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named +/// `families`, one file each, in a folder of their own: they are installed and not loaded. +/// Returns the database and the files. +fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec) { + let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}")); + let mut files = vec![]; + for family in families { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + let path = dir.join(format!("{postscript}.ttf")); + std::fs::write(&path, data).unwrap(); + files.push(path); + } + (FontDb::with_font_dirs(vec![dir]), files) +} + +/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt. +fn glyphs(db: &FontDb, text: &str) -> Vec { + let face = db.face("Source Sans 3", "Regular").unwrap(); + text.chars() + .enumerate() + .map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c))) + .collect() +} + +fn keys(shapes: &[BezPath]) -> BTreeSet { + shapes.iter().filter_map(shape_key).collect() +} + +/// `paths` as a search compares them, each matched whole. +fn whole(paths: Vec) -> Vec { + paths.into_iter().map(super::Shape::whole).collect() +} + +fn unloaded(db: &FontDb, family: &str) -> bool { + db.unloaded_installed_faces().iter().any(|f| f.family == family) +} + +#[test] +fn an_installed_face_whose_glyphs_match_is_found_and_loaded() { + let (db, files) = installed("found", &["Retype Copy A"]); + assert!(unloaded(&db, "Retype Copy A")); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.skipped), (1, 0)); + let face = found.faces.first().expect("the installed copy matches"); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular")); + assert_eq!(face.path(), Some(files[0].as_path())); + // Loaded now, as it was read. + assert!(db.loaded_faces().iter().any(|f| f.id() == face.id())); + assert!(!unloaded(&db, "Retype Copy A")); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // A later Retype compares it ahead of the other loaded faces, however many are loaded. + assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]); + assert_eq!(candidates.first().map(|f| f.id()), Some(face.id())); + // Only this database's faces. + assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty()); +} + +#[test] +fn a_matching_face_loads_without_the_family_s_other_files() { + let dir = vectorcraft_testkit::temp_dir("retype-installed-family"); + for style in ["Regular", "Bold"] { + let data = + vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap(); + std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1)); + let style = found.faces[0].style.clone(); + let loaded: Vec = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect(); + assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded"); + let left: Vec = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect(); + assert_eq!(left.len(), 1); + assert_ne!(left[0], style); +} + +#[test] +fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { + use vectorcraft_text::test_fonts::named_copy; + let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular"); + let db = FontDb::with_font_dirs(vec![]); + // Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too. + db.add_font(named_copy(true, names).unwrap()); + let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); + let path = dir.join("RetypeTwin-Regular.ttf"); + std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap(); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let keys = keys(&shapes); + let loaded = super::load(&db, &read); + assert_ne!(loaded.id(), read.id(), "the face loaded first is kept"); + let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty(); + let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys); + let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit); + assert!(fits.is_empty(), "Inter's R and x are not these"); + let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit); + assert_eq!(fits, [0, 1]); +} + +#[test] +fn an_installed_face_no_shape_matches_is_read_and_not_loaded() { + let (db, _) = installed("none", &["Retype Copy B"]); + let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)]; + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded"); + // No shape: no file is read. + let none = search(&db, &[], false).unwrap(); + assert_eq!((none.read, none.skipped), (0, 0)); +} + +#[test] +fn plain_shapes_alone_read_no_installed_font() { + // A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart. + let (db, _) = installed("plain", &["Retype Copy L"]); + let mut shapes = glyphs(&db, "-"); + shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1)); + assert!(shapes.iter().all(vectorcraft_text::retype::is_plain)); + let refs: Vec<&BezPath> = shapes.iter().collect(); + for every in [false, true] { + let found = search(&db, &refs, every).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0)); + } + assert!(unloaded(&db, "Retype Copy L")); + // Beside a shape that is not plain, the search reads the file for that shape. + shapes.extend(glyphs(&db, "q")); + let refs: Vec<&BezPath> = shapes.iter().collect(); + assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); +} + +#[test] +fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() { + let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]); + let mut shapes = glyphs(&db, "k"); + // More contours than any glyph's key counts: no face can match it. + let mut dots = BezPath::new(); + for i in 0..49 { + dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1)); + } + assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots)); + shapes.push(dots); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read"); +} + +#[test] +fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { + let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); + let shapes = glyphs(&db, "ab"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let first = search(&db, &refs, false).unwrap(); + assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read"); + let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]); + let all = search(&db, &refs, true).unwrap(); + assert_eq!((all.read, all.faces.len()), (2, 2)); + let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); +} + +#[test] +fn faces_read_are_kept_for_split_shapes_only() { + let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]); + // The k matches in the first file and the circle in none, so every file is read; the later + // files hold the k's glyph without completing a shape. With every shape whole, none is kept. + let mut shapes = glyphs(&db, "k"); + shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1)); + assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + super::KEPT_PARTIAL.with(|n| n.set(0)); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (3, 1)); + assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept"); +} + +#[test] +fn faces_past_the_limits_are_skipped_and_counted() { + let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap(); + // Files longer than the limit for one file. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX }; + let all = |_: &vectorcraft_text::FontFace| true; + let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap(); + assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0)); + // Bytes for one file only. + let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap(); + assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1)); + // Glyphs for no face. + let (db, _) = installed("limits-glyphs", &["Retype Copy I"]); + let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap(); + assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0)); + assert!(unloaded(&db, "Retype Copy I")); + // Faces found up to the cap: the faces after it are not compared, and count as skipped. + let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]); + let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap(); + assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); +} + +#[test] +fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() { + let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + let (first, second) = (len(&files[0]), len(&files[1])); + let grown = files[0].clone(); + // The first file grows past the limit for one file as its reading starts, after the listing. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 0 { + let mut data = std::fs::read(&grown).unwrap(); + data.resize(data.len() + second as usize + 1, 0); + std::fs::write(&grown, data).unwrap(); + } + }); + // Bytes for both files as listed: the grown file's reading takes one more than the limit for + // one file, which leaves too little for the second. + let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX }; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let all = |_: &vectorcraft_text::FontFace| true; + let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0)); +} + +#[test] +fn the_glyph_budget_counts_the_glyphs_drawn() { + let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let mapped = face.mapped_chars().len(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + assert!(drawn < mapped, "{drawn} of {mapped}"); + // A budget below the face's characters and at the glyphs drawn: the face is compared. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, open, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1)); +} + +#[test] +fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() { + let (db, _) = installed("list-run", &["Retype Copy List"]); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), + ); + let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); + let search = super::RetypeSearch { + command: "type.retypeFonts", + doc: 1, + shapes: whole(glyphs(&db, "Rx")), + faces: super::Faces::Given(loaded.clone()), + tolerance: 0.0, + }; + let found = search.run_in(&db).unwrap(); + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + // The loaded face first, then the installed one, each once. + assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]); + assert_eq!((found.installed.read, found.installed.skipped), (1, 0)); +} + +#[test] +fn faces_a_list_turns_down_are_loaded_and_take_no_place() { + let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Two places, and the first face found is turned down: the next two are listed. + let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap(); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); + assert_eq!((found.read, found.skipped), (3, 0)); + assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); + // Only the faces listed are compared ahead of the other loaded faces later. + let ahead: Vec = super::found(&db).iter().map(|f| f.family.clone()).collect(); + assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}"); +} + +#[test] +fn a_cancel_stops_the_search_between_files() { + let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let stop = token.clone(); + // The cancel comes as the second file starts: it is read, the third is not. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 1 { + stop.cancel(); + } + }); + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count(); + assert_eq!(left, 1, "two files were read and loaded, the third was not"); +} + +#[test] +fn a_run_away_from_the_command_loads_the_faces_it_finds() { + let (db, _) = installed("run", &["Retype Copy X"]); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ids: Vec = + glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // Off: nothing to run. + for cmd in ["type.retype", "type.retypeFonts"] { + assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none()); + } + // The command's params are checked as it checks them. + assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err()); + // An unknown key fails before any search, as the command fails on it. + for cmd in ["type.retype", "type.retypeFonts"] { + let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("typo"), "{cmd}: {e}"); + assert!(s.execute(cmd, &json!({"typo": true})).is_err()); + } + // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. + let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap(); + assert_eq!(run.command(), "type.retype"); + assert_eq!(run.params(), &json!({})); + assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); + assert!(unloaded(&db, "Retype Copy X")); + // The list compares every installed face: the copy is read and loaded. + let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap(); + assert_eq!(run.params(), &json!({"count": 5})); + assert!(run.current(&s)); + let found = run.run_in(&db).unwrap(); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // The loaded faces that match are handed in with it, ahead of it. + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}"); + assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}"); + assert!(families.contains(&"Source Sans 3"), "{families:?}"); + assert!(!unloaded(&db, "Retype Copy X")); + // A change of selection or content: it no longer applies. + s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); + assert!(!run.current(&s)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert!(run.current(&s)); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert!(!run.current(&s)); +} + +#[test] +fn plain_shapes_alone_start_no_run_away_from_the_command() { + // A rectangle and a bar are plain: the search reads no installed font for them, so the + // command runs at once. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap(); + for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] { + assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}"); + } +} + +#[test] +fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let uid = s.doc().unwrap().uid; + let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } }; + // Taken instead of a search of the installed fonts, also with installed false. + handed(uid).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}"); + // Used once. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + // Another document's is dropped. + handed(uid + 1).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(s.retype_hand_off.is_none(), "taken"); + // Retype takes it too, whether or not a loaded font matches the rectangle. + handed(uid).hand_in(&mut s); + let _ = s.execute("type.retype", &json!({"installed": false})); + assert!(s.retype_hand_off.is_none()); +} + +#[test] +fn a_canceled_search_stops_before_reading_a_file() { + let (db, _) = installed("cancel", &["Retype Copy J"]); + let shapes = glyphs(&db, "z"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded"); +} + +/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them. +fn pieces(text: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let node = d.node(vectorcraft_doc::NodeId(group)).unwrap(); + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces); + pieces +} + +#[test] +fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() { + let (db, _) = installed("retype", &["Retype Copy K"]); + let pieces = pieces("Wk-"); + assert_eq!(pieces.len(), 3); + let groups = vec![vec![]; pieces.len()]; + // The first shape is taken as matched already: the others are looked for. + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty()); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 2); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!(installed.read, 1); + // The faces found join the index, and every shape is matched again. + let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::>()); + let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys); + let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0); + let whole = |k: usize| found[k].first().expect("one part").clone(); + assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match"); + // and gets the face found too, so its line can be set in the face the others match. + assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found"); + let k = whole(1); + let m = k.first().expect("the installed copy matches the k"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k')); + assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face"); + // The hyphen, a plain shape, matches the font the k found. + let hyphen = whole(2); + let m = hyphen.first().expect("the installed copy matches the hyphen"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-')); +} + +/// `path` flattened into lines `tol` from its curves, each contour started at its second point +/// and run backwards: an outline built nothing like the font's. +fn simplified(path: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(path.iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out +} + +#[test] +fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() { + // A word outlined as one compound path: the whole shape is no glyph, and its glyphs are. + let (db, _) = installed("split", &["Retype Copy Split"]); + let mut word = BezPath::new(); + for g in glyphs(&db, "Wk") { + word.extend(g.iter()); + } + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 1); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found"); + assert!(!unloaded(&db, "Retype Copy Split")); + // A simplified outline: no installed glyph matches it exactly, and one does within a tolerance. + let (db, _) = installed("near", &["Retype Copy Near"]); + let r = simplified(&glyphs(&db, "R")[0], 0.05); + let shape = [super::Sought::unpainted(&r, &[])]; + let exact = super::search_for(&db, &shape, 0.0, false).unwrap(); + assert_eq!((exact.read, exact.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy Near")); + let near = super::search_for(&db, &shape, 0.02, false).unwrap(); + let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found"); + assert!(!unloaded(&db, "Retype Copy Near")); +} + +#[test] +fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each + // font installed: neither face holds both glyphs. + let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two"); + for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 2); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found"); + assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I")); +} + +#[test] +fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the + // loaded face compared first; the only other face is an installed copy of Inter. + let dir = vectorcraft_testkit::temp_dir("retype-installed-beside"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near); + let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs"); +} + +#[test] +fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() { + // A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source + // Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k. + let n = vectorcraft_text::retype::MAX_FACES + 4; + let dir = vectorcraft_testkit::temp_dir("retype-installed-many"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..n { + let family = format!("Retype Many {i}"); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(), + ); + } + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect(); + assert_eq!(copies.len(), n); + let indexes: Vec = copies + .chunks(vectorcraft_text::retype::MAX_FACES) + .map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near)) + .collect(); + let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.len(), 2, "{families:?}"); + assert_eq!(families.last(), Some(&"Retype Many I")); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() { + // A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first + // (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3 + // the W. + let dir = vectorcraft_testkit::temp_dir("retype-installed-kept"); + let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap(); + std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let compared: Vec = db.loaded_faces().iter().map(|f| f.id()).collect(); + db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap()); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap(); + assert!(rest.is_empty() && done == [false]); + assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts"); + let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W"); +} + +#[test] +fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() { + // Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap + // is unpainted, and two glyphs set side by side would paint it. + let paths = |db: &FontDb| { + let face = db.face("Source Sans 3", "Regular").unwrap(); + let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut word = BezPath::new(); + for x in [40.0, 49.0] { + word.extend((Affine::translate((x, 100.0)) * o.clone()).iter()); + } + word + }; + let (db, _) = installed("paint", &["Retype Copy Paint"]); + let word = paths(&db); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true }; + let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap"); + assert!(unloaded(&db, "Retype Copy Paint")); + // Without a fill to compare, the same glyphs are found. + let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]); + let word = paths(&db); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.faces.len(), 1); +} + +#[test] +fn retype_reads_no_installed_font_for_plain_shapes_alone() { + let (db, _) = installed("retype-plain", &["Retype Copy M"]); + let pieces = pieces("W-"); + let groups = vec![vec![]; pieces.len()]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 1, "the hyphen is left"); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!((installed.read, installed.faces.len()), (0, 0)); + assert!(unloaded(&db, "Retype Copy M")); +} + +#[test] +fn installed_must_be_a_bool_or_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for cmd in ["type.retype", "type.retypeFonts"] { + for bad in [json!(1), json!("yes"), json!([])] { + let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string(); + assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}"); + } + } + // false: no installed font is read, and the result says so. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); +} + +/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded, +/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on. +fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}")))); + for (inter, family) in copies { + let postscript = format!("{}-Regular", family.replace(' ', "")); + db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + db +} + +#[test] +fn loaded_faces_past_the_ones_compared_first_are_compared_too() { + let n = vectorcraft_text::retype::MAX_FACES + 4; + let db = loaded_copies("Retype Rest", 0, n); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Every loaded face that matches, more than one index takes. + let rest = super::loaded_rest(&db, &refs, &[]).unwrap(); + for i in 0..n { + assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len()); + } + // The faces compared already are left out. + let last = format!("Retype Rest {}", n - 1); + let compared: Vec = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect(); + let rest = super::loaded_rest(&db, &refs, &compared).unwrap(); + assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::>(), [last.as_str()]); + // A plain shape alone compares none. + let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)]; + assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty()); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() { + // A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are + // compared first; past them, a loaded copy of Inter holds the k. + let db = loaded_copies("Retype Rest Split", 1, 0); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let compared = [source.id(), inter.id()]; + let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near); + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap(); + assert!(kept.is_empty(), "no split shape is left"); + let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first"); + assert_eq!(done, [true]); +} + +#[test] +fn files_past_the_glyph_budget_are_skipped_without_being_read() { + let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + assert_eq!(db.unloaded_installed_faces().len(), 2); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + // The second file holds no font after the listing: had it been read, it would give no face + // to skip. + std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap(); + let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, limits, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1)); +} + +#[test] +fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() { + let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1); + let shapes = glyphs(&db, "Rx"); + // The Inter copies are compared first: none matches, and the copy loaded after them does. + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); + assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); + let search = + super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 }; + let found = search.run_in(&db).unwrap(); + assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); + assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); + // Every loaded face was compared: the command does not compare them again. + assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id()))); + // A face compared first that matches is handed in too, as loading others may move it past + // the faces the command compares first. + let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 } + .run_in(&db) + .unwrap(); + assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); +} + +#[test] +fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() { + let (db, _) = installed("full-list", &["Retype Copy Full"]); + for i in 0..super::super::fonts::MAX_COUNT { + let family = format!("Retype Full {i}"); + let postscript = format!("RetypeFull{i}-Regular"); + db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect(); + // A hyphen is plain: it fills the list and would start no search, so nothing is skipped. + let hyphen = glyphs(&db, "-"); + let refs: Vec<&BezPath> = hyphen.iter().collect(); + let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap(); + assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT); + assert_eq!((found.read, found.skipped), (0, 0)); + // A shape that is not plain would: the installed face counts as skipped. + let shapes = glyphs(&db, "-q"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap(); + assert_eq!((found.read, found.skipped), (0, 1)); + assert!(unloaded(&db, "Retype Copy Full")); +} + +#[test] +fn what_is_handed_in_and_not_taken_can_be_dropped() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let doc = s.doc().unwrap().uid; + super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s); + assert!(s.retype_hand_off.is_some()); + super::RetypeFound::drop_handed(&mut s); + assert!(s.retype_hand_off.is_none()); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5e000d52ab..b386758690 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { #[test] fn a_combining_mark_starts_no_line() { // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + // The calls that leave a shape an outline leave the installed fonts out, so what this machine + // has installed does not change the result. let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as @@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); assert_eq!(r["unmatched"], json!([mark])); // After a base, the mark is retyped with it. @@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); // A mark that is also another character (dot below, dot above) becomes that character there. let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); @@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and @@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() { pair.sort_unstable(); let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); left.sort_unstable(); @@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() { s.execute("select.set", &json!({"ids": moved})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); let texts = r["texts"].as_array().unwrap(); let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); @@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches"); } #[test] @@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } @@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() { // A bar that is exactly a hyphen of the font, somewhere else: the worst case. let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["AB"]), "{r}"); let un = r["unmatched"].as_array().unwrap(); assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); @@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { simplify_every_path(&mut s, 0.05); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); @@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); - // Nothing is left to retype: both stay outlines, as the lone bar beside art does. - let e = s.execute("type.retype", &json!({})).unwrap_err(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed + // fonts are left out, so what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err(); assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); } @@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the period became type: {r}"), Err(e) => e.to_string(), }; @@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "reported once: {e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); } @@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the overlapping o's became type: {r}"), Err(e) => e.to_string(), }; @@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - let r = s.execute("type.retype", &json!({})); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})); if opacity == 1.0 { let r = r.unwrap(); assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); @@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { s.execute("select.set", &json!({"ids": kids})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. for tolerance in [0.0, 0.05] { - if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) { panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); } } @@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_ }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + // The installed fonts left out: what this machine has installed does not change the result. + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter"); s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); @@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the A became type without its period: {r}"), Err(e) => e.to_string(), }; diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..4529cef221 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -90,6 +90,15 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.startup.run", + "Run Startup Scripts", + [], + None, + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + always, + startup_run + ), cmd!( query "script.grants", "List Script File Permissions", @@ -104,7 +113,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + run_prepared(s, request) +} + +fn run_prepared(s: &mut Session, request: script::Request) -> Result { + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -342,6 +361,278 @@ impl Session { } } +/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or +/// cannot be read, when its turn comes. +pub const STARTUP_UNREADABLE: &str = "the startup script could not be read"; + +impl Session { + /// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and + /// never made. + pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.startup_scripts_dir = Some(dir); + } + + /// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web. + pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> { + self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference), + /// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder. + pub fn startup_skip(&self) -> Option<&'static str> { + if !self.prefs.run_startup_scripts { + Some("off") + } else if vectorcraft_plugins::safe_mode::active() { + Some("safeMode") + } else if self.startup_scripts_dir().is_none() { + Some("noFolder") + } else { + None + } + } + + /// The startup script that ran has ended: the launch marker no longer names it. + pub(crate) fn startup_ended(&mut self) { + if let Some(token) = self.startup_loading.take() { + vectorcraft_plugins::safe_mode::loaded(token); + } + } + + /// The running script is a startup script (`script.startup.run`), not the script queued after + /// them. + pub fn startup_script_running(&self) -> bool { + self.startup_loading.is_some() + } + + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a + /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept + /// it from starting, which the Script Console also shows. + fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result { + let name = file_name_of(path); + let text = self.startup_text(path); + let (text, real) = match text { + Ok(read) => read, + Err(message) => { + self.note_unread(&name, &message); + return Err(message); + } + }; + let item = startup_item(path); + self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); + let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = script::Request { + name: name.clone(), + name_given: false, + file: Some(path.to_string_lossy().into_owned()), + checked_real: Some(real), + source: text, + args: serde_json::Map::new(), + fuel, + locale, + answers: vec![], + }; + let runs = self.script_runs; + self.script_start(request).map_err(|e| { + self.startup_ended(); + let message = e.to_string(); + // A run refused before it began, such as with an undo group open, has no console entry yet. + if self.script_runs == runs { + self.note_unread(&name, &message); + } + message + }) + } + + /// The text of the startup script at `path` and its real path, or the error that keeps it from + /// running. + fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> { + let unreadable = || STARTUP_UNREADABLE.to_string(); + let root = self.startup_scripts_dir().ok_or_else(unreadable)?; + let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?; + real.push(path.file_name().ok_or_else(unreadable)?); + // One byte more than a script may have shows that the file is too large. + let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(TOO_LARGE.to_string()); + } + Ok((script_text(&bytes).map_err(|e| e.to_string())?, real)) + } + + /// With no script running, starts the next run `script.startup.run` queued: the next startup + /// script that starts, or the script queued after them. A run that cannot start is kept for + /// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued + /// after them when it ran to its end at once. + pub(crate) fn start_queued(&mut self) -> Option { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + // Each run starts in the file access scope of the request that queued it, which the run + // keeps, and not in the scope of the frame that starts it. + let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); + let mut reply = None; + if self.script_key.is_none() + && let Some(next) = queue.pop_front() + { + match next { + script::startup::Queued::Startup { path, fuel } => { + if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { + self.startup_failures.push((file_name_of(&path), e)); + } + } + script::startup::Queued::Then(params) => { + let prepared = self.script_queue_then.take(); + match scope.clone().run(|| match prepared { + Some(request) => run_prepared(self, request), + None => run(self, ¶ms), + }) { + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), + Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), + } + } + } + } + if queue.is_empty() { + self.script_queue_scope = None; + self.script_queue_then = None; + } + self.script_queue = queue; + reply + } + + /// The runs `script.startup.run` queued that could not start since the last call, as (name, + /// error), in order. + pub fn take_startup_failures(&mut self) -> Vec<(String, String)> { + std::mem::take(&mut self.startup_failures) + } +} + +/// The file name of `path`, or the whole path when it has none. +fn file_name_of(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file +/// name of `path`, else "script". +fn then_name(params: &Value) -> String { + let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()); + match (given("name"), given("path")) { + (Some(name), _) => name.to_string(), + (None, Some(path)) => file_name_of(std::path::Path::new(path)), + (None, None) => "script".to_string(), + } +} + +/// The launch marker's entry for the startup script at `path`: its file and its file name. +fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name } +} + +fn startup_run(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.startup.run"; + let reason = match p.get("reason").and_then(Value::as_str) { + Some(r @ ("launch" | "menu")) => r, + _ => { + let key = "reason"; + return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu"))); + } + }; + let then = match p.get("then") { + None => None, + Some(v @ Value::Object(_)) => Some(v.clone()), + Some(_) => { + let key = "then"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let fuel = match p.get("maxFuel") { + None => script::DEFAULT_FUEL, + Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams { + cmd: C.into(), + msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL), + })?, + }; + if s.script_running() { + return Err(EngineError::Busy); + } + // A chosen script that cannot start ends the request before any startup script runs, and its + // parameters are checked as `script.run` checks them. + if let Some(then) = &then { + super::params::check_params("script.run", then)?; + } + let root = match (s.startup_skip(), s.startup_scripts_dir()) { + (None, Some(root)) => root.to_path_buf(), + (why, _) => { + let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")}); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + return Ok(out); + } + }; + let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; + if let Some(request) = &prepared { + let mut preflight = Session::new(); + if let Err(error) = preflight.script_start(request.clone()) { + s.script_report = None; + return Err(error); + } + } + let folder = root.to_string_lossy().into_owned(); + // The folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; + let listing = script::startup::list(&root); + let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let (disabled, scripts): (Vec<_>, Vec<_>) = + listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); + let disabled: Vec = disabled.iter().map(|p| name_of(p)).collect(); + if s.script_frames { + s.script_queue = + scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); + s.script_queue_then = prepared; + let queued = s.script_queue.len(); + s.startup_failures.clear(); + let then = s.start_queued(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let mut out = json!({ + "reason": reason, + "skipped": false, + "running": s.script_running(), + "queued": queued, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = then; + } + return Ok(out); + } + let (mut ran, mut failed) = (vec![], vec![]); + for path in scripts { + let name = name_of(&path); + match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) { + Ok(_) => ran.push(name), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + let mut out = json!({ + "reason": reason, + "skipped": false, + "ran": ran, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(request) = prepared { + out["then"] = run_prepared(s, request)?; + } + Ok(out) +} + /// The file name a reply names `path` by when the file is outside the automation read roots; `None` /// when a reply may name it whole. fn hidden_name(path: &str) -> Option { @@ -384,16 +675,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 420b3ed1eb..1718b37d7e 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -497,6 +497,32 @@ impl Session { /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain /// stroke. pub fn brushed_strokes_profiled(&self) -> Option { + let st = self.active()?; + let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::>()?; + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } + + /// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width + /// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without + /// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its + /// characters no profile. False with nothing selected, with an object inside a symbol instance + /// selected, and with a target that has no stroke row, which a profile from `stroke.set` would + /// give a plain stroke. + pub fn edited_strokes_profiled(&self) -> bool { + self.edited_strokes(true) + .and_then(|strokes| strokes.into_iter().collect::>>()) + .is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some())) + } + + /// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for + /// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an + /// active Appearance row is skipped with `skip_type`, and makes the result `None` without it. + fn edited_strokes(&self, skip_type: bool) -> Option>> { const C: &str = "stroke.set"; let st = self.active()?; if st.selected_symbol_part().is_some() { @@ -514,16 +540,14 @@ impl Session { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + if skip_type { + continue; + } return None; } - strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + strokes.push(n.appearance.stroke_at(row)); } - if strokes.is_empty() { - return None; - } - // The library is read only when every stroke names a brush. - let lib = vectorcraft_brush::library(&st.doc); - strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + Some(strokes) } } diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs new file mode 100644 index 0000000000..2c5fbbeceb --- /dev/null +++ b/crates/engine/src/cmd/tags.rs @@ -0,0 +1,195 @@ +//! An object's tags: name and value pairs scripts keep on page items (`object.tags`, +//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file +//! keeps them; other formats do not write them. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag}; + +use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req}; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "object.tags", + "Attributes", + [], + None, + "{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change", + has_doc, + list + ), + cmd!( + "object.tag.add", + "Attributes", + [], + None, + "{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}", + has_doc, + add + ), + cmd!( + "object.tag.set", + "Attributes", + [], + None, + "{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}", + has_doc, + set + ), + cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove), + cmd!( + "object.tag.removeAll", + "Attributes", + [], + None, + "{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}", + has_doc, + remove_all + ), + ] +} + +/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide. +fn object(s: &Session, p: &Value, c: &str) -> Result { + let id = NodeId(u64_req(p, "id", c)?); + let d = &s.doc()?.doc; + match d.node(id) { + Some(n) if is_page_item(n) => Ok(id), + Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))), + None => Err(bad(c, format!("no object {}", id.0))), + } +} + +fn is_page_item(n: &Node) -> bool { + !matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide() +} + +/// The tags of `n`. +pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] { + n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice()) +} + +/// The tag `p`'s `tag` names on object `id`: its index among the object's tags. +fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { + let tag = u64_req(p, "tag", c)?; + let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?; + tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) +} + +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None` +/// when `p` leaves it out; a null is an error. +fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + if p.get(key).is_some_and(Value::is_null) { + return Err(bad(c, format!("`{key}` must be a string"))); + } + let t = text_param(p, key, c)?; + if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { + return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); + } + Ok(t) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tags"; + let id = object(s, p, C)?; + let d = &s.doc()?.doc; + let tags = d.node(id).map(tags_of).unwrap_or_default(); + Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::>()})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.add"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?.unwrap_or_default().to_string(); + let value = tag_text(p, "value", C)?.unwrap_or_default().to_string(); + let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len()); + if count >= MAX_TAGS { + return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0))); + } + let tag = s.edit("Attributes", |d, _| { + // A document-wide id: a tag deleted earlier in the run never shares it. + let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?; + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value })); + Ok(tag) + })?; + Ok(json!({"tag": tag})) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.set"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?; + let value = tag_text(p, "value", C)?; + if name.is_none() && value.is_none() { + return Err(bad(C, "give name or value")); + } + let at = tag_index(&s.doc()?.doc, id, p, C)?; + let same = s + .doc()? + .doc + .node(id) + .and_then(|n| tags_of(n).get(at)) + .is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v)); + if same { + return Ok(json!({"changed": false})); + } + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| { + if let Some(t) = a.tags.get_mut(at) { + if let Some(v) = name { + v.clone_into(&mut t.name); + } + if let Some(v) = value { + v.clone_into(&mut t.value); + } + } + }); + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.remove"; + let id = object(s, p, C)?; + let at = tag_index(&s.doc()?.doc, id, p, C)?; + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id)); + if let Some(t) = gone { + d.raise_next_id(t.saturating_add(1)); + } + Ok(()) + })?; + Ok(json!({})) +} + +fn remove_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.removeAll"; + ids_param(p, "ids", C)?; + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + for id in &ids { + if d.node(*id).is_none() { + return Err(bad(C, format!("no object {}", id.0))); + } + } + let tagged: BTreeSet = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect(); + if !tagged.is_empty() { + s.edit("Attributes", |d, _| { + let mut last = 0; + for id in &tagged { + if let Some(n) = d.node_mut(*id) { + last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max)); + } + } + d.raise_next_id(last.saturating_add(1)); + Ok(()) + })?; + } + Ok(json!({"changed": tagged.len()})) +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 734e7fd972..d220deac73 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}", has_doc, type_step ), @@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { }, }; let story = switch_or(p, "story", false, C)?; + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } @@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap. + match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) { + Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } n = if *f == id { t.runs.len() } else { n }; } Ok(n) @@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } } edit::replace_range_styled(&mut t.runs, a, b, &runs); - refresh_bounds(t); + // With Block on, the step goes to the frame's line gap. + match runs.first().filter(|_| matches!(step, Step::Leading)) { + Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 1d3c8f7d7b..d7657df16e 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -500,13 +500,33 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { Kind::Char => { + let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { + if let Some(l) = old_leading + .filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum)))) + { + r.style.leading = l; + } + let was = r.style.leading; r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; + if r.style.leading != was && leading_at.is_none() { + leading_at = Some(off); + } } + off += r.text.len(); } } Kind::Para => { @@ -519,7 +539,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) }) @@ -857,6 +881,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); let clear = bool_or(p, "clearOverrides", false); + // The style sets a leading, or clearing overrides gives the text Normal's. + let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading"))); let style_name = (name != kind.normal()).then(|| name.clone()); // A Type tool range or whole text objects. let text_range = super::typecmd::TextRange::parse(p, &c)?; @@ -883,6 +909,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| { for id in &ids { let Some(t) = text_mut(d, *id) else { continue }; + // The first character given the style's leading. + let mut leading_at = None; match kind { Kind::Char => { let len = vectorcraft_text::edit::runs_len(&t.runs); @@ -903,6 +931,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } + leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten(); } Kind::Para => { let mut v = t.paragraph_styles(); @@ -916,7 +945,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { t.set_paragraph_styles(v); } } - refresh_bounds(t); + // With Block on, a leading the style sets goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 2a62a46374..1c45d37f4c 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); block::block_fit(t); + refresh_fitted(t); +} + +/// The part of [`refresh_bounds`] after Block has fitted the lines. +fn refresh_fitted(t: &mut TextObject) { auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } +/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading` +/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap +/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed. +pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option) { + if block::leading_to_line_gap(t, at, leading) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + +/// The first character a style change over `a..b` of `t` reaches, with both ends on character +/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no +/// character (empty, or inside one character, in text that is not empty). +pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option { + let plain = t.plain_text(); + let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b)); + (a != b || plain.is_empty()).then_some(a.min(b)) +} + +/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker). +pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { + if block::given_leading_to_line_gap(t, at) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { @@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "nothing to change")); } + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); @@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. + let changed = leading.filter(|_| !keep_line_gap).and_then(|l| { + range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l)) + }); + match changed { + Some((at, l)) => refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). @@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod area_tests; mod block; +pub(super) use block::SIZES as BLOCK_SIZES; +pub(super) use block::fit_metrics as block_fit_metrics; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index ef14a57558..4c96d817bc 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -2,11 +2,11 @@ //! typed is set to the frame's width by changing its font size, after every edit //! ([`super::refresh_bounds`]). -use vectorcraft_doc::{TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). -const SIZES: (f64, f64) = (0.1, 1296.0); +pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0); /// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures /// the lines and runs at most one more area layout. @@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { vectorcraft_text::edit::style_at(runs, byte).size } +/// The run that holds the character at `byte` (not the one before it), else the last run. +fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return Some(r); + } + off = end; + } + runs.last() +} + /// The stored size of each line's first character, in one pass over the runs. fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { let mut out = Vec::with_capacity(lines.len()); @@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { .reduce(|a, b| if b.0 > a.0 { b } else { a }) } +/// Whether every character's leading is the one Block gives it: its size plus the frame's line +/// gap (in text space, at least the least size), as [`block_fit`] sets it. +fn block_leadings(t: &TextObject, points: f64) -> bool { + let gap = t.area.block_gaps().1 / points; + let min_leading = SIZES.0 / points; + t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading))) +} + +/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the +/// change is applied to the characters: Block sets each character's leading to its size plus the +/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the +/// character at `at` has the size Block gives it (a size set by the same change included); the gap +/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in +/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap +/// by the change to the character's leading, so every line spreads or tightens by the same amount. +/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size +/// Block gives the character, so the lines are fitted again and the gap worked out again from the +/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the +/// caller lays the text out without fitting it again. Point type, type on a path and area type with +/// Block off are left as they are. +pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option) -> bool { + if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) { + return false; + } + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + t.normalize_paras(); + let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); + for _ in 0..BLOCK_PASSES { + block_fit(t); + // A frame Block could not fit leaves the characters as they were. + if !block_leadings(t, points) { + return false; + } + let Some(run) = run_at(&t.runs, at) else { return true }; + let size = run.style.size; + let new = match leading { + Some(l) => l, + None => { + // Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size + // the font height reference gives the character. An inline graphic keeps its size. + let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) }; + t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() }) + } + }; + let gap = (new - size) * points; + if !gap.is_finite() { + return true; + } + let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP; + let next = gap.clamp(lo, hi); + if (next - t.area.line_gap).abs() <= 1e-9 { + return true; + } + t.area.line_gap = next; + } + false +} + +/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker), read before Block sets it again. +pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { + let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; + leading_to_line_gap(t, at, leading) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its @@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } +pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> { + if !t.dynamic_text { + return None; + } + let TextKind::Area { frame } = &t.kind else { return None }; + let (_, line_gap) = t.area.block_gaps(); + let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?; + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + (cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell)) +} + /// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word /// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line /// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to @@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 { /// has no size. A line that still wraps at its first fit is made smaller, in at most /// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { - if !t.dynamic_text { - return false; - } - let TextKind::Area { frame } = &t.kind else { return false }; - let (_, line_gap) = t.area.block_gaps(); - let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; - let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let Some((points, line_gap, cell)) = fit_metrics(t) else { return false }; let before = t.runs.clone(); - // The room along a line in one cell of the frame, before indents. - let a = &t.area; - let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; - let cells = cells.max(1) as f64; - let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; - if !(cell.is_finite() && cell > 1e-9) { - return t.runs != before; - } - let db = vectorcraft_text::FontDb::global(); let text = t.plain_text(); let lines = typed_lines(&text); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 0354a630b3..eb4afa3760 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { + for command in ["charStyle.setAttrs", "charStyle.edit"] { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + let params = if command == "charStyle.edit" { + json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}}) + } else { + json!({"name": "Body", "attrs": {"leading": 60}}) + }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}"); + } + } +} + /// The size of the character at `byte`. fn size_at(t: &TextObject, byte: usize) -> f64 { super::block::size_at(&t.runs, byte) @@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() { assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); } +/// The distances between the baselines of `t`'s lines. +fn baseline_steps(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect() +} + +/// Block owns each character's leading (its size plus the line gap): a leading change from +/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the +/// line gap by the difference from the first character's leading, in one undo step, and sticks. +#[test] +fn a_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let (first, second) = (t.runs[0].style.size, size_at(&t, 4)); + let steps = baseline_steps(&t); + let n = undo_len(&s); + + // The whole object: the first character's leading becomes the leading given. + s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs); + assert_block(&t); + let wider = baseline_steps(&t); + assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0); + + // A range: measured from the leading of its first character. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens"); + + // Alt+Up/Down steps by the Size/Leading increment. + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9); + + // Auto: the first character's Auto leading, 120% of its size. + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap); + + // The leading the first character already has changes nothing. + let n = undo_len(&s); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap(); + assert_eq!(undo_len(&s), n, "no undo step"); + + // The gap stays within its range. + s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1); + // From a gap that holds every leading at its least, the leading given still applies. + s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 1.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + // A size set with the leading: the gap follows the size Block gives the first character, on an + // empty line (whose size Block keeps) too. + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 50.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.setText", &json!({"text": "\nwords"})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set"); + assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style); + s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + + // Scaled type: the leading given and the line gap are in document points. + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let points = text(&s, id).style_scale().unwrap().points; + s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap(); + let t = text(&s, id); + let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points); + assert!((lead - 150.0).abs() < 1e-6, "leading {lead}"); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// Without Block (point type, and area type with Block off) a leading change sets the +/// characters' leading and leaves the line gap. +#[test] +fn a_leading_change_without_block_sets_the_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one\ntwo"); + s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 5.0); + assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0))); + let id = point(&mut s, "one\ntwo", json!({})); + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 0.0); + assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment)); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; assert!(used <= bound, "point type: {used} layouts"); } + +/// Area type with Block on, its lines at different sizes, and a line gap of 0. +fn block_text(s: &mut Session) -> u64 { + let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(text(s, id).area.line_gap, 0.0); + id +} + +/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run +/// end, so it is asked for the end of the character). +fn leading_at(t: &TextObject, byte: usize) -> Option { + vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading +} + +/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to +/// the leading of the range's first character, and the range keeps the leading given. +#[test] +fn a_range_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); + // Reset Panel's form: the leading is set and Block keeps the line gap. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); +} + +/// A range inside one character styles nothing, so it leaves the line gap. +#[test] +fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + let gap = text(&s, id).area.line_gap; + let range = json!({"start": 0, "end": 1}); + let mut setstyle = json!({"ids": [id], "leading": 50}); + let mut setrange = json!({"id": id, "leading": 50}); + let mut apply = json!({"name": "Loose", "id": id}); + for p in [&mut setstyle, &mut setrange, &mut apply] { + p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone()); + } + for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + assert_eq!(text(&s, id).area.line_gap, gap, "{c}"); + } +} + +/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. +#[test] +fn a_leading_step_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9)); +} + +/// A character style edited to set a leading while Block text uses it moves the line gap; a style +/// without a leading leaves the gap. +#[test] +fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style"); + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); + assert_spread(&t); + + // Once Block has given the characters other leadings than the style's (a new line gap here), a + // new leading in the style still applies: Block's leadings are not overrides. + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + let gap = text(&s, id).area.line_gap; + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != gap, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_spread(&t); +} + +/// Every character's leading is its size plus the frame's line gap (at least the least size), so +/// every line spread or tightened by the same amount. +fn assert_spread(t: &TextObject) { + let gap = t.area.line_gap; + let least = super::block::SIZES.0; + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs); +} + +/// A character style that sets a leading, applied to Block text, moves the line gap. +#[test] +fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + assert_spread(&t); + + // Clearing overrides gives the text the leading of the Normal style. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); + let t = text(&s, id); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); + assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap); + assert_spread(&t); +} + +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value; +/// Block then gives every other character its size plus that gap. +#[test] +fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); + assert_spread(&t); +} + +/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not +/// a leading change: the line gap stays, and Block gives every character its size plus the gap. +#[test] +fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() { + let mut s = session(); + let source = point(&mut s, "source", json!({})); + s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); + let id = block_text(&mut s); + let gap = text(&s, id).area.line_gap; + s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, gap); + assert_spread(&t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index b66a50bc19..70aa0ee07c 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index f578bcd61d..5356f5b249 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions use vectorcraft_render::encode::web::{self, ColorSort}; use vectorcraft_render::encode::{gif, jpeg, png}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from}; const C: &str = "document.exportForWeb"; @@ -45,6 +45,24 @@ pub fn specs() -> Vec { has_doc, preview ), + cmd!( + "document.exportForWeb.saveColorTable", + "Save Color Table", + [], + None, + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change", + has_doc, + save_color_table + ), + cmd!( + query "webExport.loadColorTable", + "Load Color Table", + [], + None, + "{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered", + always, + load_color_table + ), cmd!( query "webExport.optimizeToFileSize", "Optimize to File Size", @@ -1253,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let st = s.doc()?; - let doc = &st.doc; - let failed = vectorcraft_render::decode_failures(); - let r = render(doc, &settings).map_err(|e| bad(P, e))?; - let warnings = undecoded(failed); - let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); - let o = match p.get("slice").and_then(Value::as_u64) { - Some(n) => { - let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?; - let [x0, y0, x1, y1] = c.px; - optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings) - } - None => optimize(doc, &r.rgba, r.width, r.height, &settings), - } - .map_err(|e| bad(P, e))?; + let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1294,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The file Save writes with some settings, as the preview shows it. +struct Shown { + o: Optimized, + /// The images an export writes (0 when they were not counted). + images: usize, + /// The export's warnings. + warnings: Vec<&'static str>, +} + +/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, +/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an +/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0, +/// and selected slices with none selected are not an error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result { + let slice = match p.get("slice") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), + }; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, settings).map_err(|e| bad(cmd, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let cells = if count_images || slice.is_some() { + let selected = super::slices::selected_slices(doc, &st.selection); + cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))? + } else { + vec![] + }; + let images = if count_images { + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1) + } else { + 0 + }; + let o = match slice { + Some(n) => { + let c = + cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?; + let [x0, y0, x1, y1] = c.px; + optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings) + } + None => optimize(doc, &r.rgba, r.width, r.height, settings), + } + .map_err(|e| bad(cmd, e))?; + Ok(Shown { o, images, warnings }) +} + +// ---------- color table files ---------- + +/// The extension of a color table file. +pub const COLOR_TABLE_EXT: &str = "act"; +/// The size of a color table file with its color count and transparent entry: 256 RGB triples +/// (768 bytes), then the two numbers, each two bytes, most significant byte first. +pub const ACT_LEN: usize = 772; +/// The size of a color table file of 256 RGB triples alone. +const ACT_COLORS_LEN: usize = 768; +/// The transparent entry of a color table file that has none. +const ACT_NO_TRANSPARENT: u16 = 0xFFFF; + +/// The error for bytes that are not a color table file. +const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors"; + +/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each +/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number +/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most +/// significant byte first. Colors past the 256th are left out. +pub fn act_bytes(colors: &[TableColor]) -> Vec { + let colors = &colors[..colors.len().min(256)]; + let mut out = vec![0u8; ACT_LEN]; + for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) { + *slot = c.color; + } + // At most 256 colors: both numbers fit in two bytes. + let count = colors.len() as u16; + let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16); + out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes()); + out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes()); + out +} + +/// The colors of a color table file and its transparent entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActTable { + /// The colors the file uses, in its order. + pub colors: Vec<[u8; 3]>, + /// The index of the transparent entry, when the file names one of `colors`. + pub transparent: Option, +} + +/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used +/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names +/// no entry. Any other size, or a count of 0 or above 256, is an error. +pub fn read_act(bytes: &[u8]) -> std::result::Result { + let (count, transparent) = match bytes.len() { + ACT_COLORS_LEN => (256, None), + ACT_LEN => { + let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + (at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2))) + } + _ => return Err(NOT_A_TABLE.into()), + }; + if !(1..=256).contains(&count) { + return Err(NOT_A_TABLE.into()); + } + let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec(); + Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) }) +} + +/// `settings` with the color table `t` loaded: its colors other than the transparent entry become +/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the +/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and +/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is +/// written as it is, in the file's order. A table whose only color is its transparent entry loads +/// that color. +pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings { + let mut s = settings.clone(); + let mut palette: Vec = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect(); + if palette.is_empty() { + palette = t.colors.iter().map(|c| hex(*c)).collect(); + } + s.colors = (t.colors.len() as u16).clamp(2, 256); + s.web_snap = 0; + s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() }; + s +} + +/// `cmd`'s error for a format without a color table. +fn no_table(cmd: &str, f: WebFormat) -> super::EngineError { + let format = f.id(); + bad(cmd, format!("`{format}` has no color table: use gif or png8")) +} + +fn save_color_table(s: &mut Session, p: &Value) -> Result { + const P: &str = "document.exportForWeb.saveColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(P, e))?; + if !settings.format.palette() { + return Err(no_table(P, settings.format)); + } + let path = text_param(p, "path", P)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`")); + } + let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; + let bytes = act_bytes(&o.colors); + let mut out = json!({ + "colors": o.colors.len().min(256), + "transparentIndex": o.colors.iter().position(|c| c.transparent), + "bytes": bytes.len(), + "warnings": warnings, + }); + match path { + Some(path) => { + super::fileio::write_file(&path, &bytes)?; + out["path"] = json!(path); + } + None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)), + } + Ok(out) +} + +fn load_color_table(s: &mut Session, p: &Value) -> Result { + const L: &str = "webExport.loadColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(L, e))?; + if !settings.format.palette() { + return Err(no_table(L, settings.format)); + } + // One byte more than a color table shows a file that is too long. + let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) { + (Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?, + (None, Some(b64)) => { + // Text past the base64 of the longest table makes the file too long. + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 { + return Err(bad(L, NOT_A_TABLE)); + } + super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))? + } + _ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")), + }; + let t = read_act(&bytes).map_err(|e| bad(L, e))?; + let loaded = with_table(&settings, &t); + Ok(json!({ + "colors": t.colors.iter().map(|c| hex(*c)).collect::>(), + "transparentIndex": t.transparent, + "settings": loaded.to_json(), + })) +} + // ---------- Optimize to File Size ---------- /// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index eef620521f..9c80d284ca 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -53,6 +53,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -410,6 +413,7 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), @@ -593,7 +597,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -609,8 +615,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -621,9 +629,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 379b8837f4..791143f53b 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 6dd833263b..221106ec0d 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 04461b332c..b1a7d37277 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; +pub use cmd::gradient::StopOwner; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; @@ -218,6 +219,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder + /// ([`Session::attach_startup_scripts_dir`]). + startup_scripts_dir: Option, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, @@ -310,6 +314,9 @@ pub struct Session { /// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or /// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]). pub(crate) trace_hand_off: Option, + /// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or + /// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]). + pub(crate) retype_hand_off: Option, /// Whether a click or drag of the place cursor asks the frontend to place its file /// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the /// file off the UI thread. False: the file is placed at once. @@ -338,6 +345,19 @@ pub struct Session { /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, + /// The runs `script.startup.run` queued in the app, each started when the run before it ends + /// ([`Session::script_pump`]). + pub(crate) script_queue: std::collections::VecDeque, + /// The file access scope of the request that queued [`Self::script_queue`], in which each queued + /// run starts and is read. + pub(crate) script_queue_scope: Option, + pub(crate) script_queue_then: Option, + /// While a startup script runs: the launch marker's entry naming it + /// ([`vectorcraft_plugins::safe_mode::loading`]). + pub(crate) startup_loading: Option, + /// The queued runs that could not start, as (name, error), until the frontend takes them + /// ([`Session::take_startup_failures`]). + pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 87d6c6df80..1a7b78a91b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -71,6 +71,10 @@ pub struct Prefs { pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, + /// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the + /// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by + /// default. + pub run_startup_scripts: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -496,6 +500,7 @@ impl Default for Prefs { show_tool_tips: true, show_tool_cards: false, show_external_script_warning: true, + run_startup_scripts: false, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9c137c96bd..46ca2824d4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -66,6 +66,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod tags; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -1353,7 +1355,7 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], @@ -1599,16 +1601,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in -/// is hidden or locked. Its name and note may still change. -fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { +/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on +/// locked artboards. Names and notes may still change. +fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); - d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) { + Some("a layer it is in is hidden or locked") + } else if on_locked_artboard(h, st, item.id) { + Some("it is on a locked artboard") + } else { + None + }; + why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why)) }); match refused { - Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))), None => Ok(()), } } @@ -1619,7 +1628,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1629,7 +1638,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1657,7 +1666,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { (now, keeps_other) }); if now.is_none() || keeps_other { - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; } set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } @@ -1741,7 +1750,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); @@ -1778,7 +1788,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { @@ -2024,7 +2035,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused, and so is an object in a hidden or locked layer. +/// compound path is refused. The item must be selectable and outside hidden or locked layers and +/// locked artboards. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -2037,7 +2049,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); @@ -2200,6 +2213,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -2220,6 +2234,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("parent", get(l, item_parent)), ("name", property(l, item_name, item_set_name)), ("note", property(l, item_note, item_set_note)), + ("tags", get(l, tags::item_tags)), ("hidden", property(l, item_hidden, item_set_hidden)), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), @@ -2248,7 +2263,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "layer", "pixelAligned", "sliced", - "tags", "uRL", "uuid", "visibilityVariable", @@ -2272,6 +2286,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), None, )); + classes.extend(tags::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; // The application's members a script may name without `app.`, assigned as `app.` is. realm.define_host_globals(vec![ diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs new file mode 100644 index 0000000000..c62f5eae81 --- /dev/null +++ b/crates/engine/src/script/dom/tags.rs @@ -0,0 +1,306 @@ +//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages +//! and +//! describe them: name and value pairs on a +//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0. +//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items, +//! and cannot add a tag, since a tag belongs to a page item. +//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and +//! `getByName` gives the first tag with the name. +//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags. +//! - A tag that was deleted, or whose page item was, throws an error on every member. + +use std::ops::ControlFlow; + +use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get, + handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc, +}; +use crate::NodeId; +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref}; + +/// The error for a tag that was deleted, or that came from an earlier run. +pub const STALE_TAG: &str = "Stale tag"; +/// The error of `Document.tags.add()`. +pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's"; + +/// What a `Tags` collection lists the tags of. +#[derive(Clone, Copy)] +enum Owner { + Item(Item), + Doc(Doc), +} + +/// The owner of the `Tags` collection `d` names. +fn owner_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + [run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)), + _ => Err(HostError::Type("this is not a Tags collection".into())), + } +} + +/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must +/// still be in its document. +fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); + if !alive { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks. +/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the +/// number of page items read. +fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> { + match owner { + Owner::Item(item) => with_doc(h, item.doc, |_, st| { + if let Some(n) = st.doc.node(item.id) { + for t in crate::cmd::tags::tags_of(n) { + if f(item.id, t).is_break() { + break; + } + } + } + Ok(()) + }), + Owner::Doc(doc) => with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + for id in ids.iter() { + if let Some(n) = st.doc.node(*id) { + for t in crate::cmd::tags::tags_of(n) { + if f(*id, t).is_break() { + return Ok(()); + } + } + } + } + Ok(()) + }), + } +} + +/// The first tag `owner` lists for which `pick` holds: its page item and its id. +fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result, HostError> { + let mut found = None; + each(h, owner, |id, t| { + if pick(t) { + found = Some((id, t.id)); + return ControlFlow::Break(()); + } + ControlFlow::Continue(()) + })?; + Ok(found) +} + +fn doc_of_owner(owner: Owner) -> Doc { + match owner { + Owner::Item(i) => i.doc, + Owner::Doc(d) => d, + } +} + +fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { + let [high, low] = id_parts(id); + let [tag_high, tag_low] = id_parts(NodeId(tag)); + host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) +} + +/// `PageItem.tags`. +pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + let [high, low] = id_parts(item.id); + Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) +} + +/// `Document.tags`. +pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Tags", &[float(h.run), float(doc.uid)])) +} + +// ---- Tags ---- + +fn tags_length(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut count = 0u64; + each(h, owner, |_, _| { + count += 1; + ControlFlow::Continue(()) + })?; + Ok(num(float(count))) +} + +fn tags_parent(h: &Host, a: &[Data]) -> Answer { + match owner_of(h, arg(a, 0))? { + Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))), + Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)), + } +} + +fn tags_at(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let mut left = i; + let found = find(h, owner, |_| { + let here = left == 0; + left = left.wrapping_sub(1); + here + })?; + Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag))) +} + +fn tags_by_name(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let found = find(h, owner, |t| t.name == *name)?; + found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn tags_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => tags_by_name(h, a), + Data::Number(_) => match tags_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `tags.add()`: a new tag with an empty name and value after the item's other tags. +fn tags_add(h: &Host, a: &[Data]) -> Answer { + let item = match owner_of(h, arg(a, 0))? { + Owner::Item(item) => item, + Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())), + }; + edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?; + // The new tag is the item's last. Its id is read from the document, since the command's answer + // gives it as a number, which is exact only up to 2^53. + let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id))); + let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?; + Ok(tag_ref(h, item.doc, item.id, tag)) +} + +/// `tags.removeAll()`: deletes every tag in the collection, in one command. +fn tags_remove_all(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut ids: Vec = Vec::new(); + each(h, owner, |id, _| { + if ids.last() != Some(&id.0) { + ids.push(id.0); + } + ControlFlow::Continue(()) + })?; + if !ids.is_empty() { + let doc = doc_of_owner(owner); + on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?; + } + Ok(Data::Undefined) +} + +// ---- Tag ---- + +/// A tag: its page item and its id there. +#[derive(Clone, Copy)] +struct TagRef { + item: Item, + tag: u64, +} + +/// The tag `d` names, which must still be on its page item. +fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> { + let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) }; + let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) }; + let item = resolve_item(h, *run, *uid, *high, *low)?; + let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0; + let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned())); + let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?; + Ok((TagRef { item, tag }, t)) +} + +fn tag_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.name)) +} + +fn tag_value(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.value)) +} + +/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when +/// it already has it. +fn set_text(h: &Host, a: &[Data], key: &str) -> Answer { + let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) }; + if v.len() > MAX_TAG_TEXT { + return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes"))); + } + let (t, now) = tag_of(h, arg(a, 0))?; + let same = if key == "name" { now.name == *v } else { now.value == *v }; + if !same { + edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?; + } + Ok(Data::Undefined) +} + +fn tag_set_name(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "name") +} + +fn tag_set_value(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "value") +} + +fn tag_parent(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id))) +} + +fn tag_remove(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?; + Ok(Data::Undefined) +} + +/// `Tags.typename`, which throws like every other member once the collection's owner is gone. +fn tags_typename(h: &Host, a: &[Data]) -> Answer { + owner_of(h, arg(a, 0))?; + Ok(text("Tags")) +} + +/// `Tag.typename`, which throws like every other member once the tag is gone. +fn tag_typename(h: &Host, a: &[Data]) -> Answer { + tag_of(h, arg(a, 0))?; + Ok(text("Tag")) +} + +/// The `Tags` and `Tag` classes. +pub(super) fn classes(l: &Link) -> Vec { + let tags: Vec<(String, HostMember)> = named(vec![ + ("typename", get(l, tags_typename)), + ("length", get(l, tags_length)), + ("parent", get(l, tags_parent)), + ("index", method(l, tags_index)), + ("getByName", method(l, tags_by_name)), + ("add", method(l, tags_add)), + ("removeAll", method(l, tags_remove_all)), + ]); + let tag = named(vec![ + ("typename", get(l, tag_typename)), + ("name", property(l, tag_name, tag_set_name)), + ("value", property(l, tag_value, tag_set_value)), + ("parent", get(l, tag_parent)), + ("remove", method(l, tag_remove)), + ]); + vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)] +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..9d4c90aed4 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// The spellings of each are tried in order, the script's first, and the first pair that some grant +/// holds is the one removed, so a grant kept under the spellings given first is removed without the +/// grants of later ones. → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..9ec36c2447 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -237,7 +237,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool { /// Does Windows mark the file or folder of `m` hidden or system? #[cfg(windows)] -fn hidden_meta(m: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool { use std::os::windows::fs::MetadataExt as _; const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; m.file_attributes() & HIDDEN_OR_SYSTEM != 0 @@ -245,13 +245,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool { /// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. #[cfg(not(windows))] -fn hidden_meta(_: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool { false } /// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows /// marks hidden or system, which a listing leaves out. -fn plain(path: &Path, folder: bool, shown: bool) -> bool { +pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { std::fs::symlink_metadata(path) .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f6f2bd36f6..c5fffb6574 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -72,6 +72,7 @@ use crate::{ pub mod files; pub mod folder; +pub mod startup; /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; @@ -186,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String { } /// A request to run a script. +#[derive(Clone)] pub(crate) struct Request { /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, @@ -1716,9 +1718,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1931,9 +1934,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -1941,9 +1945,16 @@ impl Session { } /// Stops the running script at once and puts everything back, with the report of a stopped run - /// ([`Self::script_report`]). False with none running. + /// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are + /// not started, and the report stays the last run's. False with none running or queued. pub fn script_abandon(&mut self) -> bool { - let Some(key) = self.script_key.take() else { return false }; + // The runs queued after it are not started. + let queued = !self.script_queue.is_empty(); + self.script_queue.clear(); + self.script_queue_scope = None; + self.script_queue_then = None; + self.startup_ended(); + let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); return true; @@ -1975,6 +1986,16 @@ impl Session { cmd::compositefonts::sync(self); } + /// A script named `name` that did not start because its file could not be read as a script: + /// the Script Console gets a run with a start line, `message` as its error and an end line. + pub(crate) fn note_unread(&mut self, name: &str, message: &str) { + self.script_runs += 1; + let name = console::line_name(name); + for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] { + self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false); + } + } + /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { @@ -2194,8 +2215,33 @@ impl Session { } /// Advances the running script by one slice. `None` while it is still running; otherwise the - /// run has ended: its report, or the error that ended it, with the documents put back. + /// run has ended: its report, or the error that ended it, with the documents put back. When + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; + self.startup_ended(); + Some(result) + } + + /// [`Self::script_pump`] for the running script alone. + fn pump_one(&mut self) -> Option> { let key = self.script_key.take()?; let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Internal); diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs new file mode 100644 index 0000000000..e20e67de3f --- /dev/null +++ b/crates/engine/src/script/startup.rs @@ -0,0 +1,126 @@ +//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when +//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of +//! one of them when its turn comes ([`read`]). +//! +//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a +//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names +//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names +//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too. +//! The files are sorted by name without regard to case, then by name. +//! +//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and +//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found +//! and says so ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::folder; + +/// What a Startup Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The scripts, in the order they run. + pub scripts: Vec, + /// Some scripts may be missing: a limit was reached or an entry could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not +/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes? +pub fn takes(name: &str) -> bool { + !name.starts_with('.') + && name.len() <= folder::MAX_NAME_BYTES + && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) +} + +/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist +/// gives an empty listing. +pub fn list(root: &Path) -> Listing { + let start = std::time::Instant::now(); + list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +} + +/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); +/// `elapsed` says how long the listing has taken. +pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + if root.to_str().is_none() { + return unreadable; + } + let Ok(entries) = std::fs::read_dir(root) else { return unreadable }; + let mut listing = Listing::default(); + let mut names: Vec = vec![]; + for (visited, entry) in entries.enumerate() { + if visited >= limits.entries || elapsed() > limits.time { + listing.truncated = true; + break; + } + let Ok(entry) = entry else { + listing.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + if !takes(&name) { + continue; + } + let Ok(kind) = entry.file_type() else { + listing.truncated = true; + continue; + }; + if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { + continue; + } + names.push(name); + } + names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + if names.len() > limits.scripts { + listing.truncated = true; + names.truncate(limits.scripts); + } + listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); + listing +} + +/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in +/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + if path.parent() != Some(root) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true) +} + +/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for +/// it before the read and again after it, or it cannot be read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} + +/// A run `script.startup.run` queued for the app, which starts it when the run before it ends. +#[derive(Clone, Debug, PartialEq)] +pub enum Queued { + /// A startup script, read when its turn comes, with its `maxFuel`. + Startup { path: PathBuf, fuel: u64 }, + /// The script that runs after the startup scripts, as `script.run`'s parameters. + Then(serde_json::Value), +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index d1e51ea792..2890618dd8 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -111,6 +111,7 @@ impl Session { plugin_loads: Default::default(), plugin_loads_in_background: false, scripts_dir: None, + startup_scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -139,6 +140,7 @@ impl Session { place_queue_loads: 0, image_hand_off: None, trace_hand_off: None, + retype_hand_off: None, place_cursor_requests: false, package_hand_off: None, screens_hand_off: None, @@ -177,6 +179,11 @@ impl Session { script_console: Default::default(), script_runs: 0, script_frames: false, + script_queue: Default::default(), + script_queue_scope: None, + script_queue_then: None, + startup_loading: None, + startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index c82f7ca32c..e723be129b 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -200,6 +200,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.revealing(|s| s.select_unwatched(f)) @@ -510,6 +533,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -569,6 +593,8 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index eb7de6e7c4..85dcfcdf5f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -92,7 +92,7 @@ impl Session { fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. @@ -454,6 +454,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f581be4dd6..c87b51fddd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -183,6 +183,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_tags; mod scripts; mod segment_nudge; mod select_effects; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 44b49f148d..b967e6e3ed 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -270,6 +270,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); } +/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member +/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members' +/// profiles. With an object without a stroke row among the targets the answer is false, since a +/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row +/// is left out. +#[test] +fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(!s.edited_strokes_profiled(), "neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(s.edited_strokes_profiled(), "the second one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + assert!(s.edited_strokes_profiled(), "the profiled member alone"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + assert!(!s.edited_strokes_profiled(), "an object without a stroke row"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [t.0, b.0]})); + assert!(s.edited_strokes_profiled(), "type is left out"); + run(&mut s, "select.set", json!({"ids": []})); + assert!(!s.edited_strokes_profiled(), "nothing selected"); +} + /// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. #[test] fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index 028ffa6487..91a6b9e9ff 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -254,3 +254,86 @@ fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() { assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})"); } } + +/// The anchors of `id`'s path. +fn anchors_of(s: &Session, id: NodeId) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect() +} + +/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path; +/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle +/// is; anything else is an error that draws nothing. +#[test] +fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap(); + let id = id_of(&v); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}"); + let anchors = anchors_of(&s, id); + assert_eq!(anchors.len(), 4); + assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}"); + assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0))); + + let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap()); + let upright = anchors_of(&s, upright); + s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap(); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(anchors_of(&s, id_of(&v)), upright); + + let count = object_count(&s); + for bad in [json!("points"), json!(4), json!(true)] { + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err()); + } + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err()); + assert_eq!(object_count(&s), count); +} + +/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the +/// circle with standard anchors, or with its anchors where it touches at a standard position, fits, +/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge. +#[test] +fn the_canvas_check_measures_the_path_drawn() { + let mut s = session(); + let edge = vectorcraft_doc::MAX_COORD - 0.05; + let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap(); + let path = id_of(&v); + let count = object_count(&s); + let near_right = json!({"id": path.0, "segment": 1, "t": 0.79}); + assert!(s.execute(C, &near_right).is_ok()); + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok()); + let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err(); + assert!(e.to_string().contains("past the canvas"), "{e}"); + assert_eq!(object_count(&s), count + 2); +} + +/// The tool's options are saved with the preferences and come back in the next session. +#[test] +fn the_tool_options_are_saved_with_the_preferences() { + let mut s = session(); + s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + let changed = + json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false}); + for (k, v) in changed.as_object().unwrap() { + s.set_tool_option(k, v); + } + s.select_tool("selection", ViewInfo::default()).unwrap(); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + assert_eq!(next.tool_options(), changed); +} + +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than +/// the circle's at an anchor, so a larger radius, and the result is not nominal. +#[test] +fn without_constant_radius_an_arc_gives_its_own_curvature() { + let mut s = session(); + let path = circle(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap(); + assert_eq!(v["nominal"], json!(false)); + assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}"); +} diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..56580097f2 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -2,7 +2,7 @@ //! shared between steps, and past a memory budget the oldest steps go (never the last few). use serde_json::json; -use vectorcraft_doc::{Appearance, Node}; +use vectorcraft_doc::{Appearance, Node, NodeId}; use vectorcraft_geom::shapes; use crate::*; @@ -461,3 +461,69 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} + +/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at +/// the index: with one target lacking it, the step keeps none, and the target that has it is still +/// edited. +#[test] +fn effect_options_keep_the_effect_only_when_every_target_has_it() { + let mut s = session_with_rects(2); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap(); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + let radius = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64() + }; + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect"); + assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited"); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap(); + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect"); + assert_eq!(radius(&s), Some(9.0)); +} diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 96a2aedff8..4641467aa4 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,6 +910,54 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } +/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them +/// as they are and adds no undo step. +#[test] +fn relative_rounding_without_live_corners_adds_no_undo_step() { + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.expandShape", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); + assert_eq!(steps(&s), n, "a plain path: no change"); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path"); + let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let n = steps(&s); + run(&mut s, json!({"ids": [e], "relativeRadii": true})); + assert_eq!(steps(&s), n, "an ellipse: no change"); +} + +/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the +/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a +/// smaller one adds one. +#[test] +fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + let n = steps(&s); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "past the maximum: one undo step"); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0)); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "the same radius again: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max})); + assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max / 2.0})); + assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step"); + // On a large shape a small radius is a fraction below 1e-9, and still a change. + let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap(); + run(&mut s, json!({"ids": [big], "relativeRadii": true})); + let n = steps(&s); + run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001})); + assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step"); +} + /// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round, /// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag. #[test] diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index d9945fa723..e118dfc272 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -775,6 +775,8 @@ fn an_arc_drag_shows_the_protractor() { let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { key(&mut s, ToolKey::Escape); + // With the last path selected, a press on its anchors would edit it instead of drawing. + s.execute("select.set", &json!({"ids": []})).unwrap(); s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); click(&mut s, 100.0, 100.0); click(&mut s, 200.0, 100.0); @@ -1372,3 +1374,335 @@ fn path_quick_pen_replaces_the_points_after_keep() { let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); } + +/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen +/// chosen and no path being drawn. +fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId { + let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(s); + id +} + +fn points(s: &Session) -> Vec { + only_path(s).anchors.iter().map(|a| a.p).collect() +} + +fn shift_click(s: &mut Session, x: f64, y: f64) { + let v = view(); + let mods = Mods { shift: true, ..Mods::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap(); + } +} + +/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on +/// the circle through its ends and its middle? +fn segment_is_circular(sp: &SubPath, i: usize) -> bool { + use vectorcraft_geom::ParamCurve; + let seg = sp.segment(i); + let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let sq = |p: Point| p.x * p.x + p.y * p.y; + let center = pt( + (sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d, + (sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d, + ); + let r = center.distance(a); + [0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3) +} + +/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in +/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a +/// circular arc. +#[test] +fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}])); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + let undo = undo_steps(&s); + press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]); + assert_eq!(undo_steps(&s), undo + 1); + let sp = only_path(&s); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]); + assert!(sp.segment_is_line(0), "{:?}", sp.anchors); + assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on a segment of the selected path moves that segment's two ends. +#[test] +fn a_drag_on_a_segment_moves_its_ends() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}])); + press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]); + assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag that starts on an end of the selected open path moves that end; a click there still +/// goes on drawing from it. +#[test] +fn a_drag_on_an_open_end_moves_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]); + assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected"); + click(&mut s, 350.0, 350.0); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole"); + click(&mut s, 350.0, 450.0); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); +} + +/// A press let go past the drag distance moves what it holds even when no drag event went that +/// far: an inner anchor moves, and an open end moves instead of going on drawing. +#[test] +fn a_release_past_the_drag_distance_moves_the_anchor() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]); + assert_eq!(undo_steps(&s), undo + 2); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on an anchor or a segment that comes back to where it started moves nothing and records +/// no undo step. +#[test] +fn a_drag_back_to_its_start_records_no_undo_step() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + for at in [(200.0, 100.0), (250.0, 100.0)] { + press(&mut s, &[at, (at.0, at.1 + 50.0), at]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); + assert_eq!(undo_steps(&s), undo, "press at {at:?}"); + } + // Choosing another tool during such a drag records none either. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo); +} + +/// When another command changes the selection while the press is down, neither a click nor a drag +/// selects or moves the anchor the press found. +#[test] +fn a_selection_change_during_an_edit_press_stops_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for drag in [false, true] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let y = if drag { 150.0 } else { 100.0 }; + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}"); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// When another command edits the path while the press is down, neither a drag nor a release past +/// the drag distance moves the anchor the press found. +#[test] +fn an_edit_during_an_edit_press_stops_the_move() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (drag, x) in [(true, 90.0), (false, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap(); + let undo = undo_steps(&s); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// An edit made by another command during an anchor drag stays: the rest of the drag and the +/// release move nothing more, and one undo step holds the move as last shown with the edit. +#[test] +fn an_edit_during_an_anchor_drag_stays() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap(); + assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!s.in_interaction(), "the step is committed"); + // Escape after such an edit keeps it too. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap(); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]); + assert!(!s.in_interaction(), "the step is committed"); +} + +/// When another command edits the path while a click is down, the click neither selects the +/// anchor nor goes on drawing from the open end it found. +#[test] +fn an_edit_during_an_edit_click_does_nothing() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}"); + } + // The open end was not taken up, so the next click starts a new path. + click(&mut s, 400.0, 200.0); + assert_eq!(paths(&s).len(), 2); +} + +/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the +/// context menu's Delete) then removes both. +#[test] +fn clicks_select_anchors_for_delete() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}])); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked(&s), [(0, 1)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1), (0, 2)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again"); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(undo_steps(&s), undo, "selecting is no edit"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); +} + +/// The first Shift-click on an anchor of a path selected whole selects that anchor alone. +#[test] +fn a_first_shift_click_selects_the_anchor_alone() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole"); + shift_click(&mut s, 200.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1)]); +} + +/// A drag on a segment moves its two ends alone, also when they are selected with another anchor. +#[test] +fn a_segment_drag_moves_only_its_ends() { + let mut s = session(); + let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces); + click(&mut s, 300.0, 300.0); + shift_click(&mut s, 300.0, 400.0); + shift_click(&mut s, 100.0, 400.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]); + press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag on a segment whose two ends are already selected as anchors selects the segment, so +/// Delete then cuts that connection and keeps both anchors. +#[test] +fn a_segment_drag_from_its_selected_ends_selects_the_segment() { + let mut s = session(); + let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces); + click(&mut s, 200.0, 100.0); + shift_click(&mut s, 300.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2)]); + press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]); + let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(segments, [(0, 1)], "the segment is selected"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] { + assert!(left.contains(&p), "{p:?} stays: {left:?}"); + } +} + +/// A click on an open end of another path, in front of the selected path, that lies on a segment +/// of the selected path goes on drawing from that end. +#[test] +fn an_open_end_on_a_selected_segment_continues_its_path() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 200.0, 300.0); + click(&mut s, 250.0, 250.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let ends: Vec = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]); +} + +/// Escape during a drag puts the anchor back, and the release then changes nothing. +#[test] +fn escape_takes_back_an_anchor_drag() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let (before, undo) = (points(&s), undo_steps(&s)); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + assert_ne!(points(&s), before, "the drag previews"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), before); + assert_eq!(undo_steps(&s), undo); + assert_eq!(paths(&s).len(), 1); +} + +/// While a path is being drawn, a press on one of its points adds a piece as before; the editing +/// starts only after Escape ends the path. +#[test] +fn a_press_while_drawing_adds_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]); + assert_eq!(points(&s).len(), 4, "a piece added"); + key(&mut s, ToolKey::Escape); + press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]); + let got = points(&s); + assert_eq!(got.len(), 4); + assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..c1aa77e6a6 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -909,6 +909,18 @@ fn assigning_the_same_objects_clears_the_key_and_guides() { assert!(s.active().unwrap().selection.guides.is_empty()); } +/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError"), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}"); + } +} + #[test] fn a_page_item_with_a_large_id_keeps_its_id() { let mut s = Session::new(); @@ -1325,6 +1337,54 @@ fn duplicate_refuses_hidden_or_locked_art() { assert!(order.contains(&a) && order.contains(&b)); } +#[test] +fn setters_refuse_art_on_a_locked_artboard() { + let (mut s, _, _) = doc(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], refused = [];\ + var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\ + function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\ + function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\ + for(var i=0;i = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]); + assert!(listing.truncated); +} diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..0f05c839c4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,63 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index c12653602f..9489921682 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -393,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + 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 source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn every_script_reads_e4x_and_has_the_xml_objects() { let dir = fresh_folder("e4x"); diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs new file mode 100644 index 0000000000..cc477f27fa --- /dev/null +++ b/crates/engine/src/tests/script_tags.rs @@ -0,0 +1,286 @@ +//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands +//! they run. + +use serde_json::{Value, json}; +use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +/// A document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0); + let b = rect(&mut s, 100.0, 100.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> { + let d = &s.active().unwrap().doc; + crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect() +} + +#[test] +fn tags_are_added_named_read_and_removed_in_one_undo_step() { + let (mut s, a, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var item = app.activeDocument.pageItems[1], tags = item.tags;\ + vc.log(tags.typename); vc.log(tags.length);\ + var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ + t.name = 'size'; t.value = 'XL';\ + var u = tags.add(); u.name = 'size'; u.value = 'S';\ + var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\ + vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\ + vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\ + u.remove(); vc.log(tags.length); vc.log(tags[1].name);", + ); + let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]); + assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")])); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(tags(&s, a).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(tags(&s, a).len(), 2); + log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();"); + assert!(tags(&s, a).is_empty()); +} + +#[test] +fn document_tags_list_every_items_tags_and_add_none() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ + vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", + ); + // `pageItems` lists the topmost item first, and so does `Document.tags`. + assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]); + // A copy keeps its source's tags. + let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); + assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); + s.execute("edit.undo", &json!({})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags")); + assert_eq!(undo_steps(&s), before); + log(&mut s, "app.activeDocument.tags.removeAll();"); + assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty()); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn bad_tag_values_throw_and_change_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); + let before = undo_steps(&s); + let tag = "app.activeDocument.pageItems[1].tags[0]"; + assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); + assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); + let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); + assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError")); + // A run that fails after changing a tag puts it back. + assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); + assert_eq!(tags(&s, a), pairs(&[("n", "v")])); + // Setting what a tag already has runs no command. + log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';")); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0); + assert_eq!(a.0, big); + let out = log( + &mut s, + "var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\ + var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\ + t.remove(); vc.log(all.length); vc.log(all[0].name);", + ); + assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]); + assert_eq!(tags(&s, a), pairs(&[("m", "")])); +} + +#[test] +fn an_object_takes_at_most_64_tags() { + let (mut s, a, _) = doc(); + let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + assert_eq!(out, [json!(MAX_TAGS)]); + let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();"); + assert!(e.contains("64 tags"), "{e}"); + assert_eq!(tags(&s, a).len(), MAX_TAGS); +} + +#[test] +fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run + // put the document back). + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;"); + assert!(e.contains("Stale tag"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;"); + assert!(e.contains("Stale page item"), "{e}"); + // A tag added after another was deleted does not take the deleted one's place. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor after the run undoes the add: the undone document's next id does not give the tag's id + // out again. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from + // another document). + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ahead = d.peek_next_id() + 2; + d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]); + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); +} + +#[test] +fn tag_commands_check_their_params_and_skip_unchanged_edits() { + let (mut s, a, _) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap(); + let before = undo_steps(&s); + assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false); + assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), before); + let too_long = "x".repeat(MAX_TAG_TEXT + 1); + for (id, p) in [ + ("object.tag.add", json!({"id": a.0, "name": too_long})), + ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": a.0, "name": null})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})), + ("object.tag.add", json!({"id": 999_999})), + ("object.tag.add", json!({"id": "1"})), + ("object.tag.set", json!({"id": a.0, "tag": tag})), + ("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})), + ("object.tag.remove", json!({"id": a.0, "tag": -1})), + ("object.tag.removeAll", json!({"ids": [999_999]})), + ("object.tags", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + let layer = s.active().unwrap().doc.layers[0].id; + assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err()); + assert_eq!(undo_steps(&s), before); + assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]})); +} + +#[test] +fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { + let (mut s, a, b) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("size", "XL")]); + // The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it. + assert_eq!(t[0].id, tag); + assert!(tag < back.peek_next_id()); + // A file with too many tags, repeated ids and over-long text opens with them within the limits. + doc.node_mut(b).unwrap().edit_attrs(|at| { + at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect(); + at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() }); + }); + // The repeated ids get new ids from the next node id on. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t[0].id, 7); + assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id())); + // An id at the top of the node id range, and one past it: the new ids are the smallest the + // object's other tags do not have. + let top = (1u64 << 62) - 1; + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags[0].id = u64::MAX; + at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() }); + }); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + // Opening gives both new ids below the next node id, which stays within the node id range. + let fixed: Vec = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect(); + assert_eq!(fixed.len(), 2); + assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}"); + assert_eq!(fixed, [top, 1]); + assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id()); + // No tag id is left for a new tag: one past the range would not be kept on opening, and one + // below it could be a deleted tag's. + assert_eq!(back.clone().alloc_tag_id(a), None); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t.len(), MAX_TAGS); + assert_eq!(t[0].name, "t0"); + // The first tag with the repeated id keeps it; the others get new ones. + assert_eq!(t[0].id, 7); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id < back.peek_next_id())); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), MAX_TAGS); +} + +#[test] +fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() { + let (s, a, _) = doc(); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags = + ["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect(); + }); + let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap(); + for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] { + assert!(hostile.contains(from), "{from}"); + hostile = hostile.replace(from, to); + } + let back = vectorcraft_format::load(hostile.as_bytes()).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index d49b18b031..96403dcaa0 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3250,6 +3250,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 9ab1aab001..0d1d6b50a8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1142,3 +1142,219 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); } + +/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path. +fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec) { + let v = run(s, "document.exportForWeb.saveColorTable", p); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (v, bytes) +} + +/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the +/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of +/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first. +fn act_layout(colors: &[&str], transparent: Option) -> Vec { + let mut out = vec![]; + for c in colors { + let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap(); + out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]); + } + out.resize(768, 0); + out.extend_from_slice(&(colors.len() as u16).to_be_bytes()); + out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes()); + out +} + +/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors +/// as written, in file order, zero bytes after them, the count and the transparent entry. +#[test] +fn save_color_table_writes_the_act_layout() { + let mut s = two_colours(); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "transparency": false}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert_eq!(colors.len(), 2, "{pv}"); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, None), "{format}"); + assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}"); + } + // Transparent pixels: the trailer names the transparent entry. + let mut s = session(40.0, 30.0); + rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000"); + let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let table = pv["colors"].as_array().unwrap(); + let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16; + let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect(); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, Some(at))); + assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at))); +} + +/// A color shifted by hand goes into the file as the color it is written as. +#[test] +fn save_color_table_writes_shifted_colors_as_written() { + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}}); + let (_, bytes) = color_table_file(&mut s, p); + let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}"); +} + +/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and +/// keeping another extension, and refuses formats without a color table and bad params. +#[test] +fn save_color_table_writes_the_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none"}); + let (_, bytes) = color_table_file(&mut s, p.clone()); + let bare = dir.join("table").to_string_lossy().into_owned(); + let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare}))); + let written = format!("{bare}.act"); + assert_eq!(v["path"].as_str(), Some(written.as_str())); + assert_eq!(std::fs::read(&written).unwrap(), bytes); + let other = dir.join("table.tbl").to_string_lossy().into_owned(); + run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other}))); + assert_eq!(std::fs::read(&other).unwrap(), bytes); + for (bad, says) in [ + (json!({"format": "jpg"}), "`jpg` has no color table"), + (json!({"format": "png24"}), "`png24` has no color table"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": ""}), "`path` is empty"), + (json!({"path": " "}), "`path` is empty"), + (json!({"slice": "1"}), "`slice` is a slice number"), + (json!({"slice": 0}), "`slice` is a slice number"), + ] { + let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// With Save for Web set to the selected slices and none selected, Save Color Table still writes +/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among +/// the selected slices. +#[test] +fn save_color_table_of_the_whole_image_needs_no_selected_slice() { + let mut s = two_colours(); + let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.select", json!({})); + let p = json!({"format": "gif", "dither": "none", "transparency": false}); + let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"}))); + let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"}))); + assert_eq!(bytes, whole, "{v}"); + let number = run(&mut s, "slice.list", json!({}))["slices"] + .as_array() + .unwrap() + .iter() + .find(|l| l["id"].as_u64() == Some(slice)) + .map(|l| l["number"].clone()) + .unwrap(); + let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string(); + assert!(e.contains("no selected slice"), "{e}"); +} + +/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. +#[test] +fn preview_refuses_a_slice_that_is_not_a_number() { + let mut s = two_colours(); + for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] { + let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string(); + assert!(e.contains("`slice` is a slice number"), "{slice}: {e}"); + } + assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok()); +} + +/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without +/// a transparent entry; 772 bytes add the count and the transparent index. +#[test] +fn color_table_files_are_read_by_the_published_layout() { + use cmd::webexport::read_act; + let long: Vec = (0..768).map(|i| (i % 251) as u8).collect(); + let t = read_act(&long).unwrap(); + assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None)); + let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap(); + assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1))); + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None); + // An index past the colors used names no entry. + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None); + let mut zero = act_layout(&["#ff0000"], None); + zero[768..770].copy_from_slice(&0u16.to_be_bytes()); + let mut over = act_layout(&["#ff0000"], None); + over[768..770].copy_from_slice(&257u16.to_be_bytes()); + for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] { + assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len()); + } +} + +/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry, +/// with the file's color count; the preview of the loaded settings writes those colors. +#[test] +fn load_color_table_makes_the_file_the_fixed_palette() { + let mut s = two_colours(); + let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1)); + let table = json!({ + "deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"], + "transparent": ["#00ff00"], "sort": "hue", + }); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table}); + let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)}))); + assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1))); + let settings = &v["settings"]; + assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0))); + let table = &settings["colorTable"]; + assert_eq!( + (&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]), + (&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([])) + ); + assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none"))); + // The loaded palette is what the image is written with: blue takes the nearest loaded color. + let pv = run(&mut s, "document.exportForWeb.preview", settings.clone()); + let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}"); + // A table saved and loaded again keeps its colors. + let opaque = json!({"format": "png8", "dither": "none", "transparency": false}); + let saved = color_table_file(&mut s, opaque.clone()).1; + let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)})); + let shown = run(&mut s, "document.exportForWeb.preview", opaque); + let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect(); + assert_eq!(again["colors"].as_array().unwrap().iter().collect::>(), before); + // A table whose only color is its transparent entry loads that color. + let only = act_layout(&["#336699"], Some(0)); + let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)})); + assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2))); +} + +/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses +/// bad params without changing the remembered settings. +#[test] +fn load_color_table_reads_a_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let path = dir.join("t.act").to_string_lossy().into_owned(); + std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap(); + let v = run(&mut s, "webExport.loadColorTable", json!({"path": path})); + assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"])); + let large = dir.join("large.act").to_string_lossy().into_owned(); + std::fs::write(&large, vec![0u8; 1 << 20]).unwrap(); + let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None)); + for (bad, says) in [ + (json!({"path": large}), "not a color table"), + (json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"), + // A whole table with more data after it is too long. + (json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"), + (json!({}), "give exactly one of `path` and `dataBase64`"), + (json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"), + (json!({"dataBase64": "%%%"}), "bad dataBase64"), + (json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"), + ] { + let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 61bfba6fb3..51f6f2a41d 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1793,6 +1793,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { assert!(r.get("profileMismatch").is_none(), "{r}"); } +/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the +/// paste does: pasting back into the document the objects came from, where only the RGB background +/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK +/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares +/// the swatches and lists the edited one. +#[test] +fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default"); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}"); + } + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + /// A converting paste back into the document the objects came from (its profile changed since the /// copy) still takes its image blobs as the document's own: an image whose blob under its key /// changed since keeps that key, and so shows the document's blob. diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 07389dc866..1c44685198 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -77,7 +77,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", ), ("Application.", "prototype"), ( @@ -100,7 +100,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ typename views views= width", ), ("Layer.", "prototype"), @@ -113,10 +113,14 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("Tags.", "prototype"), + ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Tag.", "prototype"), + ("Tag.prototype.", "constructor name name= parent remove typename value value="), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/crates/engine/tests/plugin_js.rs b/crates/engine/tests/plugin_js.rs new file mode 100644 index 0000000000..0b5558da11 --- /dev/null +++ b/crates/engine/tests/plugin_js.rs @@ -0,0 +1,127 @@ +//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it +//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run +//! that fails or exhausts its budget leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_engine::Session; +use vectorcraft_testkit::fixtures::{exec, rect, select, session}; + +/// Paints every input object's first fill blue. +const BLUE: &str = "function run(input, params) {\n\ + return {objects: input.objects.map(function (o) {\n\ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\ + })};\n\ +}\n"; + +/// An empty folder for one test, with anything an earlier run left there removed. +fn folder(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as +/// that file → the manifest's path. +fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String { + let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("tint.js"), script).unwrap(); + } + path.display().to_string() +} + +/// The active document's layers and its undo steps. +fn state(s: &mut Session) -> (Value, usize) { + let layers = exec(s, "document.inspect", json!({}))["layers"].take(); + (layers, s.doc().unwrap().history.undo.len()) +} + +fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color() +} + +#[test] +fn a_javascript_filter_changes_a_fill_as_one_undo_step() { + let dir = folder("blue"); + let mut s = session(); + let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE)); + let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter"))); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + select(&mut s, &[id]); + let before = state(&mut s); + let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"})); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0])); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the +/// document and its history stay as they were. +#[test] +fn an_endless_loop_stops_on_its_budget_and_changes_nothing() { + let dir = folder("loop"); + let mut s = session(); + let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string(); + assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's +/// file access. Nothing changes. +#[test] +fn a_javascript_filter_has_no_file_access() { + let dir = folder("file"); + let mut s = session(); + let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the +/// key, and nothing is installed. +#[test] +fn a_manifest_without_its_script_is_refused_at_install() { + let dir = folder("noscript"); + let mut s = session(); + let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None); + let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + for cmd in ["plugin.inspect", "plugin.install"] { + let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}"); + } + assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs new file mode 100644 index 0000000000..527374c9f6 --- /dev/null +++ b/crates/engine/tests/script_startup.rs @@ -0,0 +1,568 @@ +//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at +//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the +//! launch marker naming the startup script that runs. +//! +//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide, +//! so these tests run one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::safe_mode; +use vectorcraft_testkit::TempDir; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled, no launch marker. +fn reset() { + safe_mode::end_launch(); + safe_mode::set_active(None); + safe_mode::forget_previous(); + safe_mode::set_disabled(vec![]); +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +/// A new, empty folder for test `tag`, removed with everything in it when the test ends. +fn tmp_dir(tag: &str) -> TempDir { + TempDir::new(&format!("script-startup-{tag}")) +} + +/// Writes `text` to `name` under `dir`, folders included. +fn write(dir: &Path, name: &str, text: &str) -> PathBuf { + let path = dir.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path +} + +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +fn session(dir: &Path) -> Session { + let mut s = Session::new(); + s.attach_startup_scripts_dir(dir.to_path_buf()); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + s +} + +/// The names of the runs the Script Console started, in order. +fn started(s: &Session) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// The texts of the Script Console's lines of `kind`. +fn console(s: &Session, kind: &str) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect() +} + +fn names(v: &Value) -> Vec<&str> { + v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect() +} + +#[test] +fn startup_scripts_are_off_by_default_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("off"); + write(&dir, "a.jsx", "vc.log('ran');"); + let mut s = Session::new(); + assert!(!s.prefs.run_startup_scripts, "off by default"); + s.attach_startup_scripts_dir(dir.to_path_buf()); + assert_eq!(s.startup_skip(), Some("off")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap(); + assert_eq!(r["skipped"], true); + assert_eq!(r["then"]["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["chosen"], "no startup script ran"); +} + +#[test] +fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() { + let _f = fresh(); + let dir = tmp_dir("order"); + for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] { + write(&dir, name, "vc.log(1);"); + } + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case"); + assert!(r["failed"].as_array().unwrap().is_empty()); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["then"]["ok"], true); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); +} + +#[test] +fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { + let _f = fresh(); + let dir = tmp_dir("missing"); + let mut s = session(&dir.join("Startup Scripts")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty()); + assert_eq!(r["unreadable"], false); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["why"], "noFolder"); +} + +#[test] +fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() { + let _f = fresh(); + let dir = tmp_dir("safe"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + assert_eq!(s.startup_skip(), Some("safeMode")); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["why"], "safeMode"); + assert_eq!(started(&s), ["chosen"]); +} + +#[test] +fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() { + let _f = fresh(); + let dir = tmp_dir("disabled"); + let a = write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::disable(safe_mode::Item::file(a.to_string_lossy())); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["disabled"]), ["a.jsx"]); + assert_eq!(names(&r["ran"]), ["b.jsx"]); +} + +#[test] +fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() { + let _f = fresh(); + let dir = tmp_dir("failing"); + write(&dir, "1 throws.jsx", "throw new Error('broken');"); + write(&dir, "2 endless.jsx", "for (;;) {}"); + write(&dir, "3 syntax.jsx", "var = ;"); + write(&dir, "4 fine.jsx", "vc.log(1);"); + let mut s = session(&dir); + let then = json!({"source": "vc.log('chosen');", "name": "chosen"}); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap(); + let failed = r["failed"].as_array().unwrap(); + let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]); + assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}"); + assert_eq!(names(&r["ran"]), ["4 fine.jsx"]); + assert_eq!(r["then"]["ok"], true, "the chosen script runs after them"); + assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions"); +} + +#[test] +fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() { + let _f = fresh(); + let dir = tmp_dir("large"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it"); +} + +#[test] +fn a_startup_script_cannot_start_another_startup_run() { + let _f = fresh(); + let dir = tmp_dir("nested"); + let text = + "try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }"; + write(&dir, "a.jsx", text); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["ran"]), ["a.jsx"]); + assert_eq!(console(&s, "log"), ["refused"]); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn bad_parameters_are_refused() { + let _f = fresh(); + let dir = tmp_dir("params"); + let mut s = session(&dir); + for p in [ + json!({}), + json!({"reason": "boot"}), + json!({"reason": "menu", "then": "x.jsx"}), + json!({"reason": "launch", "maxFuel": 0}), + json!({"reason": "launch", "maxFuel": 1.5}), + ] { + assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); + } + // `then` is checked as `script.run` checks its parameters, before any startup script runs. + write(&dir, "a.jsx", "vc.log(1);"); + let then = json!({"source": "vc.log(2);", "bogus": true}); + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string(); + assert_eq!(e, alone); + assert!(started(&s).is_empty(), "no startup script ran"); +} + +#[test] +fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() { + let _f = fresh(); + let dir = tmp_dir("app"); + let launch = tmp_dir("app-launch"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "throw new Error('broken');"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "bb.jsx", &big); + write(&dir, "c.jsx", "vc.log(3);"); + assert!(safe_mode::begin_launch(&launch).is_empty()); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([]))); + let marker = || { + let file = std::fs::read_dir(&launch) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "json")) + .unwrap(); + safe_mode::parse_marker(&std::fs::read(file).unwrap()) + }; + let names = |items: Vec| items.into_iter().map(|i| i.name).collect::>(); + assert_eq!(names(marker()), [Some("a.jsx".to_string())], "the marker names the running startup script"); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert!(!s.script_running()); + assert_eq!(results, [true, false, true, true], "each run reports as it ends"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]); + let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string(); + assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app"); + assert!(s.take_startup_failures().is_empty()); + assert!(marker().is_empty(), "the marker names nothing once they have run"); +} + +#[test] +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { + let _f = fresh(); + let dir = tmp_dir("app-then"); + write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn a_stop_between_runs_survives_an_entry_that_cannot_start() { + let _f = fresh(); + let dir = tmp_dir("stop-before-failed-entry"); + write(&dir, "a.jsx", "vc.log('first');"); + write(&dir, "b.jsx", "var = ;"); + write(&dir, "c.jsx", "vc.log('must not run');"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok()); + if by_interrupt { + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop()); + } + let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(stopped.is_err(), "by_interrupt={by_interrupt}"); + assert_eq!(s.script_report().unwrap()["name"], "c.jsx"); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(console(&s, "log"), ["first"]); + assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::>(), ["b.jsx"]); + } +} + +#[test] +fn the_chosen_run_reads_includes_after_the_startup_runs() { + let _f = fresh(); + let dir = tmp_dir("chosen-includes"); + let startup = dir.join("startup"); + let chosen = dir.join("chosen"); + write(&startup, "a.jsx", "vc.log('startup');"); + let include = write(&chosen, "value.jsxinc", "vc.log('before');"); + let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');"); + let mut s = session(&startup); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap(); + std::fs::write(&include, "vc.log('after');").unwrap(); + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running()); + assert_eq!(console(&s, "log"), ["startup", "after", "main"]); +} + +#[test] +fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() { + let _f = fresh(); + let dir = tmp_dir("failed-startup-pumps"); + for name in ["a.jsx", "b.jsx", "c.jsx"] { + write(&dir, name, "var = ;"); + } + let mut s = session(&dir); + s.script_frames = true; + let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap(); + let failures = first["failed"].as_array().unwrap(); + assert!(!failures.is_empty() && failures.len() < 3, "{first}"); + assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries"); + let mut failed: Vec = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect(); + for _ in 0..100 { + if !s.script_running() { + break; + } + s.script_pump(); + failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name)); + } + assert!(!s.script_running()); + assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]); + assert_eq!(console(&s, "log"), ["chosen"]); +} + +#[test] +fn a_failed_chosen_preflight_clears_the_previous_report() { + let _f = fresh(); + let dir = tmp_dir("preflight-report"); + write(&dir, "a.jsx", "vc.log('startup');"); + for frames in [false, true] { + let mut s = session(&dir); + s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap(); + assert!(s.script_report().is_some()); + let before = started(&s); + s.script_frames = frames; + assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err()); + assert!(s.script_report().is_none(), "frames={frames}"); + assert_eq!(started(&s), before); + assert!(!s.script_running()); + } +} + +#[test] +fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { + let _f = fresh(); + let dir = tmp_dir("invalid-chosen-syntax"); + write(&dir, "a.jsx", "vc.log('startup ran');"); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})); + assert!(result.is_err(), "frames={frames}: {result:?}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames={frames}"); + assert!(s.take_startup_failures().is_empty()); + } +} + +#[test] +fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() { + let _f = fresh(); + for frames in [false, true] { + let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" }); + let data = dir.join("data"); + let startup = dir.join("startup"); + let entry = write(&startup, "a.jsx", ""); + let real = std::fs::canonicalize(&entry).unwrap(); + let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes()); + let installed = data.join(&key[..16]); + let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');"); + let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap(); + write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';")); + let mut s = session(&startup); + s.attach_script_data(data); + s.attach_scripts_dir(installed); + s.script_frames = frames; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap(); + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(result) = s.script_pump() { + result.unwrap(); + } + } + assert!(!s.script_running()); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]); + assert!(!chosen.exists()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); + } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + } +} + +#[test] +fn a_startup_script_refused_before_it_begins_is_in_the_script_console() { + let _f = fresh(); + let dir = tmp_dir("refused"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.execute("file.new", &json!({})).unwrap(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + let error = r["failed"][0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("undo group"), "{r}"); + assert_eq!(started(&s), ["a.jsx"]); + assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]); +} + +#[test] +fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() { + let _f = fresh(); + let dir = tmp_dir("app-abandon-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(2);"); + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump"); + assert!(s.script_abandon(), "the queued runs are stopped"); + assert!(!s.script_running()); + assert!(s.script_pump().is_none()); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { + let _f = fresh(); + let dir = tmp_dir("app-unread"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["running"], json!(false)); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); +} + +#[test] +fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() { + let _f = fresh(); + let dir = tmp_dir("app-roots"); + // Writes a file in the run's temporary folder, which is outside the write roots below. + let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\ + vc.log(ok ? 'wrote' : 'refused');"; + write(&dir, "a.jsx", source); + write(&dir, "b.jsx", source); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap(); + for confined in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}}); + let mut request = || s.execute("script.startup.run", ¶ms).unwrap(); + let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; + assert_eq!(r["queued"], json!(3)); + // The frames that start the later runs are outside the request. + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running(), "the startup queue did not finish, confined {confined}"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + let want = if confined { "refused" } else { "wrote" }; + assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); + } +} diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..44a9f01369 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -472,6 +517,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..1de16f938d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; @@ -644,6 +646,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); + // Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids + // (after the depth limit too). + doc.tidy_tags(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0); // Untrusted: the superscript, subscript and small caps proportions of the type, the graph diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 304f20557e..aea7afde1d 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; /// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to /// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + curvature_circle_with(c, t, convex, true) +} + +/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a +/// circular arc too. +pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result { let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); if !finite || !(0.0..=1.0).contains(&t) { return Err(NoCircle::Cusp); } let at = c.eval(t); - let (center, radius, nominal) = match circular_arc(c) { + let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) { Some((center, radius)) => { let out = at - center; let len = out.hypot(); @@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result Result { + curvature_circle_on_with(sp, seg, t, convex, true) +} + +/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`. +pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result { let n = sp.segment_count(); if seg >= n { return Err(NoCircle::Cusp); @@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re if corner { return Err(NoCircle::Corner); } - curvature_circle(c, t, convex) + curvature_circle_with(c, t, convex, arcs) } /// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether @@ -260,6 +271,19 @@ mod tests { } } + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller + /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. + #[test] + fn without_arcs_a_circle_segment_gives_its_own_curvature() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let sp = &pd.subpaths[0]; + let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap(); + let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap(); + assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}"); + assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}"); + assert_eq!(own.at, sp.segment(0).eval(0.0)); + } + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index e255258f34..8efa1458eb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -244,6 +244,12 @@ pub enum Expr { OptionalChain(ExprId), /// The object or function before `?.` in an [`Expr::OptionalChain`]. Optional(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -440,6 +446,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 86b31414b3..3baad7b7bd 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,8 +3,9 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and //! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,6 +13,7 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; @@ -261,6 +263,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; @@ -471,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -610,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -622,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -647,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; @@ -687,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -700,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -722,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -740,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index b40f979fc0..d7d5a8192a 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize { } /// CreateIterResultObject (section 7.4.7): `{ value, done }`. -fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index ab2c480c4b..9122362928 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -18,9 +18,9 @@ //! 25.6.1.9); one that still has none when the run ends successfully is reported by //! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. //! -//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object -//! whose `length` is a whole number by index, and a string by code point; other values reject the -//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator +//! when processing a yielded value throws. Noniterable values reject the promise they return +//! with a `TypeError`. The statics need a constructor as `this`, and the //! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` //! are not read. @@ -30,9 +30,10 @@ use std::rc::Rc; use super::{arg, constructor, create_at, method, native, new_array}; use crate::LimitKind; use crate::bytecode::Code; -use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::heap::{ + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, +}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::string_builtins::flat_charged; use crate::value::Value; /// Where a promise was rejected: the code and the instruction. @@ -262,6 +263,9 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let object_proto = interp.intrinsics.object_proto; let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); interp.promises.proto = Some(proto); + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?; + } let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; interp.promises.ctor = Some(ctor); constructor(interp, "Promise", ctor, proto)?; @@ -929,8 +933,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -939,7 +943,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { code, .. } => return Ok(!code.arrow && !code.method), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; @@ -1028,67 +1032,41 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe }) } -/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to -/// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. -enum Inputs { - Indexed { object: ObjId, length: f64 }, - CodePoints(Rc<[u16]>), -} - -impl Inputs { - fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { - match input { - Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { - Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { - Ok(Inputs::Indexed { object: *o, length }) - } - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - }, - Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - } - } - - /// The input at `index`, which counts code units for a string; `None` past the end. - fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { - match self { - Inputs::Indexed { object, length } => { - let end = match interp.heap.object(*object).map(|o| &o.class) { - Some(Class::Array { length, .. }) => f64::from(*length), - _ => *length, - }; - if *index >= end { - return Ok(None); - } - let v = super::get_at(interp, *object, *index)?; - *index += 1.0; - Ok(Some(v)) - } - Inputs::CodePoints(units) => { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let i = *index as usize; - let Some(&first) = units.get(i) else { return Ok(None) }; - let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); - let n = if pair { 2 } else { 1 }; - let piece = units.get(i..i + n).unwrap_or_default().to_vec(); - *index += n as f64; - let bytes = crate::heap::string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - Ok(Some(Value::String(crate::value::Str::from_units(piece)))) - } - } - } -} - fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { let resolve_fn = interp.get_value(this, &key("resolve"))?; if !interp.is_callable(&resolve_fn) { return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); } root(interp, &resolve_fn); - let inputs = Inputs::new(interp, input, how)?; + let iterator = interp.get_iterator(input)?; + root(interp, &Value::Object(iterator)); + let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject)); + if let Err(Abrupt::Throw(reason)) = &result { + root(interp, reason); + let site = interp.throw_site.clone(); + let mark = interp.thrown_mark; + match interp.iter_close(iterator) { + Ok(()) | Err(Abrupt::Throw(_)) => { + interp.throw_site = site; + interp.thrown_mark = mark; + interp.passing = reason.clone(); + } + Err(other) => return Err(other), + } + } + result +} + +fn combine_iterator( + interp: &mut Interp, + this: &Value, + iterator: ObjId, + how: Combine, + rec: ObjId, + resolve_fn: &Value, + handlers: (&Value, &Value), +) -> JsResult<()> { + let (resolve, reject) = handlers; let combinator = if how == Combine::Race { None } else { @@ -1098,14 +1076,12 @@ fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine root(interp, &Value::Object(c)); Some((c, values)) }; - let mut position = 0.0; let mut index: u32 = 0; loop { - interp.use_fuel()?; let mark = interp.temp_roots.len(); - let Some(next) = inputs.get(interp, &mut position)? else { break }; + let Some(next) = interp.iter_next(iterator)? else { break }; root(interp, &next); - let next_promise = interp.call(&resolve_fn, this, &[next])?; + let next_promise = interp.call(resolve_fn, this, &[next])?; root(interp, &next_promise); match combinator { None => { diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 2671959b17..5a44e6385a 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -246,6 +246,30 @@ pub(crate) enum Op { InitIndex, /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. InitAccessorIndex(bool), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`, + /// which calls the iterator's methods itself. + DelegateIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -354,6 +378,9 @@ pub(crate) struct Code { /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: /// its functions have no `prototype` and cannot be constructed (section 14.3.8). pub(crate) method: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. @@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::IterClose => e(1, 0), Op::IterCloseThrow => end(2), Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::DelegateIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { 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"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 26cd0a71cd..f4314f2e5e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -109,6 +109,8 @@ struct FnCompiler<'a> { /// The optional chains being compiled, innermost last: where a step that finds `undefined` /// or `null` jumps, and the stack depth the chain started at. optional: Vec<(Label, u32)>, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> { block_funcs: HashSet::new(), annex: HashSet::new(), optional: Vec::new(), + generator: false, } } @@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> { self.at(self.ast.expr_span(id).end); self.nullish_check()?; } + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::DelegateIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfNullish { target: t, .. } | Op::ForInNext(t) | Op::IterStep(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> { es2015: self.es2015, own_name: meta.own_name, method: meta.method, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..ccf3aee006 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,414 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`. + pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value is not iterable")); + } + let iterator = self.call(&method, &v, &[])?; + if !matches!(iterator, Value::Object(_)) { + return Err(self.type_error("the iterator is not an object")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..551fb4e5e6 --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,382 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn promise_jobs_resume_generator_callbacks() { + let mut realm = es2015(Limits::default()); + realm + .run( + "var log = []; var it = (function* () { log.push('start'); var value = yield 7; \ + log.push('resume:' + value); return 9; })(); \ + Promise.resolve().then(it.next.bind(it)).then(function (result) { \ + log.push(result.value + ':' + result.done); return it.next(5); \ + }).then(function (result) { log.push(result.value + ':' + result.done); });", + ) + .unwrap(); + assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into())); +} + +#[test] +fn promise_static_methods_reject_generator_constructors() { + truth( + "var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \ + try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \ + try { Promise.reject.call(C, 1).catch(function () {}); } \ + catch (error) { if (error instanceof TypeError) count++; } }); count === 4", + ); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + // A generator method has a `prototype` that its generator objects inherit from, unlike other + // methods, and takes a computed name and the method's `name`. + truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')"); + truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); + } + assert!(used[1] >= used[0] + 1000, "{used:?}"); + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 57ec9d6680..1a58fa1d28 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -181,6 +181,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -245,6 +247,8 @@ pub(crate) enum Class { /// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the /// operand stack only. IterRecord(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -339,7 +343,13 @@ impl Class { Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", + Class::Ordinary + | Class::ForIn(_) + | Class::Host(_) + | Class::Symbol(_) + | Class::Iterator(_) + | Class::IterRecord(_) + | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -759,6 +769,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..276895e782 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -265,9 +266,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -299,6 +298,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -407,16 +414,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +462,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,8 +504,8 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, @@ -520,7 +519,14 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { @@ -552,6 +558,29 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d2994fb80b..9d14718dee 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -172,6 +172,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -220,11 +226,10 @@ impl Interp { /// gets `true` as a third argument. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - let mut args = vec![this, k]; - if probe { - args.push(Data::Bool(true)); + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); } + let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 25265086e5..8c4b036898 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -11,6 +11,57 @@ fn realm(fuel: u64) -> Realm { r } +#[test] +fn non_finite_indexer_keys_reach_the_host_unchanged() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|args| { + assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}"); + Ok(Data::Bool(true)) + }); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); +} + +#[test] +fn host_receivers_obey_limits_lowered_after_the_object_was_created() { + for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { + for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] { + let mut r = realm(1_000_000); + let calls = Rc::new(Cell::new(0)); + let called = calls.clone(); + let function: HostFunction = Rc::new(move |_| { + called.set(called.get() + 1); + Ok(Data::Undefined) + }); + let class = HostClass { + name: "Indexed".into(), + parent: None, + members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))], + index: Some(function), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap(); + r.set_data_limits(limits); + let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}"); + assert_eq!(calls.get(), 0, "{expression}"); + } + } +} + +#[test] +fn index_keys_share_the_receivers_data_budget() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); + assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); + let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result"; + assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); +} + /// A realm with `host.take(value)`, which records what it was given and returns it. fn with_take(r: &mut Realm) -> Rc>> { let seen: Rc>> = Rc::default(); @@ -75,6 +126,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() { r.end(); } +fn paused_for_replacement(promise: bool) -> Realm { + let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default()); + let pause = r.pause_flag(); + r.define_function("pauseNow", move |_| { + pause.set(true); + Ok(JsValue::Undefined) + }); + let source = if promise { + "var kept = 'yes', after = false, queued = false;\n\ + Promise.resolve().then(function () { pauseNow(); after = true; });\n\ + Promise.resolve().then(function () { queued = true; }); 'old'" + } else { + "var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'" + }; + r.start(source).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.is_running()); + if promise { + assert!(r.interp().promises.draining); + } + r +} + +fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result { + if sliced { + r.start(source)?; + finish(r, 1_000).0 + } else { + r.run(source) + } +} + +#[test] +fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() { + for sliced in [false, true] { + let mut r = paused_for_replacement(true); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_paused_script_discards_its_remaining_code() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_waiting_run_discards_its_host_call() { + for sliced in [false, true] { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var after = false; ask('old'); after = true").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.waits()); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + assert_eq!(calls.get(), 1); + assert!(r.answer(Data::Null).is_err()); + } +} + +#[test] +fn replacing_a_paused_run_with_invalid_source_still_ends_it() { + for promise in [false, true] { + for sliced in [false, true] { + let mut r = paused_for_replacement(promise); + assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } + } +} + +#[test] +fn replacing_a_paused_run_applies_its_pending_language_setting() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + r.set_es2015(true); + assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0)); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + } +} + /// Setting `Folder.current` back for the next run drops what only the last run's uncaught /// exception held, so a full heap from that exception does not stop the next run. #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 6a57041cfe..f8e80a6e87 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -198,22 +200,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -530,7 +534,7 @@ fn arguments_bytes(args: usize) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -539,9 +543,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -868,7 +874,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -896,7 +902,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -995,6 +1001,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -1049,6 +1057,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -1065,6 +1074,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -1072,8 +1082,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1254,7 +1271,12 @@ impl Interp { Op::PatternGet(n) => self.op_pattern_get(n), Op::InitIndex => self.op_init_index(), Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Resume(t) => self.op_resume(t), + Op::DelegateIterator => self.op_delegate_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -2407,7 +2429,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2421,6 +2444,18 @@ impl Interp { if let Some(name) = own_name { self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?; } + // A generator function's `prototype`, a generator method's included, inherits from + // %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13). + // A generator function has no own `caller` or `arguments`, strict or not + // (section 16.2). + if let (false, Some((_, generator_proto))) = (arrow, generator) { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } // An arrow function, a method and an accessor of ECMAScript 2015 code have no // `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8). if arrow || method { @@ -2819,6 +2854,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2944,6 +2984,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2964,6 +3008,7 @@ impl Interp { } 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.generator => Err(self.type_error("a generator 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 }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; @@ -3066,6 +3111,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3300,6 +3346,7 @@ impl Interp { match prepared? { Prepared::Done(v) => Ok(Some(v)), Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None), } } @@ -3311,6 +3358,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3560,6 +3612,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index a300d22451..97f33ea054 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1015,6 +1015,7 @@ fn code(ops: Vec) -> Code { es2015: false, own_name: None, method: false, + generator: false, } } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index 49a503f506..eac1d4abe6 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -162,7 +162,7 @@ impl Interp { /// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return` /// method, unless it is done, and checks that it gives an object. - fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { + pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { let r = self.record(rec)?; if r.done { return Ok(()); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 17f2b1de0f..a93dcd5483 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,7 +63,16 @@ //! closes its iterator. In a realm made without the option and later given it with //! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects //! by index and strings by code point, and throw a `TypeError` for other values. -//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors. +//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -96,6 +105,7 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; mod host_classes; @@ -273,6 +283,8 @@ mod es2020_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 0e25c141fe..b0b6870b67 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -37,6 +37,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> { /// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal /// is read as a destructuring pattern. proto_twice: HashSet, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -143,6 +149,7 @@ impl<'s> Parser<'s> { cover_ok: false, rest_commas: HashSet::new(), proto_twice: HashSet::new(), + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -284,9 +291,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -359,7 +375,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -368,7 +384,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -532,6 +549,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index 27d684ced2..a616adc805 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -146,6 +146,12 @@ impl Parser<'_> { /// initializer (`a = 1`), which only a pattern may hold. pub(super) fn parse_property_es2015(&mut self) -> Result { let start = self.tok.span; + // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). + if self.eat(Punct::Star)? { + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } // `get` and `set` start an accessor only when written without escapes and followed by a // property name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { @@ -158,7 +164,7 @@ impl Parser<'_> { { self.bump()?; let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -192,7 +198,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_rest(FunctionKind::Method, None, start)?; + let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index ef0ed1d0d1..01abc2c92e 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -57,6 +57,22 @@ fn promise_prototype_cannot_be_replaced() { assert_eq!(string(src), "true,true,true"); } +#[test] +fn promise_prototype_has_a_configurable_string_tag() { + assert_eq!( + string( + "var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \ + [Object.prototype.toString.call(Promise.prototype), \ + Object.prototype.toString.call(Promise.resolve()), \ + d.value, d.writable, d.enumerable, d.configurable].join()" + ), + "[object Promise],[object Promise],Promise,false,false,true" + ); + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into())); +} + #[test] fn then_callbacks_run_after_the_scripts_code_in_order() { let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ @@ -144,7 +160,73 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { } #[test] -fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { +fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() { + let src = "var input = {}; input[Symbol.iterator] = function () {\n\ + var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\ + };\n\ + Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\ + Promise.race(input).then(function (v) { log.push('race ' + v); });\n\ + var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\ + Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\ + Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });"; + let out = log(src); + for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] { + assert!(out.contains(expected), "{expected} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_close_after_resolve_or_then_throws() { + let src = "function check(name, failure) {\n\ + var closed = 0, input = {};\n\ + input[Symbol.iterator] = function () { return {\n\ + next: function () { return { value: 1, done: false }; },\n\ + return: function () { closed++; throw 'close'; }\n\ + }; };\n\ + Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\ + function () { return { get then() { throw 'then'; } }; };\n\ + Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\ + }\n\ + var original = Promise.resolve;\n\ + for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\ + Promise.resolve = original;"; + let out = log(src); + for name in ["all", "allSettled", "race"] { + for failure in ["resolve", "then"] { + let expected = format!("{name}:{failure}:{failure}:1"); + assert!(out.contains(&expected), "{expected} in {out}"); + } + } +} + +#[test] +fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() { + let src = "var closed = 0;\n\ + function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\ + next: function () { if (failure === 'next') throw failure;\n\ + return { get done() { if (failure === 'done') throw failure; return false; },\n\ + get value() { throw failure; } }; },\n\ + return: function () { closed++; return {}; }\n\ + }; }; return o; }\n\ + for (var i = 0; i < 3; i++) {\n\ + Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\ + }\n\ + var empty = {}; empty[Symbol.iterator] = function () { return {\n\ + next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\ + }; };\n\ + Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\ + Promise.race(empty).then(function () { log.push('race settled'); });\n\ + log.push('closed ' + closed);"; + let out = log(src); + for expected in ["next", "done", "value", "empty 0", "closed 0"] { + assert!(out.contains(expected), "{expected} in {out}"); + } + assert!(!out.contains("race settled"), "{out}"); +} + +#[test] +fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() { // `Promise.resolve` runs once for each input and appends to the input while it is read. let src = "var resolve = Promise.resolve; var input;\n\ Promise.resolve = function (x) {\n\ @@ -152,11 +234,10 @@ fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_t return resolve.call(this, x);\n\ };\n\ input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ - input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });"; + input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });"; let out = log(src); assert!(out.contains("array 1,2,3"), "{out}"); - assert!(out.contains("object 1"), "{out}"); - assert!(!out.contains("object 1,"), "{out}"); + assert!(out.contains("object true"), "{out}"); } #[test] diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index b1273cb760..bd191b0463 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -277,6 +277,7 @@ impl Realm { /// Runs `source` as a script in the global environment, then the promise jobs it queued, and /// returns its completion value (the value of the last expression statement that ran). A realm /// whose built-ins could not be installed runs nothing and gives an internal error. + /// A paused or waiting run ends first; its globals remain available. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); @@ -285,6 +286,7 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.end(); self.script_tag = UNKNOWN_SOURCE; self.rejections = (Vec::new(), 0); let interp = &mut self.interp; @@ -351,6 +353,9 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); @@ -391,6 +396,7 @@ impl Realm { } /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + /// A paused or waiting run ends first; its globals remain available. pub fn start(&mut self, source: &str) -> Result<(), RunError> { let code = self.compile(source)?; match self.interp.enter_global(code, false) { diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7f19ba162e..4bb98b1e55 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bd8c406b79..8d012a81e1 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -51,11 +51,15 @@ //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse with that option. Its failures go to `symbol-failures.txt`. //! -//! The last test reads the tests of `for-of` and destructuring (the folders +//! Another test reads the tests of `for-of` and destructuring (the folders //! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose //! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a //! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`. //! +//! The last test reads and runs the tests of generator functions, `yield` and the generator objects +//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of +//! the two tests before it. Its failures go to `generators-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -1176,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all +/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with +/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each +/// folder and writes the failures to `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut features: Vec<&str> = vec!["generators"]; + features.extend(FOR_OF_AND_PATTERN_FEATURES); + features.extend(SYMBOL_FEATURES); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_FOLDERS { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + }; + let mut counts = run_parse_negatives(dir, &root, &options, &features); + counts.add(run_tagged_tests(dir, &root, &missing, &options, &features)); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + /// Parses the negative parse tests under `root` whose feature tags are all in `features`, in /// each mode the test names, with `options`; each must give a `SyntaxError`. fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index fa2bc204f6..a519986ed0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -771,7 +771,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -867,7 +867,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -1174,7 +1174,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1513,7 +1513,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} 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), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; 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 item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {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); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list 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, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} 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), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; 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 item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {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); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else 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, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -2030,17 +2030,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 69269cb7eb..15d6746ce1 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -615,6 +615,10 @@ impl Dest { /// The catalog entries `set` asks for (none in PDF/A files, which carry their own); a PDF/X file's /// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one. +/// When the settings leave the condition identifier blank, a profile computed for a registered +/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier, +/// and its registry when the settings leave the registry blank too. An identifier set in the +/// settings is written as given, with the settings' registry. fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { let o = &set.output; if set.standard == Standard::PdfA2b { @@ -631,13 +635,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { ProfileKind::Gray => None, }); let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::(); - OutputIntent { - id: text(if id.is_empty() { name } else { id }), - condition: text(&o.output_condition), - registry: text(&o.registry), - info: text(name), - profile, - } + // Without a condition identifier, a profile computed for a registered printing condition + // names that condition and, unless the settings name one, the registry it belongs to. + let (id, registry) = match cms::characterization(name) { + Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }), + _ => (if id.is_empty() { name } else { id }, o.registry.as_str()), + }; + OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile } }); let trapped = (o.trapped || intent.is_some()).then_some(o.trapped); (intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped }) diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index f7cf8ff56a..6af2e0e0a5 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -151,6 +151,75 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds"))); } +/// The ICC tag signatures of `icc`'s tag table. +fn icc_tags(icc: &[u8]) -> Vec { + let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize; + (0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect() +} + +#[test] +fn a_registered_condition_profile_names_its_condition_and_embeds_itself() { + use std::io::Read; + let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]); + for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] { + let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let t = text(&r.bytes); + let info = profile.replace('(', r"\(").replace(')', r"\)"); + for want in [ + "/S/GTS_PDFX".to_string(), + format!("/OutputConditionIdentifier({reference})"), + "/RegistryName(http://www.color.org)".into(), + format!("/Info({info})"), + ] { + assert!(t.contains(&want), "{profile}: {want}"); + } + // The embedded profile is the working space's: a CMYK output profile with Lab tables both + // ways, read from the file's bytes. + let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap(); + let obj = &r.bytes[start..end]; + let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap(); + let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap(); + let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len(); + data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count(); + let raw = &obj[data..data + length]; + let mut icc = vec![]; + if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() { + flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap(); + } else { + icc = raw.to_vec(); + } + assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap()); + assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..])); + assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]); + let tags = icc_tags(&icc); + for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] { + assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}"); + } + let back = cms::IccProfile::from_bytes(None, &icc).unwrap(); + assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk)); + assert!(import(&r.bytes).is_ok()); + } + // A condition identifier or registry the settings give stays. + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.output_condition_id = "Press 2".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}"); + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.registry = "https://example.com/registry".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)")); + // Other profiles keep their name as the identifier, with no registry. + let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap()); + let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)"); + assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}"); +} + #[test] fn pdfx_1a_files_have_no_rgb() { let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 0a964167a2..c5d80823d6 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-plugins" -description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects" +description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } +# The interpreter of JavaScript plug-ins (`js.rs`). +vectorcraft-js = { workspace = true } wasmi = { workspace = true } wasmparser = { workspace = true } # The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 354610e4c0..fb12557f37 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -688,7 +688,7 @@ impl Run { } } - fn progress(&mut self, done: i64, total: i64) { + pub(crate) fn progress(&mut self, done: i64, total: i64) { let total = u64::try_from(total).unwrap_or(0); let done = u64::try_from(done).unwrap_or(0); let done = if total > 0 { done.min(total) } else { done }; @@ -710,12 +710,12 @@ impl Run { vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP); } - fn cancelled(&self) -> i32 { + pub(crate) fn cancelled(&self) -> i32 { i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed()) } /// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns. - fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { + pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL }; let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY }; if self.report.truncated { diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs new file mode 100644 index 0000000000..a8fa158c41 --- /dev/null +++ b/crates/plugins/src/js.rs @@ -0,0 +1,517 @@ +//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a +//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`. +//! +//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`, +//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host +//! loads it as one JSON object, the manifest with the script's text in `source` +//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in +//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the +//! script needs a new approval. Loading parses the script and runs none of it. +//! +//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input` +//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and +//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and +//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]). +//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock +//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then +//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON, +//! is the run's output, which the host checks as it checks a WebAssembly filter's. +//! +//! A run is held to the filter's instruction budget (one budget for the top level and the call, +//! checked in slices between which the deadline and Cancel are checked), a heap of at most the +//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit +//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and, +//! when known, the line and column. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value}; +use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; + +use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; +use crate::permissions::{self, Permission}; +use crate::runtime::SELECTION_TOO_LARGE; +use crate::{Error, Limits, Result}; + +/// The extension of a JavaScript plug-in's manifest file. +pub const PACKAGE_EXT: &str = "vcplugin"; + +/// Largest script, in bytes. +pub const MAX_SCRIPT_BYTES: usize = 8 << 20; + +/// Longest script file name, in bytes. +pub const MAX_SCRIPT_NAME: usize = 128; + +/// The script's name when the plug-in's JSON gives none. +pub const DEFAULT_SCRIPT: &str = "plugin.js"; + +/// Instructions a run executes between two checks of its deadline and Cancel. +pub const FUEL_SLICE: u64 = 1_000_000; + +/// Longest error message a run reports, in characters. +const MAX_ERROR_TEXT: usize = 512; + +/// What `script` may hold. +const SCRIPT_NAME_RULE: &str = + "`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`"; + +/// Where the script's text may be given. +pub const SOURCE_RULE: &str = + "`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`"; + +/// The error of a plug-in's JSON without `"runtime": "js"`. +pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\""; + +/// What the arguments of `vc.progress` and `vc.log` may be. +const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers"; +const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string"; + +/// What runs the plug-in: its script's top level is done, `run` is called with the input and the +/// parameters, and what it returns is written as JSON. +const ENTRY: &str = "(function () {\n\ + if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\ + return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\ +})()"; + +/// A JavaScript plug-in's code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Script { + /// Its file name, which errors give. + pub(crate) name: String, + pub(crate) source: String, +} + +/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder? +pub fn valid_script_name(name: &str) -> bool { + (1..=MAX_SCRIPT_NAME).contains(&name.len()) + && !name.starts_with('.') + && !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) + && name.len() > 3 + && name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js")) +} + +/// The `script` a manifest's JSON gives, checked. +pub(crate) fn script_name(v: &Value) -> Result { + match v.as_str() { + Some(name) if valid_script_name(name) => Ok(name.to_string()), + _ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())), + } +} + +/// The error of a manifest with `"runtime": "js"` and no `script`. +pub(crate) fn no_script() -> Error { + Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into()) +} + +/// Does `map`, a plug-in's JSON, give `"runtime": "js"`? +pub(crate) fn is_js(map: &Map) -> bool { + map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name()) +} + +/// How the script is read. +fn options() -> vectorcraft_js::Options { + vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() } +} + +/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in +/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as +/// a module's is, and the script is parsed, not run. +pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { + let mut map: Map = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?; + if !is_js(&map) { + return Err(Error::Manifest(NOT_JS.into())); + } + let named = map.remove("script"); + let source = match map.remove("source") { + Some(Value::String(s)) => s, + Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())), + None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())), + None => return Err(no_script()), + }; + let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?; + if source.len() > MAX_SCRIPT_BYTES { + return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); + } + // The manifest is read from `bytes`, so `params` keep their order; its size is counted + // without `script` and `source`. + let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len(); + if size > MAX_MANIFEST_BYTES { + return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})"))); + } + let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + let manifest = Manifest::parse_text(text)?; + if let Err(e) = vectorcraft_js::parse(&source, &options()) { + let named = Named { id: &manifest.id, script: &name }; + return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); + } + Ok((manifest, Script { name, source })) +} + +/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives +/// them, the line and column. +fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String { + let (id, script) = (named.id, named.script); + match at { + Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"), + _ => format!("{reason} ({id}, {script})"), + } +} + +/// One run's input and budgets. +pub(crate) struct Call<'a> { + pub(crate) input: &'a [u8], + pub(crate) params: &'a [u8], + pub(crate) limits: &'a Limits, + /// The plug-in's memory cap, which the run's heap stays within. + pub(crate) max_memory: usize, + pub(crate) deadline: Deadline, +} + +/// The heap a run may use with memory cap `max_memory`. +fn heap_bytes(max_memory: usize) -> usize { + vectorcraft_js::Limits::default().heap_bytes.min(max_memory) +} + +/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the +/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`. +pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result> { + let heap = heap_bytes(call.max_memory); + // Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more. + if call.input.len().saturating_add(call.params.len()) > heap / 8 { + return Err(Error::Limit(SELECTION_TOO_LARGE.into())); + } + // The host writes the input and the parameters with serde_json, so they are UTF-8. + let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params)); + let state = Rc::new(RefCell::new(state)); + let out = run_realm(script, m, (&*input, &*params), call, heap, &state); + *report = std::mem::take(&mut state.borrow_mut().report); + out +} + +/// What errors name: the plug-in's id and its script's file name. +struct Named<'a> { + id: &'a str, + script: &'a str, +} + +fn run_realm( + script: &Script, + m: &Manifest, + (input, params): (&str, &str), + call: &Call<'_>, + heap: usize, + state: &Rc>, +) -> Result> { + let defaults = vectorcraft_js::Limits::default(); + let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte)); + let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults }; + let mut realm = Realm::with_options(options(), limits); + realm.set_clock(|| f64::NAN); + let named = Named { id: &m.id, script: &script.name }; + realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind { + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()), + _ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named), + })?; + let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?; + // The call takes what the top level left of the budget. + let left = realm.fuel_left(); + realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() }); + let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call.deadline.check()?; + match value { + JsValue::String(s) if s.len() > call.limits.max_output_bytes => { + let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes); + Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})"))) + } + JsValue::String(s) => Ok(s.into_bytes()), + _ => Err(Error::Output(located(NO_OUTPUT, &named, None))), + } +} + +/// The error of a `run` that returned nothing JSON can write. +const NO_OUTPUT: &str = "run(input, params) returned no output object"; + +/// The limit a run that nested its calls too deeply exceeded. +const CALL_DEPTH: &str = "call depth"; + +/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel +/// checked between them → its completion value, and the source tag of the plug-in's script: +/// `script_tag`, or with `None` the tag of `source`, which is then the script. +fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option) -> Result<(JsValue, u32)> { + let started = realm.start(source); + let tag = script_tag.unwrap_or_else(|| realm.script_tag()); + started.map_err(|e| js_error(realm, e, tag, named))?; + loop { + match realm.advance(FUEL_SLICE) { + Ok(Progress::Done(v)) => return Ok((v, tag)), + Ok(Progress::Paused) => {} + Err(e) => return Err(js_error(realm, e, tag, named)), + } + if vectorcraft_doc::cancel::check().is_err() { + realm.end(); + return Err(Error::Cancelled); + } + if let Err(e) = deadline.check() { + realm.end(); + return Err(e); + } + } +} + +/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script, +/// and the line and column when the error is in the script (source tag `tag`). +fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error { + let at = (realm.error_tag() == tag).then_some((e.line, e.column)); + let message = permissions::display_text(&e.message, MAX_ERROR_TEXT); + match e.kind { + RunErrorKind::Syntax => Error::Module(located(&message, named, at)), + RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)), + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)), + RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)), + RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled, + RunErrorKind::Internal => Error::Trap(located(&message, named, at)), + } +} + +/// The members of the realm's `vc` object. +fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc>) -> Vec<(String, HostItem)> { + let mut items = vec![ + ("input".to_string(), HostItem::Value(Data::String(input.into()))), + ("params".to_string(), HostItem::Value(Data::String(params.into()))), + ]; + if !m.permissions().contains(&Permission::Progress) { + return items; + } + let number = |args: &[Data], i: usize, rule: &str| match args.get(i) { + Some(Data::Number(n)) => Ok(*n), + _ => Err(HostError::Type(rule.into())), + }; + let run = state.clone(); + items.push(( + "progress".into(), + HostItem::Function(Rc::new(move |args| { + let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?); + // `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values. + run.borrow_mut().progress(done as i64, total as i64); + Ok(Data::Undefined) + })), + )); + let run = state.clone(); + items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1)))))); + let run = state.clone(); + items.push(( + "log".into(), + HostItem::Function(Rc::new(move |args| { + let level = number(&args, 0, LOG_ARGS)?; + let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) }; + let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL }; + match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) { + LOG_WRITTEN => Ok(Data::Bool(true)), + LOG_DROPPED => Ok(Data::Bool(false)), + _ => Err(HostError::Range(LOG_ARGS.into())), + } + })), + )); + items +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::{Error, Limits, Plugin}; + + /// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys. + fn bundle(id: &str, source: &str, extra: Value) -> Vec { + let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + serde_json::to_vec(&m).unwrap() + } + + fn load(bytes: &[u8]) -> crate::Result { + load_with(bytes, Limits::default()) + } + + fn load_with(bytes: &[u8], limits: Limits) -> crate::Result { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Plugin::load(bytes, limits) + } + + const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#; + + /// The output of `run(input, params)` is the run's output JSON. + #[test] + fn a_filter_returns_its_objects_as_json() { + let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }"; + let p = load(&bundle("test.js.blue", src, json!({}))).unwrap(); + assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js"))); + let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap(); + assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]})); + } + + /// The realm has none of the script runner's globals, so code that reads them throws a + /// `ReferenceError` naming the global, the plug-in and where in its script. + #[test] + fn file_folder_and_app_are_not_defined() { + for name in ["File", "Folder", "$", "app", "BridgeTalk"] { + let src = format!("function run(input) {{\n return {name}.x;\n}}"); + let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err(); + let Error::Failed(why) = &e else { panic!("{name}: {e:?}") }; + assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}"); + assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}"); + } + let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap(); + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["n"], "NaN", "no clock"); + } + + /// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't + /// see. + #[test] + fn a_polluted_prototype_does_not_reach_the_next_run() { + let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \ + Array.prototype.map = null; return {objects: [], seen: String(seen)}; }"; + let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap(); + for _ in 0..2 { + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["seen"], "undefined"); + } + } + + /// An endless loop ends with the instruction budget, naming the plug-in and the line. + #[test] + fn an_endless_loop_ends_with_the_instruction_budget() { + let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap(); + let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }; + let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}"); + } + + /// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds + /// meanwhile, such as a script's, runs on as before. + #[test] + fn heap_exhaustion_leaves_a_held_realm_usable() { + let mut held = vectorcraft_js::Realm::new(); + held.run("var kept = 41;").unwrap(); + let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }"; + let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap(); + let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}"); + assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0)); + } + + /// An input too large for the heap is refused before it is copied in. + #[test] + fn a_selection_too_large_for_the_heap_is_refused() { + let small = + load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() }) + .unwrap(); + let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000)); + assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into()))); + } + + /// A result that isn't an output object, and a script without `run`, fail the run. + #[test] + fn a_missing_entry_or_result_fails_the_run() { + let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}"); + let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}"); + let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({}))) + .unwrap() + .run(b"{\"objects\":[]}", b"{}") + .unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc` + /// has neither. + #[test] + fn progress_and_log_need_the_progress_permission() { + let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }"; + let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap(); + let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()); + let out: Value = serde_json::from_slice(&out.unwrap()).unwrap(); + assert_eq!(out["cancelled"], false); + assert_eq!(report.progress, Some((3, 4))); + assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]); + let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// Loading checks the manifest and the script, and runs none of it. + #[test] + fn loading_refuses_a_bad_manifest_or_script() { + let ok = "function run() { return {objects: []}; }"; + let refused = |bytes: Vec| load(&bytes).unwrap_err(); + let e = refused(bundle("test.js.syntax", "function run( {", json!({}))); + assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}"); + let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1); + assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is"))); + let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); + let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); + assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); + let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); + assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}"); + let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap(); + no_source.as_object_mut().unwrap().remove("source"); + let e = refused(serde_json::to_vec(&no_source).unwrap()); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}"); + // Top-level code that would throw does not run at load. + assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok()); + } + + /// A WebAssembly module's manifest can't give `"runtime": "js"`. + #[test] + fn a_module_manifest_cannot_be_javascript() { + let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#; + let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap(); + assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`"))); + } + + /// The SHA-256 a grant records is the bundle's, so another script is another module. + #[test] + fn the_hash_covers_the_script() { + let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap(); + let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap(); + assert_ne!(a.hash(), b.hash()); + } + + /// The parameters, and a command's, keep the order the plug-in's JSON declares them in. + #[test] + fn params_keep_their_declaration_order() { + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", + "params": {{"z": {num}, "a": {num}, "m": {num}}}, + "commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}], + "source": "function run(i) {{ return i; }}"}}"# + ); + let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap(); + let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::>(); + assert_eq!(names(&manifest.params), ["z", "a", "m"]); + assert_eq!(names(&manifest.commands[0].params), ["y", "b"]); + } + + #[test] + fn script_names_stay_in_the_manifest_s_folder() { + for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { + assert!(super::valid_script_name(ok), "{ok}"); + } + for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] { + assert!(!super::valid_script_name(bad), "{bad:?}"); + } + assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126)))); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index df4c9a0a23..c4597fcec4 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -32,6 +32,10 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. +//! +//! An object filter may also be written in JavaScript ([`js`]): its manifest gives +//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each +//! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] pub mod deferred; @@ -40,6 +44,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod js; pub mod loader; pub mod manifest; pub mod objects; @@ -53,7 +58,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index e4274fc716..56b8357cf1 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -224,6 +224,32 @@ impl Budget { } } +/// What runs a plug-in's code. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Runtime { + /// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`. + #[default] + Wasm, + /// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest + /// gives `"runtime": "js"`. + Js, +} + +impl Runtime { + pub fn name(self) -> &'static str { + match self { + Runtime::Wasm => "wasm", + Runtime::Js => "js", + } + } + + /// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`). + fn is_wasm(&self) -> bool { + *self == Runtime::Wasm + } +} + /// One declared parameter. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -494,6 +520,9 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. + #[serde(default, skip_serializing_if = "Runtime::is_wasm")] + pub runtime: Runtime, } impl Manifest { @@ -503,6 +532,13 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + Manifest::parse_text(text) + } + + /// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the + /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys + /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. + pub(crate) fn parse_text(text: &str) -> Result { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } @@ -533,6 +569,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Runtime::Wasm, } } @@ -620,7 +657,30 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_runtime() + } + + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions + /// it lists only `progress`: its realm has no settings, cache or command calls. + fn validate_runtime(&self) -> Result<()> { + if self.runtime == Runtime::Wasm { + return Ok(()); + } + if self.kind != Kind::Filter { + let kind = self.kind.name(); + return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); + } + let listed = self.permissions.as_deref().unwrap_or_default(); + for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + if listed.iter().any(|n| n == p.name()) { + let name = p.name(); + return Err(Error::Manifest(format!( + "a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`" + ))); + } + } + Ok(()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 9432b151b8..d1f7265cff 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -279,14 +279,73 @@ pub fn intern(s: &str) -> &'static str { v } -/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit) +/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit), +/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]), /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - let bytes = read_module(path, &limits, || {})?; + load_file_where(path, limits, &|_| Ok(())) +} + +/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path. +#[cfg(not(target_arch = "wasm32"))] +fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result { + let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? }; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`? +pub fn is_js_package(path: &std::path::Path) -> bool { + path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT)) +} + +/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`] +/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest +/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`. +/// Each file is refused before it is read when it isn't a regular file or is larger than its limit +/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read +/// only when `allow` accepts its path, and must be UTF-8. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result> { + read_js_package_with(path, allow, || {}) +} + +/// [`read_js_package`], with `opening` run between the script's size check and its open. +#[cfg(not(target_arch = "wasm32"))] +fn read_js_package_with( + path: &std::path::Path, + allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>, + opening: impl FnOnce(), +) -> Result> { + use serde_json::Value; + let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; + let bytes = read_module(path, &manifest_limits, || {})?; + let map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + if !crate::js::is_js(&map) { + return Err(Error::Manifest(crate::js::NOT_JS.into())); + } + if map.contains_key("source") { + return Err(Error::Manifest(crate::js::SOURCE_RULE.into())); + } + let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?; + let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name); + allow(&file).map_err(Error::Io)?; + let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; + let source = read_module(&file, &script_limits, opening)?; + let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; + // `source` is added to the manifest's own text, so its keys keep their order. The text parsed as + // an object that has `runtime`, so its last character other than white space is its closing `}`. + let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}'); + let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?; + let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?; + let mut out = Vec::with_capacity(bytes.len() + source.len() + 12); + out.extend_from_slice(&bytes[..end]); + out.extend_from_slice(b",\"source\":"); + out.extend_from_slice(&source); + out.push(b'}'); + Ok(out) +} + /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused /// before it is opened, and so is one over the module limit. On Unix the file is opened without /// waiting, so a named pipe put in its place after that check doesn't hold the load until something @@ -329,7 +388,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result { #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; -/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how /// many more there are. Only that many paths are held while the folder is listed. An error while /// the folder is listed is returned, as one opening it is. #[cfg(not(target_arch = "wasm32"))] @@ -340,7 +399,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize let mut more = 0; for entry in rd { let p = entry.map_err(io)?.path(); - if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) { continue; } kept.push(p); @@ -373,7 +432,7 @@ pub struct FolderReport { pub no_thread: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it /// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name @@ -386,7 +445,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) } -/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list +/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list /// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others /// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the @@ -500,7 +559,7 @@ impl FolderLoad { hook(&path); } } - load_file(&path, Limits::default()) + load_file_where(&path, Limits::default(), &*allow) })); } files.push((f, refused)); @@ -885,6 +944,104 @@ mod tests { assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); } + /// A JavaScript plug-in's manifest file and its script, in `dir`. + #[cfg(not(target_arch = "wasm32"))] + fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf { + let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"}); + if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("f.js"), script).unwrap(); + } + path + } + + /// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of + /// the same package by bytes gets. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_a_javascript_plugin() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("js"); + let id = "test.registry.js"; + write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }")); + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![id.to_string()], "{r:?}"); + let p = get(id).unwrap(); + assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str())); + assert!(remove(id)); + } + + /// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key; + /// so is one that names a script `allow` refuses or that isn't there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_manifest_needs_its_script() { + let dir = test_dir("js-script"); + let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None); + let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap(); + let missing = write_js(&dir, "b", serde_json::json!({}), None); + let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None); + let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None); + let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display()))); + let results = [ + read_js_package(&no_key, &|_| Ok(())), + read_js_package(&missing, &|_| Ok(())), + read_js_package(&inline, &|_| Ok(())), + read_js_package(¬_js, &|_| Ok(())), + ]; + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]); + assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]); + assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]); + assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]); + assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}"); + } + + /// A script larger than the limit is refused by its size before it is opened. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_oversized_script_is_refused_before_it_is_read() { + let dir = test_dir("js-big"); + let path = write_js(&dir, "big", serde_json::json!({}), Some("")); + std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap(); + let opened = std::cell::Cell::new(false); + let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}"); + assert!(!opened.get(), "the script was opened"); + } + + /// A manifest file's parameters keep their declaration order through the package it is read + /// into, which is its own text with `source` added. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_package_keeps_the_manifest_s_order() { + let dir = test_dir("js-order"); + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + "{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n" + ); + let path = dir.join("order.vcplugin"); + std::fs::write(&path, &text).unwrap(); + std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap(); + let bytes = read_js_package(&path, &|_| Ok(())); + std::fs::remove_dir_all(&dir).unwrap(); + let bytes = bytes.unwrap(); + let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap()); + assert_eq!(String::from_utf8_lossy(&bytes), expected); + let (manifest, _) = crate::js::read_bundle(&bytes).unwrap(); + assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::>(), ["z", "a"]); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index b7950f0056..1ad3a194fa 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -7,7 +7,7 @@ use wasmi::{ use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -169,12 +169,17 @@ impl Default for Limits { } } +/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]). +enum Code { + Wasm { engine: Engine, module: Module }, + Js(crate::js::Script), +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: -/// every run gets its own store and instance. +/// every run gets its own store and instance, or for a JavaScript plug-in its own realm. pub struct Plugin { manifest: Manifest, - engine: Engine, - module: Module, + code: Code, limits: Limits, size: usize, hash: String, @@ -341,13 +346,21 @@ impl Plugin { /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is /// checked without being instantiated, so none of its code runs; one without that section is - /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded - /// ([`Error::SafeMode`]). + /// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with + /// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its + /// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes))); } + if bytes.trim_ascii_start().starts_with(b"{") { + let (manifest, script) = crate::js::read_bundle(bytes)?; + let hash = crate::permissions::sha256_hex(bytes); + let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 }; + p.heavy_limits(); + return Ok(p); + } if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } @@ -362,8 +375,17 @@ impl Plugin { let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?; let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); - let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let live = match section_manifest(&p.module)? { + let section = section_manifest(&module)?; + let mut p = Plugin { + manifest: Manifest::placeholder(), + code: Code::Wasm { engine, module: module.clone() }, + limits, + size: bytes.len(), + hash, + source: None, + serial: 0, + }; + let live = match section { Some(manifest) => { p.manifest = manifest; None @@ -388,13 +410,11 @@ impl Plugin { Some(live) } }; - host::check_granted(&p.manifest, &imports)?; - // A heavy filter's runs get the larger budget the host allows for one, which the host - // lets the user allow or refuse before installing it. - if p.manifest.budget == crate::Budget::Heavy { - p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel); - p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); + if p.manifest.runtime != Runtime::Wasm { + return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into())); } + host::check_granted(&p.manifest, &imports)?; + p.heavy_limits(); // The other exports must exist with the right types. match live { Some(live) => { @@ -402,13 +422,35 @@ impl Plugin { live.func::("vc_run")?; } None => { - check_exports(&p.module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes)?; check_tables(bytes)?; } } Ok(p) } + /// A heavy filter's runs get the larger budget the host allows for one, which the host lets the + /// user allow or refuse before installing it. + fn heavy_limits(&mut self) { + if self.manifest.budget == crate::Budget::Heavy { + self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel); + self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms); + } + } + + /// What runs its code ([`Manifest::runtime`]). + pub fn runtime(&self) -> Runtime { + self.manifest.runtime + } + + /// A JavaScript plug-in's script file name; `None` for a WebAssembly module. + pub fn script(&self) -> Option<&str> { + match &self.code { + Code::Js(script) => Some(&script.name), + Code::Wasm { .. } => None, + } + } + pub fn manifest(&self) -> &Manifest { &self.manifest } @@ -452,6 +494,7 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new() .memory_size(self.limits.max_memory_bytes) .memories(1) @@ -459,13 +502,13 @@ impl Plugin { .table_elements(MAX_TABLE_ELEMENTS as usize) .instances(1) .build(); - let mut store = Store::new(&self.engine, Host { limits, run }); + let mut store = Store::new(engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; - let linker = host::linker(&self.engine, granted); - let instance = match linker.instantiate_and_start(&mut store, &self.module) { + let linker = host::linker(engine, granted); + let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); @@ -595,6 +638,14 @@ impl Plugin { let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); + if let Code::Js(script) = &self.code { + // Its manifest lists no `commands`, so nothing calls it with a bridge. + if bridge.is_some() { + return Err(Error::Abi("a JavaScript plug-in makes no command calls".into())); + } + let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline }; + return crate::js::run(script, m, &call, run, report); + } let mut live = self.instantiate(run, &m.permissions(), report)?; // Calls can be made from `vc_run` on, not from the start function. if bridge.is_some() { diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 637dd9c243..37c4cefbae 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -73,6 +73,10 @@ pub(crate) fn colour_glyph( return (None, false); } let used = tree.foreground_used; + // Over the budget nothing is drawn, not even the raster fallback: it would replay the graph. + if tree.too_large { + return (None, used); + } if tree.unsupported.is_some() { // What it paints, y up, for a glyph without a clip box. let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b)); @@ -114,7 +118,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) if let Some(g) = font.outline_glyphs().get(gid) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen); } - let mut path = pen.0; + let mut path = pen.finish(); path.apply_affine(FLIP); path } @@ -507,6 +511,9 @@ impl ColorPainter for Tree<'_> { self.unsupported.get_or_insert("a fill outside any glyph"); return; }; + if self.too_large { + return; + } let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; let innermost = at + 1 == self.groups.len(); let before = self.groups.last().map_or(0, |g| g.children.len()); @@ -523,6 +530,9 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { + if self.too_large { + return; + } let path = self.layer_outline(glyph_id); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); self.transforms.push(brush_xf); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 67818e8d9f..6964c3af19 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -27,6 +27,7 @@ mod dirs; mod face; mod glyph_pen; mod gsub; +mod installed; mod lookup; mod names; mod scan; @@ -58,6 +59,7 @@ pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use installed::{InstalledFace, UnloadedFile}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index a7f5c869bf..f01b0d9639 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,14 +7,20 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } -/// The most path elements one glyph outline keeps. Real outlines have hundreds; a variable -/// composite glyph can repeat a big base outline into millions. Elements past it are dropped. +/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's +/// composite glyph repeating a large component many times) is drawn as nothing, not kept. pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; -/// A pen drawing outlines y down, as text space has them. +/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path +/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path. pub(crate) struct FlipPen(pub(crate) BezPath); impl FlipPen { + /// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`]. + pub(crate) fn finish(self) -> BezPath { + if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 } + } + fn full(&self) -> bool { self.0.elements().len() >= MAX_OUTLINE_ELEMENTS } @@ -77,12 +83,17 @@ mod tests { use super::*; #[test] - fn a_pen_keeps_at_most_the_element_cap() { + fn a_pen_past_the_cap_gives_nothing() { let mut pen = FlipPen(BezPath::new()); pen.move_to(0.0, 0.0); for i in 0..MAX_OUTLINE_ELEMENTS + 10 { - pen.line_to(i as f32, 0.0); + pen.line_to(i as f32, 1.0); } - assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS); + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments"); + assert!(pen.finish().elements().is_empty()); + let mut small = FlipPen(BezPath::new()); + small.move_to(0.0, 0.0); + small.line_to(1.0, 1.0); + assert_eq!(small.finish().elements().len(), 2); } } diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs new file mode 100644 index 0000000000..05ec64bccb --- /dev/null +++ b/crates/text/src/fontdb/installed.rs @@ -0,0 +1,201 @@ +//! Installed faces that nothing has loaded yet, read for one search without adding them to the +//! database (Retype's matching, `vectorcraft_text::retype`). + +#[cfg(not(target_arch = "wasm32"))] +use super::build::make_face; +#[cfg(not(target_arch = "wasm32"))] +use super::face::FontBytes; +#[cfg(not(target_arch = "wasm32"))] +use super::scan::enumerate_faces; +use super::{Arc, FontDb, FontFace, Path, PathBuf}; + +/// One style of an installed family that is not loaded: no loaded face has its family and style. +#[derive(Clone, Debug, PartialEq)] +pub struct InstalledFace { + pub family: String, + pub style: String, + /// The font file holding it (a suitcase font's file, whose fonts are in its resource fork). + pub path: PathBuf, + /// The file's length in bytes (a suitcase font's resource fork's), when the scan read it. + pub len: u64, +} + +impl FontDb { + /// The installed faces no loaded face has the family and style of, by family name and then + /// style, as the font scan cataloged them. Reading the list reads no font file. Empty on wasm, + /// where no fonts are installed. + pub fn unloaded_installed_faces(&self) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + // The catalog first: the first scan takes the faces' lock, which a guard held here would block. + // The bundled faces have no file to read. The catalog lists a bundled face ahead of an + // installed file of the same face, so each face's file is its first installed version. + let cataloged: Vec<(String, String, PathBuf)> = self + .catalog + .faces() + .iter() + .filter_map(|f| { + let path = + self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; + Some((f.family.clone(), f.style.clone(), path)) + }) + .collect(); + let unloaded: Vec<(String, String, PathBuf)> = { + let loaded = self.read_faces(); + let is_loaded = + |family: &str, style: &str| loaded.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + cataloged.into_iter().filter(|(family, style, _)| !is_loaded(family, style)).collect() + }; + let mut out: Vec = + unloaded.into_iter().map(|(family, style, path)| InstalledFace { family, style, len: file_len(&path), path }).collect(); + out.sort_by(|a, b| { + a.family + .to_lowercase() + .cmp(&b.family.to_lowercase()) + .then_with(|| a.style.to_lowercase().cmp(&b.style.to_lowercase())) + .then(a.path.cmp(&b.path)) + }); + out + } + #[cfg(target_arch = "wasm32")] + { + vec![] + } + } + + /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one + /// search and not added to the database, with the bytes read: no faces when the file, or the + /// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face + /// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile { + #[cfg(not(target_arch = "wasm32"))] + { + let (files, bytes) = if crate::suitcase::is_suitcase(path) { + match crate::suitcase::read_fonts_within(path, max_len) { + (_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + (fonts, n, false) => (fonts, n), + } + } else { + match read_within(path, max_len) { + Some((data, n)) if n <= max_len => (vec![data], n), + Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + None => return UnloadedFile::default(), + } + }; + let mut faces = vec![]; + for data in files { + let data = Arc::new(data); + for (i, spec) in enumerate_faces(&data) { + if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { + faces.push(Arc::new(f)); + } + } + } + UnloadedFile { faces, bytes, too_long: false } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, max_len); + UnloadedFile::default() + } + } +} + +/// What [`FontDb::read_unloaded_file`] read from one font file. +#[derive(Default)] +pub struct UnloadedFile { + /// The faces read, not loaded. + pub faces: Vec>, + /// The bytes read from the file, those of a file longer than the limit included (at most one + /// past it). + pub bytes: u64, + /// The file, or the fork, is longer than the limit: no face was read. + pub too_long: bool, +} + +impl FontDb { + /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or + /// the family's other files: it joins the loaded faces, unless a face of its family, style and + /// version is loaded already, which is returned instead. + pub fn load_read_face(&self, face: Arc) -> Arc { + let same = + |f: &FontFace| f.family.eq_ignore_ascii_case(&face.family) && f.style.eq_ignore_ascii_case(&face.style) && f.version == face.version; + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(f) = faces.iter().find(|f| same(f)) { + return f.clone(); + } + faces.push(face.clone()); + drop(faces); + self.changed(); + face + } +} + +/// The length of the font file at `path`, or of its resource fork for a suitcase font; 0 when it +/// cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn file_len(path: &Path) -> u64 { + match std::fs::metadata(path) { + Ok(m) if m.len() == 0 => crate::suitcase::fork_len(path), + Ok(m) => m.len(), + Err(_) => 0, + } +} + +/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than +/// `max_len` when the file is longer. None when it cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn read_within(path: &Path, max_len: u64) -> Option<(Vec, u64)> { + use std::io::Read; + let mut data = Vec::new(); + std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; + let n = data.len() as u64; + Some((data, n)) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + + /// A database whose catalog holds the bundled font files, with Inter's faces dropped from the + /// loaded ones: Inter is installed and not loaded. + fn inter_unloaded() -> FontDb { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![dir]); + db.faces.write().unwrap().retain(|f| f.family != "Inter"); + db + } + + #[test] + fn installed_faces_not_loaded_are_listed_and_read_without_loading_them() { + let db = inter_unloaded(); + let list = db.unloaded_installed_faces(); + let inter: Vec<&InstalledFace> = list.iter().filter(|f| f.family == "Inter").collect(); + assert!(inter.iter().any(|f| f.style == "Regular"), "{list:?}"); + // The loaded families are not listed. + assert!(!list.iter().any(|f| f.family == "Source Sans 3"), "{list:?}"); + let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); + assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); + let before = db.loaded_faces().len(); + let file = db.read_unloaded_file(®ular.path, regular.len); + assert_eq!((file.bytes, file.too_long), (regular.len, false)); + let read = file.faces; + assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); + assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); + // Read for the search only: the database does not hold it, and no loaded face has its id. + assert_eq!(db.loaded_faces().len(), before); + assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); + // A file longer than the limit is not read past one byte over it, and says so. + let long = db.read_unloaded_file(®ular.path, regular.len - 1); + assert!(long.faces.is_empty()); + assert_eq!((long.bytes, long.too_long), (regular.len, true)); + let missing = db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX); + assert!(missing.faces.is_empty()); + assert_eq!((missing.bytes, missing.too_long), (0, false)); + // Once loaded, the family is no longer listed. + assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 67ec31a560..f1a024d020 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -725,7 +725,8 @@ impl FontDb { // As before, keep the prefix emitted before a malformed glyph reports an error. let _ = font.draw_to(gid, &mut pen); } - pen.0 + // An outline past MAX_OUTLINE_ELEMENTS comes back empty. + pen.finish() } /// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph). diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07357a87f3..25e44392d6 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -46,10 +46,10 @@ pub use features::{ pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, - RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, + PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, + app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, + set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7cf48e025..191e1dad87 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -217,12 +217,7 @@ impl RetypeIndex { near: &[NearKey], near_glyphs: usize, ) -> Self { - let near: Vec = near - .iter() - .copied() - .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) - .take(MAX_NEAR_KEYS) - .collect(); + let near = Self::near_keys(near); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -232,6 +227,35 @@ impl RetypeIndex { kept.push(f); } } + Self::indexed_faces(db, kept, keys, &near, near_glyphs, false) + } + + /// Index the outline glyphs of `face`, a face read for one search and not loaded + /// ([`FontDb::read_unloaded_file`]), as [`Self::build_near`] indexes a loaded face's: those + /// whose [`shape_key`] is in `keys`, and for near matching those that could near match a shape + /// with one of the [`near_key`]s in `near`. The face's keys are not kept for a later search, so + /// the keys of loaded faces stay kept. Each of its encoded glyphs ([`encoded_glyphs`]) is drawn + /// once, for its key and its sampling both. + pub fn build_unloaded_near(db: &FontDb, face: Arc, keys: &BTreeSet, near: &[NearKey]) -> Self { + let near = Self::near_keys(near); + Self::indexed_faces(db, vec![face], keys, &near, MAX_NEAR_GLYPHS, true) + } + + /// [`Self::build_unloaded_near`] for exact matching only. + pub fn build_unloaded(db: &FontDb, face: Arc, keys: &BTreeSet) -> Self { + Self::build_unloaded_near(db, face, keys, &[]) + } + + /// The near keys an index looks glyphs up by: the first [`MAX_NEAR_KEYS`] of `near` that a + /// glyph can have. + fn near_keys(near: &[NearKey]) -> Vec { + near.iter().copied().filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0).take(MAX_NEAR_KEYS).collect() + } + + /// The index of the glyphs of `kept` that [`Self::build_near_within`] takes, with `near` read + /// by [`Self::near_keys`]. With `unloaded`, the faces' keys are read for this index only and + /// not kept ([`face_keys`]), each glyph drawn once. + fn indexed_faces(db: &FontDb, kept: Vec>, keys: &BTreeSet, near: &[NearKey], near_glyphs: usize, unloaded: bool) -> Self { // Each face gets an equal share of the near checks and entries, so a face with many glyphs // (a CJK face) does not use them up before the faces after it. let share = |cap: usize| cap / kept.len().max(1); @@ -246,13 +270,20 @@ impl RetypeIndex { close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); close.truncate(keep); }; - for &(gid, ch, key, count) in face_keys(db, face).iter() { + // A loaded face's keys are kept, and a glyph is drawn when it is sampled; an unloaded + // face's glyphs are each drawn once, for the key and the sampling both. + let kept_keys = if unloaded { None } else { Some(face_keys(db, face)) }; + let glyphs: Box + '_> = match &kept_keys { + Some(k) => Box::new(k.iter().map(|&(gid, ch, key, count)| (gid, ch, key, count, None))), + None => Box::new(drawn_keys(db, face).map(|(gid, ch, key, count, outline)| (gid, ch, key, count, Some(outline)))), + }; + for (gid, ch, key, count, drawn) in glyphs { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } if keys.contains(&key) { - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } @@ -263,7 +294,7 @@ impl RetypeIndex { continue; } face_checks += 1; - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); let Some(g) = near_key(&outline) else { continue }; let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; close.push((d, gid, ch, outline)); @@ -281,6 +312,11 @@ impl RetypeIndex { } } } + Self::indexed(kept, entries) + } + + /// The index of `entries`, glyphs of `kept`. + fn indexed(kept: Vec>, entries: Vec) -> Self { let mut buckets: HashMap> = HashMap::new(); for (i, e) in entries.iter().enumerate() { buckets.entry(e.sig.contours).or_default().push(i); @@ -1037,23 +1073,7 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { return keys.clone(); } } - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - let keys: FaceKeys = Arc::new( - gids.into_iter() - .filter_map(|(gid, ch)| { - let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; - Some((gid, ch, key, u16::try_from(count).ok()?)) - }) - .collect(), - ); + let keys: FaceKeys = Arc::new(drawn_keys(db, face).map(|(gid, ch, key, count, _)| (gid, ch, key, count)).collect()); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -1069,6 +1089,42 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { keys } +/// The glyphs of `face` that are matched, under the lowest character that maps to each: its +/// encoded characters (the first [`MAX_GLYPHS_PER_FACE`]) less spaces, controls and +/// [`is_shape_symbol`]s. +fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + gids +} + +/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once, +/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only. +pub fn encoded_glyphs(face: &FontFace) -> usize { + matched_glyphs(face).len() +} + +/// A glyph with its key as [`FaceKeys`] holds it (glyph id, character, key and contour count) and +/// its outline when it was drawn already. +type KeyedGlyph = (u32, char, u64, u16, Option); + +/// The keys of `face`'s matched glyphs ([`matched_glyphs`]) as [`FaceKeys`] holds them, each glyph +/// drawn once, past the outline cache, and given with its outline. +fn drawn_keys<'a>(db: &'a FontDb, face: &'a FontFace) -> impl Iterator + 'a { + matched_glyphs(face).into_iter().filter_map(move |(gid, ch)| { + let outline = db.outline_uncached(face, gid); + let (key, count) = key_and_count(&outline)?; + Some((gid, ch, key, u16::try_from(count).ok()?, outline)) + }) +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -1534,6 +1590,20 @@ fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { Some((h, cs.len())) } +/// Is `path` a plain shape: one contour of at most [`PLAIN_EDGES`] straight edges, as +/// [`contours`] reads it (a rectangle, a triangle, a bar)? Many fonts have a glyph of such a shape +/// (a hyphen, a bar, a mark), so it does not tell which font outlined text is in. `false` for an +/// empty shape or one past the size caps. +pub fn is_plain(path: &BezPath) -> bool { + match contours(path).as_deref() { + Some([c]) => c.len() <= PLAIN_EDGES && c.iter().all(|s| matches!(s, PathSeg::Line(_))), + _ => false, + } +} + +/// The most straight edges of a plain shape ([`is_plain`]). +const PLAIN_EDGES: usize = 4; + /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. @@ -2472,4 +2542,53 @@ mod tests { index.matches(&shape).iter().map(|m| m.face.id()).collect::>() ); } + + #[test] + fn plain_shapes_are_one_contour_of_up_to_four_straight_edges() { + let rect = kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1); + assert!(is_plain(&rect)); + let mut triangle = BezPath::new(); + triangle.move_to((0.0, 0.0)); + triangle.line_to((50.0, 0.0)); + // A straight edge split in two reads as one. + triangle.line_to((50.0, 20.0)); + triangle.line_to((50.0, 40.0)); + triangle.close_path(); + assert!(is_plain(&triangle)); + let mut pentagon = BezPath::new(); + pentagon.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (50.0, 30.0), (20.0, 50.0), (-10.0, 30.0)] { + pentagon.line_to(p); + } + pentagon.close_path(); + assert!(!is_plain(&pentagon)); + assert!(!is_plain(&kurbo::Circle::new((0.0, 0.0), 10.0).to_path(0.1)), "curves"); + assert!(!is_plain(&letter()), "two contours"); + assert!(!is_plain(&BezPath::new())); + } + + /// A face read from an installed file and not loaded is indexed as a loaded one is, and the + /// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unloaded_face_is_indexed_as_a_loaded_one() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![]); + let loaded = db.face("Source Sans 3", "Regular").unwrap(); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces; + let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); + assert_ne!(face.id(), loaded.id()); + assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len()); + // Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters. + assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); + let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); + let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); + let built = RetypeIndex::build(&db, [loaded.clone()], &keys); + assert_eq!(unloaded.len(), built.len()); + let (a, b) = (unloaded.matches(&shape), built.matches(&shape)); + assert_eq!(a.first().map(|m| (m.face.id(), m.ch)), Some((face.id(), 'g'))); + assert_eq!(b.first().map(|m| m.ch), Some('g')); + assert!(a.first().unwrap().origin.distance(b.first().unwrap().origin) < 1e-9); + } } diff --git a/crates/text/src/suitcase.rs b/crates/text/src/suitcase.rs index ff06a66672..102492b252 100644 --- a/crates/text/src/suitcase.rs +++ b/crates/text/src/suitcase.rs @@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec> { sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect() } +/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest +/// fork read), with the bytes read: no fonts, and true, when the fork is longer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec>, u64, bool) { + let max_len = max_len.min(MAX_FORK); + let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) }; + let n = fork.len() as u64; + if n > max_len { + return (vec![], n, true); + } + (sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false) +} + /// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its /// resource fork. pub(crate) fn is_suitcase(path: &Path) -> bool { @@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 { #[cfg(target_os = "macos")] fn read_fork(path: &Path) -> Option> { + read_fork_within(path, MAX_FORK) +} + +/// The first `max` bytes of the resource fork of the file at `path`. +#[cfg(target_os = "macos")] +fn read_fork_within(path: &Path, max: u64) -> Option> { use std::io::Read; let mut fork = Vec::new(); - std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?; + std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?; Some(fork) } @@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option> { None } +#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))] +fn read_fork_within(_: &Path, _: u64) -> Option> { + None +} + /// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as /// a font utility writes them. #[cfg(test)] diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index e59fb390c9..cd71fbae1c 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -714,3 +714,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() { assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}"); assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}"); } + +/// A layer list that reuses one run of layers many times grows the tree past its node cap: the +/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn. +#[test] +fn layers_repeating_a_run_of_layers_pass_the_cap() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32(); + let o = GlyphId16::new(u16::try_from(o).unwrap()); + let font = |runs: u8| { + // 255 glyph layers, then `runs` layers that each repeat all of them. + let mut layers: Vec = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect(); + layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0))); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into(); + colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into(); + crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap() + }; + assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit"); + assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not"); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index c469b48ead..44da64b495 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -997,6 +997,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { let _ = std::fs::remove_dir_all(&dir); } +/// A suitcase font read for one search (Retype) is read no further than one byte past the limit, +/// and the bytes read are counted. +#[cfg(target_os = "macos")] +#[test] +fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suitcase = dir.join("Sysfont Sans3"); + std::fs::write(&suitcase, b"").unwrap(); + let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]); + let len = fork.len() as u64; + std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let file = db.read_unloaded_file(&suitcase, len); + assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false)); + let long = db.read_unloaded_file(&suitcase, len - 1); + assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn font_files_are_told_by_their_extension() { for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] { diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..14bc32fa6d 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -79,14 +98,17 @@ impl Panel { /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is -/// ([`LineKind::fold_angle`]). +/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most +/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle +/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its +/// pieces may not have at the middle of `from` to `to`. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, + pub on: Point, pub keys: Vec, pub straight: bool, pub angle: f64, @@ -1297,9 +1319,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1368,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } @@ -1331,7 +1378,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option { mod pose; pub mod raster; -pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon}; #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs index 650ab54291..91a6cdfb12 100644 --- a/crates/three-d/src/fold/pose.rs +++ b/crates/three-d/src/fold/pose.rs @@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in}; /// test and the preview. pub const MAX_POLYGON_POINTS: usize = 1 << 16; +/// How far apart two placements of a panel may turn a unit direction and still be one placement: +/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth +/// of a degree from another ([`super::kept_angle`], 1.7e-8). +const TURNED: f64 = 1e-10; + type V3 = [f64; 3]; fn sub(a: V3, b: V3) -> V3 { @@ -105,14 +110,24 @@ impl Pose { let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } } + + /// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the + /// flat blank's own terms. + fn about(&self, origin: V3) -> Pose { + Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) } + } } -/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no -/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it -/// and the base. +/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold +/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where +/// it is) and how many hinges lie between it and the base. #[derive(Clone, Debug)] pub struct FoldedPanel { pub pose: Pose, + /// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less + /// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a + /// blank far from the document's origin to the size of the blank. + pub local: Pose, pub parent: Option, pub depth: usize, } @@ -141,6 +156,28 @@ pub struct Folded { pub hinges: Vec, /// Pairs of panels (`a` < `b`) that pass through each other. pub collisions: Vec<(usize, usize)>, + /// The fold tree that panels folded flat onto each other stack by. + pub stack: Stack, + /// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about. + pub origin: [f64; 3], +} + +/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its +/// `root`), whichever panel is the base, so choosing another base moves the folded blank without +/// changing which panel shows where they lie flat on each other. The base's own tree when the two +/// join different panels. +#[derive(Clone, Debug, Default)] +pub struct Stack { + pub root: usize, + /// Each panel's parent in this tree. + pub parent: Vec>, + /// The panels in breadth-first order from `root`, the panels not joined to it last. + pub order: Vec, + /// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector + /// in the parent's plane, across the hinge to the side the fold took the parent to be on, as + /// long as the corners of the parent's bounds reach that way. `None` for `root` and the + /// panels not joined to it. + pub toward_parent: Vec>, } /// The panel of `blank` that `p` (document coordinates) lies in. @@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }); } let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); - let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // The corners of each panel's bounds (flat). + let corners: Vec> = blank + .panels + .iter() + .map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y))))) + .collect(); + let origin = corners + .iter() + .flatten() + .flatten() + .fold(None, |b: Option<(V3, V3)>, c| { + Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0]))) + }) + .map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5)); + let placing = Placing { blank, by_panel: &by_panel, centers: ¢ers, corners: &corners, origin }; + let (panels, tree, order, toward_parent) = place(&placing, base, amount); // Closing hinges are measured with every hinge at its full angle, so a blank that closes when // folded is not reported open part of the way there. - let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) }; let measured = full.as_deref().unwrap_or(&panels); let hinges = blank .hinges @@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }) .collect(); let collisions = collisions(blank, &panels, tolerance); - Some(Folded { base, panels, order, hinges, collisions }) + let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent }; + let stack = match base_panel(&blank.panels) { + Some(root) if root != base => { + let (placed, root_tree, root_order, toward) = place(&placing, root, amount); + // Whether the root's tree puts every panel where the base's does, moved with the root + // (which lies at the identity in its own): the same hinges do, and around a loop of + // panels another tree can leave out a fold that placed them. Each panel's turn is + // compared to within `TURNED` whatever its size or place, and its inside point by the + // poses about `origin` (`local`), to rounding at that distance from it. + let agrees = |r: &FoldedPanel| { + let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b))); + placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| { + let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some()); + let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin)); + let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + .into_iter() + .all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED); + joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at)))) + }) + }; + match panels.get(root) { + // The root's tree in the base's terms. + Some(r) if root_tree == tree || agrees(r) => Stack { + root, + parent: placed.iter().map(|p| p.parent).collect(), + order: root_order, + toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(), + }, + _ => own, + } + } + _ => own, + }; + Some(Folded { base, panels, order, hinges, collisions, stack, origin }) } -/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its -/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not -/// joined to the base last). -fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { +/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and +/// [`Stack::toward_parent`]. +type Tree = (Vec, Vec, Vec, Vec>); + +/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and +/// bounds corners (flat), and the point the panels' local poses are about. +struct Placing<'a> { + blank: &'a Blank, + by_panel: &'a [Vec], + centers: &'a [Option], + corners: &'a [Option<[V3; 4]>], + origin: V3, +} + +/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined +/// to the base last), and [`Stack::toward_parent`]. +fn place(placing: &Placing, base: usize, amount: f64) -> Tree { + let Placing { blank, by_panel, centers, corners, origin } = *placing; let n = blank.panels.len(); - let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut toward_parent: Vec> = vec![None; n]; let mut reached = vec![false; n]; let mut tree = vec![false; blank.hinges.len()]; let mut order = Vec::with_capacity(n); @@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u // The parent on the left of the hinge's direction, the child on its right. The side is // read next to the hinge, so a parent with a notch or an arm past the hinge's line still // turns the child the right way; the panel's inside point is the fallback. - let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) { Some(left) => left, None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), }; @@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u continue; } if let Some(slot) = panels.get_mut(child) { - *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + let local = parent.local.turned_about(sub(from, origin), axis, theta); + *slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 }; + } + // Across the hinge, to its left: into the parent, as far as the corners of its bounds + // reach that way. + let into = [-axis[1], axis[0], 0.0]; + let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max)); + if let Some(slot) = toward_parent.get_mut(child) { + *slot = Some(parent.pose.turn(scale(into, reach))); } if let Some(r) = reached.get_mut(child) { *r = true; @@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u } } order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); - (panels, tree, order) + (panels, tree, order, toward_parent) } /// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) -/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and -/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset -/// tells them apart. The nearest offset is tried first. -fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { +/// next to it: `true` when a point just off the line on the left is inside it and the matching +/// point on the right is not, `false` the other way round. `on` (a point of the line where the +/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an +/// eighth of the way along, each with the nearest offset first; `None` when no point tells the +/// sides apart. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option { let bp = outline.to_bezpath(); - let mid = scale(add(from, to), 0.5); let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; let doc = |v: V3| Point::new(v[0], -v[1]); let mut offsets = [1e-3, 0.25, len * 0.01]; offsets.sort_by(f64::total_cmp); - offsets.into_iter().find_map(|off| { - let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); - (l != r).then_some(l) + let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t))); + std::iter::once(on).chain(along).find_map(|at| { + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0); + (l != r).then_some(l) + }) }) } diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 9cccbaf6d9..4db9cd728f 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096; pub const MAX_PIXELS: u32 = 1 << 21; /// The share of the eye's distance a panel is cut at in front of the eye. const NEAREST: f64 = 1e-3; -/// How far apart (points of view depth) two panels may be and still tie. +/// How far apart (points of view depth) two panels in one plane may be and still tie. const TIE: f64 = 1e-4; +/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one +/// plane. +const PARALLEL: f64 = 1e-9; +/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding, +/// as this many times the precision of a number at their distance from the origin for each hinge +/// that placed them. +const COPLANAR: f64 = 16.0 * f64::EPSILON; +/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count +/// as along it. +const ALONG: f64 = 1e-6; /// The light's direction: above, to the left of and toward the viewer. const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; @@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) } -fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { +fn map_panel(camera: &Camera, pose: &super::Pose) -> Option { let r = camera.rotation(); - let turn = |v: V3| mul(&r, f.pose.turn(v)); + let turn = |v: V3| mul(&r, pose.turn(v)); let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); - let o = camera.to_view(f.pose.t); + let o = camera.to_view(pose.t); let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); let normal = turn([0.0, 0.0, 1.0]); let (w, k, printed) = match camera.eye() { @@ -326,18 +336,23 @@ struct Target { panel: Vec, } -/// One panel's fill: its map, rank (for ties), panel number and colors. +/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as +/// [`planes`] gives them), panel number and colors. struct Fill<'a> { mapped: &'a Mapped, rank: u16, + planes: &'a [u16], panel: u16, print: Option<&'a Print>, + /// The flat point the map is about ([`Folded::origin`]): a flat point less it is what + /// `mapped` maps. + origin: [f64; 2], inside: [f32; 4], outside: [f32; 4], } impl Fill<'_> { - /// The document point under pixel center `(x, y)`, or `None` behind the eye. + /// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye. fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) @@ -346,7 +361,7 @@ impl Fill<'_> { /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { let base = if self.mapped.printed { - let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint)); let under = 1.0 - p[3] / 255.0; [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] } else { @@ -370,8 +385,12 @@ impl Fill<'_> { let [a, b, c] = self.mapped.depth; let z = u * a + v * b + c; let i = row * target.width + col; - let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; - let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue }; + // Panels in one plane tie within `TIE` and stack by rank; panels in different planes + // that pass this close go by depth alone. Panel numbers count from 1. + let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p)); + let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a)); + let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb }; if !wins { continue; } @@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option>> { Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) } +/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each +/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed +/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are +/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so +/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between +/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the +/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later +/// one nearer seen from one side of their plane and the earlier one seen +/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other +/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel +/// it branched from, after leaving it, takes the side of that plane it came back from for every +/// step up to the one it left by: the side the nearest panel out of the plane lies on from the +/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as +/// [`planes`] does. +fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec { + let n = folded.panels.len(); + // Each panel's layer holds a step per fold up to the base: past the panels a blank can have, + // the order alone decides. So it does when every panel lies where it lies flat (a fold amount + // of 0), as panels there do not overlap. + if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) { + return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(); + } + // The step each panel takes off its parent: the parent's printed side, negated for a positive + // angle; none for a 0° hinge or a panel without a parent. + // The parents are those of [`Folded::stack`], so the panels stack the same about any base. + let stack = &folded.stack; + let parent_of = |c: usize| stack.parent.get(c).copied().flatten(); + let mut step: Vec> = vec![None; n]; + for c in 0..n { + let Some(p) = parent_of(c) else { continue }; + let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue }; + let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue }; + let [x, y, z] = parent.pose.normal(); + *slot = match h.angle { + a if a > 0.0 => Some([-x, -y, -z]), + a if a < 0.0 => Some([x, y, z]), + _ => None, + }; + } + // Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's + // plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next + // to its parent, before any later step, however many folds deep. + // Each panel's place in the stack's order. + let mut place = vec![0usize; n]; + for (i, &pi) in stack.order.iter().enumerate() { + if let Some(slot) = place.get_mut(pi) { + *slot = i; + } + } + // Each step also carries the place in `folded.order` of the panel that took it, so panels whose + // steps match up to a fold that branches stack by that branch: the later panel nearer seen from + // one side of their plane, the earlier one seen from the other, so the two sides show opposite + // panels. The rest of a branch stays with it. + // Whether the view sees each panel's printed side. + let sees_print: Vec = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect(); + // The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it + // lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1 + // the other; `None` when every panel on the way lies in the plane. The plane is the one + // [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it + // and a stack folded a hair short of flat goes by depth instead. + let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> { + let (mut child, mut up) = (pi, parent_of(pi)); + for _ in 0..n { + let c = up?; + if planes.get(c) != planes.get(pi) + && let Some(Some(way)) = stack.toward_parent.get(child) + { + let d = dot(*way, n_view); + if d != 0.0 { + return Some((c, if d > 0.0 { 1 } else { -1 })); + } + } + (child, up) = (c, parent_of(c)); + } + None + }; + let layer = |pi: usize| -> Vec<(i8, i64)> { + let Some(f) = folded.panels.get(pi) else { return vec![] }; + let printed = sees_print.get(pi).copied().unwrap_or(true); + let n_view = { + let [x, y, z] = f.pose.normal(); + if printed { [x, y, z] } else { [-x, -y, -z] } + }; + let mut out = vec![]; + let mut at = Some(pi); + // From the nearest panel out of the plane on the way to the base, every step counts as on + // the side of the plane that panel lies on: a panel that comes round onto the plane of a + // panel it branched from lies on the side it came back from, whatever its folds before. + let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s)); + let mut returned = false; + // A panel's chain to the base is at most the panel count long. + for _ in 0..n { + let Some(c) = at else { break }; + returned |= Some(c) == back_at; + if let Some(Some(s)) = step.get(c) { + let d = if returned { f64::from(back_side) } else { dot(*s, n_view) }; + // Branches off one panel stack one way seen from that panel's printed side and the + // other way from its back, so the panels of one plane that compare a step off one + // parent agree, however the parent is turned. + let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX)); + // A parent seen edge on gives no side: the panel that took the step gives it, and + // when that is edge on too, the largest part of the view's normal does. Each choice + // gives two panels of one plane the same sign however an edge-on dot rounds, and + // each turns over with the side of the plane the view is on. + let faces = |f: &super::FoldedPanel| { + let d = dot(f.pose.normal(), n_view); + (d.abs() > ALONG).then_some(d >= 0.0) + }; + // The view's normal in the root's flat terms, so this too is the same about any base. + let largest = || { + let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m); + let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::()); + local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0) + }; + let parent = parent_of(c).and_then(|p| folded.panels.get(p)); + let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest); + let branch = if parent_faces { branch } else { -branch }; + // Any step that is not along the plane counts whole, so a step seen from two panels + // of one plane counts the same for both. + out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch)); + } + at = parent_of(c); + } + out.reverse(); + out + }; + // Layers compared step by step, a missing step as none. + let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| { + (0..a.len().max(b.len())) + .map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0)))) + .find(|o| o.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }; + // A panel alone in its plane ties with no other, so its layer is not worked out. + let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)]; + for &p in planes { + if let Some(c) = in_plane.get_mut(usize::from(p)) { + *c += 1; + } + } + let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1); + let mut keys: Vec<(Vec<(i8, i64)>, usize)> = + folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect(); + // Then by the stack's order, for panels that stack as one. + let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX); + keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1))); + let mut ranks = vec![0u16; folded.order.len()]; + for (r, &(_, i)) in keys.iter().enumerate() { + if let Some(slot) = ranks.get_mut(i) { + *slot = u16::try_from(r + 1).unwrap_or(u16::MAX); + } + } + ranks +} + /// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more /// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than /// [`super::MAX_POLYGON_POINTS`] points, are left out. @@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option { Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); - for (rank, &pi) in scene.folded.order.iter().enumerate() { + let planes = planes(scene.folded, scene.blank); + let ranks = tie_ranks(scene.folded, &camera, &planes); + // Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat + // points and the view's center moved to match. + let o = scene.folded.origin; + let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera }; + for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; - let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(mapped) = map_panel(&local, &f.local) else { continue }; let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let rings: Vec> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect(); let projected: Vec> = rings .iter() .map(|r| match near { @@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option { .collect(); let fill = Fill { mapped: &mapped, - rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + rank, + planes: &planes, panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), print: scene.print, + origin: [o[0], o[1]], inside, outside, }; @@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option { Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) } +/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their +/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them +/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the +/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is +/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`] +/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the +/// planes. Past [`super::MAX_PANELS`] panels, one plane for all. +fn planes(folded: &Folded, blank: &Blank) -> Vec { + let n = folded.panels.len(); + if n > super::MAX_PANELS { + return vec![0; n]; + } + let length = |v: V3| dot(v, v).sqrt(); + // Each plane's normal, a point of it, the size of the coordinates that point came from and the + // hinges that placed it. + let mut kinds: Vec<(V3, V3, f64, usize)> = vec![]; + folded + .panels + .iter() + .enumerate() + .map(|(i, f)| { + let o = folded.origin; + let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]); + let (normal, at) = (f.local.normal(), f.local.apply(middle)); + let size = length(at).max(length(middle)); + let same = |(m, p, s, d): &(V3, V3, f64, usize)| { + let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]]; + let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs(); + // Saturating: a `Folded` built by a caller may carry any depth. + let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX)); + length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s)) + }; + let k = kinds.iter().position(same).unwrap_or_else(|| { + kinds.push((normal, at, size, f.depth)); + kinds.len() - 1 + }); + u16::try_from(k).unwrap_or(u16::MAX) + }) + .collect() +} + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 8639615a53..014cf010d7 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; -use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose, Stack}; use super::*; fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { @@ -16,10 +18,12 @@ fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { let n = panels.len(); let folded = Folded { base: 0, - panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + panels: poses.into_iter().map(|pose| FoldedPanel { pose, local: pose, parent: None, depth: 0 }).collect(), order: (0..n).collect(), hinges: vec![], collisions: vec![], + stack: Stack { root: 0, parent: vec![None; n], order: (0..n).collect(), toward_parent: vec![None; n] }, + origin: [0.0; 3], }; (Blank { panels, hinges: vec![], holes: vec![] }, folded) } @@ -135,6 +139,1032 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); } +#[test] +fn of_two_parallel_panels_the_nearer_shows_however_close() { + // 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE` + // equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn + // first. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + for (near, poses) in [(1, vec![moved(2.0), moved(2.0001)]), (0, vec![moved(2.0001), moved(2.0)])] { + let (b, f) = scene_of(vec![whole(), whole()], poses); + assert_eq!(planes(&f, &b).iter().collect::>().len(), 2, "two planes"); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), Some(near)); + } +} + +#[test] +fn a_scene_whose_panels_claim_any_depth_still_draws() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, mut f) = scene_of(vec![whole(), whole()], vec![moved(5.0), moved(5.0)]); + for p in &mut f.panels { + p.depth = usize::MAX; + } + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert!(img.panel_at(50, 50).is_some()); +} + +#[test] +fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() { + // A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // Folds a hair short of flat lie on the same side, everywhere within a tie of the base. + for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] { + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(60.0, 0.0), (60.0, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(angle), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = 1 - f.base; + let views = [ + (front(), true), + (Camera { rotate_y: 180.0, ..front() }, false), + (Camera { perspective: 60.0, ..front() }, true), + (Camera { rotate_y: 180.0, perspective: 60.0, ..front() }, false), + ]; + for (camera, seen_from_print) in views { + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // The point x 40, y 30 of the blank, where the flap lies over the base. + let x = if seen_from_print { 40 } else { 60 }; + let want = if flap_in_front == seen_from_print { flap } else { f.base }; + assert_eq!(img.panel_at(x, 30), Some(want), "{angle}°, seen from the print: {seen_from_print}, {camera:?}"); + } + } +} + +#[test] +fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() { + // A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to + // 100) folded back at 180°, which lies behind the base from x 30 to 60. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2, 0.0), + crease(65.0, 3, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(45, 30), Some(f.base), "the base is in front of the flap behind it"); +} + +#[test] +fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() { + // A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at + // 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at + // x 20 to 30. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = f.panels.iter().position(|p| p.parent == Some(f.base)).expect("the panel folded from the base"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(25, 30), Some(f.base), "the base, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(75, 30), Some(middle), "the folded panel, from the back"); + // Folded about the flap instead, the blank only moves: the flap (x 100 to 110 now) still lies + // between the other two, the 60 pt panel over it on the printed side. + let tip = super::super::panel_at(b, Point::new(105.0, 30.0)).expect("the flap"); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [105.0, -30.0, 0.0], ..front() }; + let wide = super::super::panel_at(b, Point::new(30.0, 30.0)).expect("the 60 pt panel"); + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() { + // The strip of the test above turned 45° and moved to about (3,000,000, 3,000,000) pt, folded + // about its 10 pt flap: the 60 pt panel still lies over the flap on the printed side. + let s = std::f64::consts::FRAC_1_SQRT_2; + let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s); + let poly = + |pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::>(), closed)); + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let panel = |x: f64, y: f64| super::super::panel_at(b, at(x, y)).expect("a panel"); + let (wide, middle, tip) = (panel(30.0, 30.0), panel(80.0, 30.0), panel(105.0, 30.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let c = at(105.0, 30.0); + let at_tip = Camera { center: [c.x, -c.y, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_flat_stack_far_from_the_origin_stays_in_one_plane() { + // A strip from x = 3,000,000 pt: the base (60 pt wide), a 40 pt panel folded back under it at + // 180° and a 35 pt flap folded back at 180° between the two. + let x0 = 3_000_000.0; + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let middle = super::super::panel_at(b, Point::new(x0 + 80.0, 30.0)).expect("the middle panel"); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(planes(&f, b).iter().collect::>().len(), 1, "one plane"); + let draw = |rotate_y| { + let camera = Camera { rotate_y, center: [x0 + 40.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 50) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(middle))); +} + +#[test] +fn a_panel_parallel_to_the_base_a_hair_behind_it_goes_by_depth() { + // A strip 30 pt tall: the base (x 0 to 100), a 20 pt panel folded back at 179.9999° and a 30 pt + // flap at 0.0001° off it, parallel to the base and about 0.000035 pt behind it; then the same + // strip 100,000 pt to the right; then at 179.999999° and 0.000001°, about 0.00000035 pt behind, + // 3,000,000 pt to the right; then with a 1 pt middle panel, about 0.0000000175 pt behind, at the + // origin and 3,000,000 pt to the right. + for (dx, back, w) in + [(0.0, 0.0001, 20.0), (100_000.0, 0.0001, 20.0), (3_000_000.0, 0.000001, 20.0), (0.0, 0.000001, 1.0), (3_000_000.0, 0.000001, 1.0)] + { + parallel_a_hair_behind(dx, back, w); + } +} + +fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(100.0, 2, 180.0 - back), + crease(100.0 + w, 3, back), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = Point::new(115.0 + w + dx, 15.0); + let flap = super::super::panel_at(b, at).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let m = f.panels[flap].pose.place(at); + assert!(m[2] < 0.0 && m[2] > -1e-4, "the flap lies a hair behind the base: {m:?}"); + let draw = |rotate_y| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(flap)), "at x + {dx}, a {w} pt middle panel"); +} + +#[test] +fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() { + // A 4 pt strip, its second half folded back at 179.999999° so it lies a hair behind the first, + // seen at a three-quarter turn with and without perspective: every pixel shows the same panel + // at the origin and 3,000,000 pt right and down. + let draw = |at: f64, perspective: f64| { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::>(), closed)) + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(2.0, 0.0), (2.0, 1.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(179.999999), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let base = super::super::panel_at(b, Point::new(0.5 + at, 0.5 + at)).expect("the base"); + let f = super::super::fold(b, Some(base), 1.0, 0.0001).expect("folds"); + let camera = Camera { rotate_x: 35.0, rotate_y: 40.0, scale: 40.0, perspective, center: [1.0 + at, -0.5 - at, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown: Vec> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.panel_at(x, y).map(|p| p == base)).collect(); + assert!(shown.contains(&Some(true)), "the base shows"); + shown + }; + for perspective in [0.0, 40.0] { + assert!(draw(0.0, perspective) == draw(3_000_000.0, perspective), "perspective {perspective}"); + } +} + +#[test] +fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() { + // A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no + // layer is worked out. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for i in 1..64u32 { + let x = f64::from(i) * 10.0; + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 10.0)], false), + kind: super::super::LineKind::Crease, + key: u64::from(i) + 1, + angle: Some(180.0), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let f = super::super::fold(&blanks[0], None, 0.0, 0.1).expect("folds"); + let ranks = tie_ranks(&f, &front(), &planes(&f, &blanks[0])); + assert_eq!(ranks, (1..=64).collect::>()); +} + +#[test] +fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() { + // A 100 × 100 blank cut into four 50 pt squares by four creases, one per side of the middle + // point. The crease that closes the loop when folded about the largest panel folds at 180° and + // the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap + // lies flat behind the panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let lines = |flat_key: Option| { + let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }), + }; + vec![ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (blanks, issues) = super::super::blanks(&lines(None), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let level = super::super::fold(&blanks[0], None, 1.0, 0.1).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = *blanks[0].hinges[closing].keys.first().expect("a line"); + let (blanks, issues) = super::super::blanks(&lines(Some(key)), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let h = &b.hinges[closing]; + assert_eq!(h.keys, [key]); + let f = super::super::fold(b, Some(h.a), 1.0, 0.1).expect("folds"); + assert!(f.hinges[closing].tree); + // The panel's middle, in pixels: the blank's top left square is pixels 0 to 50. + let middle = |p: usize| { + let c = b.panels[p].outline.bounds().expect("bounds").center(); + (c.x as u32, c.y as u32) + }; + let (x, y) = middle(h.a); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(x, y), Some(h.a), "the panel, from its printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(100 - x, y), Some(h.b), "the flap, from the back"); +} + +#[test] +fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() { + // A 2 × 2 grid of panels joined by 0° creases (the largest at the bottom left), and two flaps + // folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the + // tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way, + // and the stack stays as it is about the largest panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((60.0, 0.0), (60.0, 40.0), 2, 0.0), + crease((60.0, 40.0), (60.0, 100.0), 3, 0.0), + crease((0.0, 40.0), (60.0, 40.0), 4, 0.0), + crease((60.0, 40.0), (100.0, 40.0), 5, 0.0), + crease((100.0, 0.0), (100.0, 40.0), 6, 180.0), + crease((130.0, 0.0), (130.0, 40.0), 7, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = |x: f64, y: f64| super::super::panel_at(b, Point::new(x, y)).expect("a panel"); + let (corner, under, tip) = (at(80.0, 20.0), at(115.0, 20.0), at(135.0, 20.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [135.0, -20.0, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(corner), "the top right panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(under), "the first flap, from the back"); +} + +#[test] +fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() { + // The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the + // left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(52.0, 20.0), (58.0, 20.0), (58.0, 40.0), (52.0, 40.0)], true, Cut, 2, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(80.0, 0.0), (80.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let through_window = draw(front()).panel_at(55, 30); + let from_back = draw(Camera { rotate_y: 180.0, ..front() }).panel_at(45, 30); + let flaps: Vec = (0..b.panels.len()).filter(|&i| i != f.base).collect(); + assert!(through_window.is_some_and(|p| flaps.contains(&p)), "{through_window:?}"); + assert!(from_back.is_some_and(|p| flaps.contains(&p)), "{from_back:?}"); + assert_ne!(through_window, from_back); +} + +#[test] +fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { + // The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to + // 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(90.0, 0.0), (90.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(15.0, 0.0), (15.0, 60.0)], false, Crease, 4, Some(0.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 140 - x in the image. + let starting_at = |x0: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x0).abs() < 1e-6)); + let right_flap = starting_at(90.0).expect("the right flap"); + // Folded back about x 30, the left flap's part from 15 to 30 lies at 30 to 45 and its part from + // 0 to 15 at 45 to 60. + let (inner, outer) = (starting_at(15.0).expect("the left flap's inner part"), starting_at(0.0).expect("its outer part")); + let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); + // Either flap may be in front, but the same one at both samples. + let right = (near, far) == (Some(right_flap), Some(right_flap)); + let left = (near, far) == (Some(inner), Some(outer)); + assert!(right || left, "{near:?} {far:?}: right flap {right_flap}, left flap {inner} and {outer}"); +} + +#[test] +fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() { + // Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap + // (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and + // the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(20.0, 0.0), (20.0, 60.0)], false, Crease, 2, Some(-180.0)), + line(&[(70.0, 0.0), (70.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (tip, left, right) = (starts_at(0.0), starts_at(20.0), starts_at(140.0)); + let camera = Camera { width: 210, center: [105.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 210 - x in the image. + let (flaps_only, with_tip) = (img.panel_at(210 - 90, 30), img.panel_at(210 - 110, 30)); + if flaps_only == Some(right) { + assert_eq!(with_tip, Some(right), "the right flap covers the left flap and the tip on it"); + } else { + assert_eq!((flaps_only, with_tip), (Some(left), Some(tip)), "the left flap, and the tip on it, cover the right flap"); + } +} + +#[test] +fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() { + // The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to + // 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + // The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base. + for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] { + let base = middle + 20.0; + let end = base + middle + 10.0; + let lines = [ + line(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(base, 0.0), (base, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(base + middle, 0.0), (base + middle, 60.0)], false, Crease, 3, Some(tip_angle)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let tip = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (base + middle)).abs() < 1e-6)).expect("the tip"); + let back = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: back }).expect("drawn"); + assert_eq!(img.panel_at(100 - 25, 30), Some(tip), "{middle} pt, {tip_angle}°"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(25, 30), Some(f.base), "{middle} pt, {tip_angle}°"); + } +} + +#[test] +fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_lid() { + // A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to + // 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps + // meet in one plane 40 pt below the base and overlap from x 140 to 160. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0)); + let lines = [ + line(&[(0.0, 0.0), (300.0, 0.0), (300.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + crease(60.0, 2), + crease(100.0, 3), + crease(200.0, 4), + crease(240.0, 5), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + // Looking up at the lid from below, a little to one side and then the other, at its middle. + let shown = |rotate_y: f64| { + let camera = Camera { width: 200, rotate_y, center: [150.0, -30.0, -40.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(100, 50) + }; + let (left, right) = (shown(175.0), shown(185.0)); + assert!(left.is_some_and(|p| p != f.base), "{left:?}"); + assert_eq!(left, right); +} + +#[test] +fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() { + // The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100, + // with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded + // at -180° onto the panel's printed side, where they overlap from y 20 to 40. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let shown = |tilt: f64| { + let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(100.0, -40.0), (100.0, 0.0)], false, Cut, 2, None), + line(&[(100.0, 60.0), (100.0, 100.0)], false, Cut, 3, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 4, Some(tilt)), + line(&[(100.0, 0.0), (200.0, 0.0)], false, Crease, 5, Some(-180.0)), + line(&[(100.0, 60.0), (200.0, 60.0)], false, Crease, 6, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 200, center: [150.0, -30.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0)); + let shown = img.panel_at(100, 50); + if shown == flap(-40.0) { + "above" + } else if shown == flap(60.0) { + "below" + } else { + "neither" + } + }; + let (up, down) = (shown(1.0), shown(-1.0)); + assert_ne!(up, "neither"); + assert_eq!(up, down); +} + +#[test] +fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() { + // The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180° + // onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(60.0, 0.0), (60.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 3, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(60.0), starts_at(100.0)); + let mut sides = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the wall from one side and then the other, the middle row of the view. + let camera = Camera { width: 200, height: 100, rotate_y, center: [60.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[wall].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = |p: usize| (0..img.width).filter(|&x| img.panel_at(x, 50) == Some(p)).count(); + let (walls, flaps) = (count(wall), count(flap)); + if printed { + assert!(flaps > 25 && walls < 15, "from the wall's printed side the flap covers it: wall {walls} px, flap {flaps} px"); + } else { + assert!(flaps == 0 && walls > 35, "from the back the wall covers the flap: wall {walls} px, flap {flaps} px"); + } + sides.push(printed); + } + assert_ne!(sides[0], sides[1], "both sides of the wall are looked at"); +} + +#[test] +fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_side() { + // The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each + // with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover + // the same 100 pt. Looking straight through that end, the base and walls are edge on. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(40.0, 0.0), (40.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(90.0)), + line(&[(0.0, 60.0), (40.0, 60.0)], false, Crease, 4, Some(90.0)), + line(&[(140.0, 60.0), (180.0, 60.0)], false, Crease, 5, Some(90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6 && r.y0 > 59.0)).expect("a flap"); + let (left, right) = (flap(0.0), flap(140.0)); + let shown = |rotate_x: f64| { + let camera = Camera { width: 300, height: 300, rotate_x, center: [90.0, -60.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = + |p: usize| (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(p)).count(); + (count(left), count(right)) + }; + let (one, other) = (shown(90.0), shown(-90.0)); + // Each view shows one flap over (nearly) the whole of the other. + let winner = |(l, r): (usize, usize)| { + if l > 10 * r.max(1) { + Some(left) + } else if r > 10 * l.max(1) { + Some(right) + } else { + None + } + }; + assert!(winner(one).is_some() && winner(other).is_some(), "the flaps cover the same end: {one:?} {other:?}"); + assert_ne!(winner(one), winner(other), "{one:?} {other:?}"); +} + +#[test] +fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() { + // A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90° + // and -90°, so the last one comes round and lies on the base's plane over part of it. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(-90.0)), + line(&[(200.0, 0.0), (200.0, 60.0)], false, Crease, 4, Some(-90.0)), + line(&[(240.0, 0.0), (240.0, 60.0)], false, Crease, 5, Some(-90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 240.0).abs() < 1e-6)).expect("the flap"); + // The panels between the base and the flap all lie behind the base's printed side. + for (i, (panel, folded)) in b.panels.iter().zip(&f.panels).enumerate() { + let r = panel.outline.bounds().expect("bounds"); + let z = folded.pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0))[2]; + if i != f.base && i != flap { + assert!(z < -1.0, "panel {i} at z {z}"); + } + } + // At x 90 the flap lies on the base: from the front the base covers it, from the back it + // covers the base. + let at = |rotate_y: f64, x: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(x, 50) + }; + assert_eq!(at(0.0, 200 - 10), Some(f.base)); + assert_eq!(at(180.0, 200 + 10), Some(flap)); +} + +#[test] +fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from() { + // A strip 60 pt tall: the base (x 0 to 100) and panels 20, 20, 40, 40 and 20 pt wide, then a + // flap (240 to 270, y 0 to 30), folded 90°, -90°, -90°, -90°, -90° and 90°. The 20 pt wall the + // flap folds from stands on the printed side of the base, and the flap lands on the base at x + // 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60), + // through the base's plane, which moves its middle to the other side of that plane. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with + // a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side. + let shown = |tab: bool, cutout: f64| { + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = if tab { + vec![ + line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (340.0, 30.0), (340.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(240.0, 30.0), (270.0, 30.0)], false, Cut, 2, None), + ] + } else { + vec![line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (0.0, 60.0)], true, Cut, 1, None)] + }; + let creases = + [(100.0, 60.0, 90.0), (120.0, 60.0, -90.0), (140.0, 60.0, -90.0), (180.0, 60.0, -90.0), (220.0, 60.0, -90.0), (240.0, 30.0, 90.0)]; + for (i, (x, high, a)) in creases.into_iter().enumerate() { + let key = 10 * (i as u64 + 1); + if cutout > 0.0 { + let (lo, hi) = if cutout > 5.0 { (2.0, high - 2.0) } else { (high / 2.0 - 5.0, high / 2.0 + 5.0) }; + let w = cutout.min(5.0); + lines.push(line(&[(x - w, lo), (x + w, lo), (x + w, hi), (x - w, hi)], true, Cut, key, None)); + lines.push(line(&[(x, 0.0), (x, lo)], false, Crease, key + 1, Some(a))); + lines.push(line(&[(x, hi), (x, high)], false, Crease, key + 2, Some(a))); + } else { + lines.push(line(&[(x, 0.0), (x, high)], false, Crease, key, Some(a))); + } + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(220.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let m = middle(flap); + assert!(m[2].abs() < 1e-6 && (m[0] - 65.0).abs() < 1e-6, "the flap lies on the base: {m:?}"); + assert_eq!(middle(wall)[2] > 0.0, !tab, "the wall's middle is on the printed side without the tab only"); + // The flap's row at y 5, at x 65, from the front and from the back (mirrored). + let at = |rotate_y: f64, px: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(px, 25) + }; + let named = |p: Option| match p { + Some(p) if p == f.base => "base", + Some(p) if p == flap => "flap", + _ => "other", + }; + (named(at(0.0, 200 - 35)), named(at(180.0, 200 + 35))) + }; + assert_eq!(shown(false, 0.0), ("flap", "base")); + assert_eq!(shown(true, 0.0), ("flap", "base"), "the side next to the hinge decides, not the wall's middle"); + assert_eq!(shown(false, 5.0), ("flap", "base"), "a hinge broken by a cutout"); + assert_eq!(shown(true, 5.0), ("flap", "base"), "both"); + assert_eq!(shown(true, 6.0), ("flap", "base"), "hinges joined only near their ends"); +} + +#[test] +fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_came_from() { + // A strip 30 pt tall: the base (x 0 to `base`), a panel 10 pt wide folded down behind it, one + // 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp + // `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that + // lies on the base from where the ramp ends. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let shown = |base: f64, ramp: f64, drop: f64| { + // To the millionth of a degree a line keeps, and the drop that ramp comes down by. + let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees()); + let drop = ramp * tilt.to_radians().sin(); + let up = base + 30.0; + let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)]; + let end = up + 10.0 + drop + ramp + 30.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (end - 30.0)).abs() < 1e-6)).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let r = b.panels[flap].outline.bounds().expect("bounds"); + let m = f.panels[flap].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)); + let x = base + 20.0 - ramp - 15.0; + assert!(m[2].abs() < 1e-6 && (m[0] - x).abs() < 1e-2 && x > 0.0, "the flap lies on the base at {x}: {m:?}"); + // The flap's middle, from the front and from the back. + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + (at(0.0) == Some(flap), at(180.0) == Some(f.base)) + }; + assert_eq!(shown(100.0, 40.0, 0.01), (true, true), "a 40 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.01), (true, true), "a 500 pt ramp 0.01 pt high"); + assert_eq!(shown(2100.0, 2000.0, 0.01), (true, true), "a 2,000 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.001), (true, true), "a 500 pt ramp 0.001 pt high"); +} + +#[test] +fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_from() { + // A strip 30 pt tall: the base (x 0 to 1,000) and panels 100, 300, 200 and 50 pt wide, folded + // `tilt`, 180°, -2 `tilt` and `tilt`: at 0.04° the 200 pt panel comes back down onto the base's + // plane from about 0.14 pt off it, at 0.00001° from 0.00004 pt, and the last panel lies on the + // base. + for tilt in [0.04, 0.00001] { + flap_brought_back_by_folds_all_near_flat(tilt); + } +} + +fn flap_brought_back_by_folds_all_near_flat(tilt: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)]; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (ramp, flap) = (starts_at(1400.0), starts_at(1600.0)); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let (m, above) = (middle(flap), middle(ramp)[2]); + assert!(m[2].abs() < 1e-3 && (0.0..1000.0).contains(&m[0]) && above.abs() > tilt * 0.25, "the flap lies on the base: {m:?}, the ramp at {above}"); + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + let (from_front, from_back) = (at(0.0), at(180.0)); + if above > 0.0 { + assert_eq!((from_front, from_back), (Some(flap), Some(f.base)), "{tilt}°"); + } else { + assert_eq!((from_front, from_back), (Some(f.base), Some(flap)), "{tilt}°"); + } +} + +#[test] +fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() { + // The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's + // first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)]; + lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0))); + for (i, (x, a)) in [(100.0, 90.0), (120.0, -90.0), (140.0, -90.0), (180.0, -90.0), (220.0, -90.0)].into_iter().enumerate() { + lines.push(line(&[(x, 0.0), (x, 60.0)], false, Crease, 3 + i as u64, Some(a))); + } + lines.push(line(&[(240.0, 0.0), (240.0, 30.0)], false, Crease, 9, Some(90.0))); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (panel, flap) = (starts_at(0.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(f.base, starts_at(-150.0)); + let mut seen = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the panel from one side and then the other: how many pixels show the flap. + let camera = Camera { width: 400, height: 200, rotate_y, center: [0.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[panel].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flaps = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(flap)).count(); + seen.push((printed, flaps)); + } + let (from_print, from_back) = if seen[0].0 { (seen[0].1, seen[1].1) } else { (seen[1].1, seen[0].1) }; + assert_ne!(seen[0].0, seen[1].0, "both sides of the panel are looked at"); + assert!(from_print > 600 && from_back == 0, "the flap shows on the panel's printed side only: {seen:?}"); +} + +#[test] +fn a_strip_rolled_up_45_times_keeps_the_base_in_front() { + // A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so + // each panel rolls under the one before it and all of them lie behind the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let end = 60.0 + 45.0 * 50.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| { + let x = 60.0 + 50.0 * f64::from(i); + super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 10 + u64::from(i), + angle: Some(180.0), + } + })); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(40, 30), Some(f.base)); +} + +#[test] +fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() { + // A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to + // 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies + // behind the flat strips at x 65 to 75. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0))); + lines.push(crease(105.0, 2, 180.0)); + lines.push(crease(145.0, 3, 180.0)); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (strip, middle, flap) = (starts_at(70.0), starts_at(105.0), starts_at(145.0)); + let camera = Camera { width: 160, center: [80.0, -50.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown = img.panel_at(70, 30); + assert_eq!(shown, Some(strip), "a flat strip, not the flap ({flap}) or the folded panel ({middle})"); +} + #[test] fn a_hole_in_a_panel_is_left_empty() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..6781a2c64d 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() { + // A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes + // the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest + // panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the + // origin and 3,000,000 pt to the right. + let own_tree = |dx: f64| { + let lines = |closing: Option| { + let crease = |a: (f64, f64), b: (f64, f64), key: u64| { + let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key); + l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 }); + l + }; + vec![ + cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1), + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (b, issues) = check(&lines(None)); + assert!(issues.is_empty(), "{issues:?}"); + let level = fold(&b[0], None, 1.0, TOL).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = b[0].hinges[closing].keys[0]; + let (b, issues) = check(&lines(Some(key))); + assert!(issues.is_empty(), "{issues:?}"); + let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds"); + f.stack.root == f.base + }; + assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree"); + assert!(own_tree(3_000_000.0), "far from the origin too"); +} + +#[test] +fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() { + // A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the + // grid's right squares. Every crease is at 0° but the one between the two left squares, at a + // millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out + // and places the other square at most 0.0000001 pt from where the fold's own tree does. + let mut lines = vec![ + cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1), + crease((5.0, 0.0), (5.0, 5.0), 2), + crease((5.0, 5.0), (5.0, 10.0), 3), + crease((0.0, 5.0), (5.0, 5.0), 4), + crease((5.0, 5.0), (10.0, 5.0), 5), + crease((10.0, 0.0), (10.0, 10.0), 6), + ]; + for l in &mut lines { + l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 }); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge"); + let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds"); + assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4])); + assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns"); +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 96b6a36291..e8b705a54a 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -8,6 +8,9 @@ description = "VectorCraft tool state machines: pointer events in, commands and [lints] workspace = true +[features] +testing = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +vectorcraft-tools = { workspace = true, features = ["testing"] } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cec57b2887..cdc7f6f7dc 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -33,6 +33,9 @@ mod live_paint; mod lookup; mod map; +#[cfg(all(feature = "testing", not(target_arch = "wasm32")))] +pub mod testing; + use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] @@ -260,7 +263,13 @@ struct PendingMerge { #[cfg(not(target_arch = "wasm32"))] fn spawn_merge(map: Arc, touched: Touched, gap: f64, inputs: Vec) -> Option> { let (tx, done) = std::sync::mpsc::channel(); + #[cfg(feature = "testing")] + let gate = testing::take(); let spawned = std::thread::Builder::new().name("vectorcraft-shape-builder-merge".into()).spawn(move || { + #[cfg(feature = "testing")] + if let Some(gate) = gate { + gate.wait(); + } // The tool may have dropped the receiver meanwhile (another tool, another document). let _ = tx.send(merge_geometry(&map, &touched, gap, &inputs)); }); diff --git a/crates/tools/src/builder/testing.rs b/crates/tools/src/builder/testing.rs new file mode 100644 index 0000000000..a378014e32 --- /dev/null +++ b/crates/tools/src/builder/testing.rs @@ -0,0 +1,75 @@ +//! Channel control for the next Shape Builder merge started on the calling thread. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvError, Sender, channel}; + +thread_local! { + static NEXT: RefCell> = const { RefCell::new(None) }; +} + +/// Holds a merge worker until released. Dropping the gate also releases the worker. +pub struct MergeGate { + id: Arc<()>, + started: Receiver<()>, + release: Option>, + _thread: PhantomData>, +} + +impl MergeGate { + /// Waits until the worker reaches the gate. + pub fn wait_started(&self) -> Result<(), RecvError> { + self.started.recv() + } + + /// Allows the worker to compute the merge. + pub fn release(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + } +} + +impl Drop for MergeGate { + fn drop(&mut self) { + NEXT.with_borrow_mut(|next| { + if next.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.id, &self.id)) { + *next = None; + } + }); + self.release(); + } +} + +pub(super) struct WorkerGate { + id: Arc<()>, + started: Sender<()>, + release: Receiver<()>, +} + +impl WorkerGate { + pub(super) fn wait(self) { + let _ = self.started.send(()); + let _ = self.release.recv(); + } +} + +pub(super) fn take() -> Option { + NEXT.with_borrow_mut(Option::take) +} + +/// Pauses the next merge started on this thread. Returns an error if a gate is already waiting. +pub fn pause_next_merge() -> Result { + NEXT.with_borrow_mut(|next| { + if next.is_some() { + return Err("a Shape Builder merge gate is already waiting on this thread"); + } + let id = Arc::new(()); + let (started_tx, started) = channel(); + let (release, release_rx) = channel(); + *next = Some(WorkerGate { id: id.clone(), started: started_tx, release: release_rx }); + Ok(MergeGate { id, started, release: Some(release), _thread: PhantomData }) + }) +} diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 0d0106eddb..0b19e3e4c0 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -47,14 +47,20 @@ look = "The same pointer as Arrow, hollow: white with a dark outline." [[cursor]] id = "DirectAnchor" group = "Selection" -shown_when = ["Direct Selection over an anchor of a path that isn't selected."] +shown_when = [ + "Direct Selection over an anchor of a path that isn't selected.", + "The Quick Pen, with no path being drawn, over an anchor of a selected path that is not itself selected (a click selects it, a drag moves it).", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small hollow square badge (an unselected anchor)." [[cursor]] id = "DirectAnchorSelected" group = "Selection" -shown_when = ["Direct Selection over an anchor of a selected path."] +shown_when = [ + "Direct Selection over an anchor of a selected path.", + "The Quick Pen, with no path being drawn, over a selected anchor.", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small filled square badge (a selected anchor)." @@ -137,6 +143,7 @@ shown_when = [ "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", + "The Quick Pen, with no path being drawn, over a segment of a selected path, and while a drag moves an anchor or a segment.", ] hotspot = "The centre." look = "A four-way move cursor." @@ -242,6 +249,7 @@ group = "Pen" shown_when = [ "The Pen (not drawing) over an end of an open path (a click continues it).", "The Curvature tool over an open end.", + "The Quick Pen (not drawing) over an end of an open path (a click continues it, a drag on a selected path's end moves it).", ] hotspot = "The nib's tip." look = "The Pen nib with a slash badge." diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index 7124f55cda..05aaef2feb 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -14,21 +14,35 @@ //! nothing. The pointer passes over the circles the tool drew until the selection holds none of //! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is //! made outside the tool. +//! +//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the +//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); +//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › +//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach +//! stays the same); `annotateRadius` off hides the radius label; +//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every +//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off +//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every +//! switch is on by default. use std::collections::HashSet; -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::{MAX_COORD, NodeId}; -use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with}; +use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes}; +use crate::option_check; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub const ID: &str = "curvatureCircle"; -/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance -/// is larger. -const SNAP_PX: f64 = 5.0; +/// The range of `snapTolerance` (screen points). +pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0); +/// `snapTolerance` by default (screen points). +pub const DEFAULT_SNAP: f64 = 5.0; +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]; /// How far (screen points) the pointer travels from a press before the press counts as a drag. const DRAG_PX: f64 = 2.0; /// Half the length (screen points) of each arm of the cross at the circle's center. @@ -52,8 +66,37 @@ enum Found { Refused(&'static str, Point), } +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Options { + snap_tolerance: f64, + snap_without_guides: bool, + annotate_radius: bool, + standard_anchors: bool, + constant_radius: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "snapWithoutGuides" => &mut self.snap_without_guides, + "annotateRadius" => &mut self.annotate_radius, + "standardAnchors" => &mut self.standard_anchors, + "constantRadius" => &mut self.constant_radius, + _ => return None, + }) + } +} + #[derive(Default)] pub struct CurvatureCircleTool { + options: Options, /// The point under the pointer, and whether Shift was held. hover: Option<(Hit, bool)>, /// The press in progress, where the pointer was pressed: what a release draws. @@ -64,6 +107,17 @@ pub struct CurvatureCircleTool { drawn: HashSet, } +/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides › +/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no +/// further than Selection & Anchor Display › Tolerance. +fn reach(cx: &ToolContext, o: &Options) -> f64 { + let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol()); + if !cx.smart_guides && !o.snap_without_guides { + return snap.min(cx.pick_tol()); + } + snap +} + impl CurvatureCircleTool { /// After Deselect or a selection made outside the tool, the selection holds none of the /// circles the tool drew, and the pointer reaches them again. @@ -77,10 +131,9 @@ impl CurvatureCircleTool { } } -/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. -fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { - let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); +fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet) -> Option { let mut best: Option<(Hit, f64)> = None; for id in crate::draw2::candidate_paths(cx) { if skip.contains(&id) { @@ -103,14 +156,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { /// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the /// path or segment is gone. -fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { +fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option { let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; if hit.segment >= sp.segment_count() { return None; } let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); - Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { - Ok(c) if on_canvas(&c) => Found::Circle(c), + Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) { + Ok(c) if on_canvas(&c, o) => Found::Circle(c), Ok(_) => Found::Refused("Circle too large", at), Err(NoCircle::Straight) => Found::Refused("Straight segment", at), Err(NoCircle::Cusp) => Found::Refused("Cusp", at), @@ -118,10 +171,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { }) } -/// Does the circle stay on the canvas? -fn on_canvas(c: &CurvatureCircle) -> bool { +/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors +/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path. +fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData { let (p, r) = (c.center, c.radius); - [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) + if !o.standard_anchors { + return shapes::circle_with_anchors_at(p, r, &[c.at]); + } + shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r)) +} + +/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it? +fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool { + drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) } impl Tool for CurvatureCircleTool { @@ -134,13 +196,14 @@ impl Tool for CurvatureCircleTool { return vec![]; } self.forget_unselected(cx); + let (o, tol) = (self.options, reach(cx, &self.options)); match ev.kind { PointerKind::Move => { - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); vec![] } PointerKind::Down => { - self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); self.hover = self.press; self.from = ev.pos; vec![] @@ -155,12 +218,21 @@ impl Tool for CurvatureCircleTool { } PointerKind::Up => { let press = self.press.take(); - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); let Some((hit, convex)) = press else { return vec![] }; - if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) { return vec![]; } - let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + let anchors = if o.standard_anchors { "standard" } else { "touch" }; + let p = json!({ + "id": hit.id.0, + "subpath": hit.subpath, + "segment": hit.segment, + "t": hit.t, + "convex": convex, + "constantRadius": o.constant_radius, + "anchors": anchors, + }); vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -236,10 +308,10 @@ impl Tool for CurvatureCircleTool { let Some((hit, convex)) = self.hover else { return vec![] }; let color = crate::draw2::FEEDBACK; let mut o = vec![]; - match found(cx, hit, convex) { + match found(cx, hit, convex, &self.options) { Some(Found::Circle(c)) => { let r = c.radius; - let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + let path = drawn_path(&c, &self.options).to_bezpath(); // The outline is drawn solid when it is longer than DASHED_PX on screen. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); @@ -248,7 +320,7 @@ impl Tool for CurvatureCircleTool { o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); - if cx.measurement_labels { + if cx.measurement_labels && self.options.annotate_radius { let star = if c.nominal { "*" } else { "" }; o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); } @@ -262,6 +334,39 @@ impl Tool for CurvatureCircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + json!({ + "snapTolerance": o.snap_tolerance, + "snapWithoutGuides": o.snap_without_guides, + "annotateRadius": o.annotate_radius, + "standardAnchors": o.standard_anchors, + "constantRadius": o.constant_radius, + }) + } + + /// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "snapTolerance" { + option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1) + } else if SWITCHES.contains(&key) { + option_check::boolean(key, value) + } else { + Err(option_check::unknown(key)) + } + } + + /// Sets one option; a value the option does not take leaves it as it was. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "snapTolerance" { + if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) { + self.options.snap_tolerance = v; + } + } else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) { + *switch = on; + } + } } #[cfg(test)] diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index 1dccebecc6..76df830591 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -305,3 +305,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() { let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); assert_eq!(ids.get(circle + 1), Some(&ID)); } + +/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart +/// Guides off the pointer reaches no further than the selection tolerance, and never further than +/// with the switch on; with Smart Guides on it reaches as far as before. +#[test] +fn the_snap_options_set_how_far_the_pointer_reaches() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]); + t.set_option("snapTolerance", &json!(10)); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2); + t.set_option("snapTolerance", &json!(5)); + t.set_option("snapWithoutGuides", &json!(false)); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2); + let guides = ToolContext { smart_guides: true, ..cx }; + assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2); + let wide = ToolContext { selection_tolerance: 8.0, ..cx }; + assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2); + assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]); +} + +/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius +/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends +/// `anchors: "touch"`. +#[test] +fn the_label_and_circle_options_change_what_is_shown_and_drawn() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let measure = |t: &CurvatureCircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard"))); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + assert!(measure(&t).is_some_and(|m| m.ends_with('*'))); + t.set_option("annotateRadius", &json!(false)); + assert_eq!(measure(&t), None); + t.set_option("annotateRadius", &json!(true)); + let arc = preview(&t.overlays(&cx)).unwrap(); + t.set_option("constantRadius", &json!(false)); + assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t)); + assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width()); + t.set_option("standardAnchors", &json!(false)); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch"))); +} + +/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle, +/// or with `standardAnchors` off starting where the circle touches the path. +#[test] +fn the_preview_follows_the_anchor_options() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let start = |t: &CurvatureCircleTool, cx: &ToolContext| { + t.overlays(cx).iter().find_map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default())); + let upright = start(&t, &cx).unwrap(); + let turned = ToolContext { constrain_angle: 30.0, ..cx }; + assert_eq!(start(&t, &turned), Some(upright)); + assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}"); + t.set_option("standardAnchors", &json!(false)); + let at = start(&t, &cx).unwrap(); + assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}"); +} + +/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are +/// errors, and `set_option` leaves the option as it was for them. +#[test] +fn invalid_options_are_refused() { + let mut t = CurvatureCircleTool::default(); + assert!(t.check_option("snapTolerance", &json!(0)).is_err()); + assert!(t.check_option("snapTolerance", &json!(41)).is_err()); + assert!(t.check_option("snapTolerance", &json!("5")).is_err()); + assert!(t.check_option("annotateRadius", &json!(1)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok()); + let before = t.options(); + t.set_option("snapTolerance", &json!(0)); + t.set_option("annotateRadius", &json!("no")); + assert_eq!(t.options(), before); +} diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index abae4bc5ea..92377ac2d7 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,6 +12,7 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! While no path is being drawn, the tool edits the selected paths ([`edit`]). //! //! A handle stands beyond each end of the path being drawn, or, while none is, of the selected //! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc @@ -33,6 +34,8 @@ //! the document or the selection changes, the canvas hovers the still pointer again. Shift does //! not constrain Quick Pen points, so it does not change the snapping. +mod edit; + use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -44,6 +47,7 @@ use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use edit::{Edit, Grab}; use length::EndPiece; /// The tool's id. @@ -449,6 +453,8 @@ pub struct QuickPenTool { turn: f64, drawing: Option, press: Option, + /// A press on an anchor or a segment of a selected path while no path is being drawn. + edit: Option, length: Option, hover: Option, snap: DrawSnap, @@ -466,6 +472,7 @@ impl Default for QuickPenTool { turn: DEFAULT_TURN, drawing: None, press: None, + edit: None, length: None, hover: None, snap: DrawSnap::default(), @@ -657,8 +664,9 @@ impl QuickPenTool { } /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from - /// an end of an open path, the path goes on). - fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + /// an end of an open path, the path goes on). With no path being drawn, a press on an anchor + /// or a segment of a selected path waits to see whether it drags ([`edit`]). + fn press_down(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } @@ -689,11 +697,11 @@ impl QuickPenTool { self.length = Some(drag); return vec![]; } - self.click(cx, p) + self.click(cx, p, shift) } /// What a press away from a length handle, or a click on one, draws. - fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { + fn click(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -724,28 +732,90 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } + // An anchor of a selected path comes first, then an open end, then a selected path's + // segment. + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) { - // From its start, `continue_from` reverses the path first; the tool then sees it. - self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); - let mut out = continue_from(cx, id, si, at_first); - out.push(drawn()); - return out; + return self.continue_path(cx, id, si, at_first); } + if let Some(grab) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } + self.start_path(cx, p) + } + + /// Goes on drawing from an end of subpath `si` of path `id`. + fn continue_path(&mut self, cx: &ToolContext, id: NodeId, si: usize, at_first: bool) -> Vec { + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = vec![]; + // Anchors selected by an earlier click or drag: the path is selected whole again. + if !cx.selection.anchors.is_empty() || !cx.selection.segments.is_empty() { + let top = cx.doc.parent_of(id).filter(|p| cx.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + out.push(Action::Exec("select.set".into(), json!({"ids": [top.0]}))); + } + out.extend(continue_from(cx, id, si, at_first)); + out.push(drawn()); + out + } + + /// Starts a new path at `p`. + fn start_path(&mut self, cx: &ToolContext, p: Point) -> Vec { let q = self.snap.press(cx, p, &[], None); self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } - /// Ends the path being drawn; a press that added a piece is taken back. - fn end(&mut self) -> Vec { + /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken + /// back. A move that another command's edit interrupted is kept with that edit. + fn end(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.pointer = None; self.snap.clear(); + let moved = self.edit.take().filter(|e| e.began).map(|mut e| if e.open(cx) { Action::Cancel } else { Action::Commit }); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], - _ => vec![], + _ => moved.into_iter().collect(), + } + } + + /// The release of a press on an anchor or a segment of a selected path: a drag, also one let + /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends + /// its undo step. A click on an end of an open path goes on drawing from it, a click on another + /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a + /// click on a segment starts a new path there. A click whose path or selection another command + /// changed while the press was down does nothing. + fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { + if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { + let mut out = e.drag(cx, p); + // A drag that could not begin (its path or the selection changed under the press) has + // no step to end. + out.extend(e.finish(cx)); + return out; + } + if !e.unchanged(cx) { + return vec![]; + } + match e.grab { + Grab::Anchor { id, si, ai, .. } if e.shift => { + // `select.anchors` toggles from every anchor of a path selected whole on its own, + // so the first Shift-click there selects the anchor alone. + let whole = cx.selection.anchors.is_empty() && cx.selection.objects.len() <= 1; + let mode = if whole { "set" } else { "toggle" }; + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": mode}))] + } + Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), + Grab::Anchor { id, si, ai, .. } => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } + Grab::Segment { .. } => self.start_path(cx, e.start), } } @@ -929,7 +999,12 @@ impl QuickPenTool { return if drag.begun { vec![Action::Commit] } else { vec![] }; } if !drag.dragged { - let mut out = self.click(cx, drag.press); + let mut out = self.click(cx, drag.press, false); + // A handle over a segment of the selected path: the press has ended, so the click + // there is released at once. + if let Some(e) = self.edit.take() { + out.extend(self.release_edit(cx, e, drag.press)); + } if self.press.take().is_some_and(|pr| pr.begun) { out.extend([Action::Commit, Action::Notify(PLACED.into())]); } @@ -978,7 +1053,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() || self.length.is_some() + self.press.is_some() || self.edit.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -992,7 +1067,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() || self.length.is_some() { + if self.press.is_some() || self.edit.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -1003,10 +1078,16 @@ impl Tool for QuickPenTool { } self.hover = None; self.pointer = None; - self.press_down(cx, p) + self.press_down(cx, p, ev.mods.shift) } PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { + if let Some(e) = self.edit.as_mut() { + if !e.began && p.distance(e.start) < cx.tol(DRAG_PX) { + return vec![]; + } + return e.drag(cx, p); + } let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { return vec![]; @@ -1019,6 +1100,9 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if let Some(e) = self.edit.take() { + return self.release_edit(cx, e, p); + } if self.length.is_some() { self.snap.clear(); // The end goes where the press is let go, also past the last drag. @@ -1054,6 +1138,12 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == edit::MOVED { + if let Some(e) = self.edit.as_mut() { + e.revision = Some(cx.revision); + } + return; + } if what == DRAWN && let Some(drag) = self.length.as_mut() { @@ -1106,6 +1196,8 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + // The session takes back what an edit moved; the release that follows does nothing. + self.edit = None; if let Some(drag) = self.length.take() { self.restore_last_piece(&drag); if let Some(dr) = self.drawing.as_mut() { @@ -1158,7 +1250,7 @@ impl Tool for QuickPenTool { ToolKey::Enter if self.length.is_some() => vec![], // C and [ ] change the last piece once the drag has ended. ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], - ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Escape | ToolKey::Enter => self.end(cx), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { return vec![]; @@ -1206,15 +1298,16 @@ impl Tool for QuickPenTool { } } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().and_then(|mut e| e.finish(cx)); if self.length.take().is_some_and(|drag| drag.begun) { return vec![Action::Commit]; } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], - _ => vec![], + _ => moved.into_iter().collect(), } } @@ -1238,6 +1331,9 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + if let Some(e) = &self.edit { + o.extend(e.guides.iter().cloned()); + } // The length handles: a line from each end to a handle circle beyond it; during a drag, the // one being dragged, where the changed end is. let handles: Vec<(Point, Point)> = match &self.length { @@ -1247,7 +1343,7 @@ impl Tool for QuickPenTool { let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() } - None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None if self.press.is_none() && self.edit.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), None => vec![], }; for &(a, b) in &handles { @@ -1306,7 +1402,17 @@ impl Tool for QuickPenTool { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; } - if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + if let Some(e) = &self.edit { + return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; + } + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + return edit::cursor(cx, grab); + } + if open_end_at(cx, p, tol, None).is_some() { + return Cursor::PenContinue; + } + grab.map_or(Cursor::Pen, |grab| edit::cursor(cx, grab)) } fn options(&self) -> Value { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs new file mode 100644 index 0000000000..e06680d282 --- /dev/null +++ b/crates/tools/src/quickpen/edit.rs @@ -0,0 +1,211 @@ +//! Editing with the Quick Pen while no path is being drawn: a drag on an anchor of a selected path +//! moves it, and a drag on one of its segments moves that segment (`path.moveAnchors` with +//! `interpolate`: a segment with one moved end is turned and scaled to its new ends, so a line +//! stays a line and an arc stays an arc of the same angle; at a smooth point, where two arcs join, +//! the handles stay in line and the arcs bend to meet). The moved anchor snaps as a Direct +//! Selection drag's does. A click on an anchor selects it, Shift-click adds it to the selected anchors or takes it +//! out, and the canvas context menu's Delete then removes them (`edit.clear`). A click on an end +//! of an open path goes on drawing from it, as before. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{AnchorRef, Node, NodeId, Selection}; +use vectorcraft_geom::Point; + +use super::{same_node, shared_node}; +use crate::draw2::{anchor_in, segment_in, shown_paths}; +use crate::guides::{PointSnap, Targets}; +use crate::{Action, Cursor, Overlay, ToolContext}; + +/// The notice the tool asks for after each preview of a drag, to see the document's revision then. +pub(super) const MOVED: &str = "moved"; + +/// What a press holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Grab { + /// Anchor `ai` of subpath `si` of path `id`, at `at`; `end` when it is an end of an open subpath. + Anchor { id: NodeId, si: usize, ai: usize, at: Point, end: bool }, + /// The segment from anchor `seg` of subpath `si` of path `id` to the next one. + Segment { id: NodeId, si: usize, seg: usize }, +} + +impl Grab { + /// The path the grab is on. + pub(super) fn id(self) -> NodeId { + match self { + Grab::Anchor { id, .. } | Grab::Segment { id, .. } => id, + } + } + + /// The anchors the drag moves when they are not already selected: the anchor, or the + /// segment's two ends. + fn anchors(self, cx: &ToolContext) -> Option> { + match self { + Grab::Anchor { si, ai, .. } => Some(vec![(si, ai)]), + Grab::Segment { id, si, seg } => { + let n = cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.len(); + Some(vec![(si, seg), (si, (seg + 1).checked_rem(n)?)]) + } + } + } +} + +/// An anchor or a segment of a selected path under `p`, within the tool's point tolerance `tol`. +/// Anchors come before segments. +pub(super) fn grab_at(cx: &ToolContext, p: Point, tol: f64) -> Option { + let shown = shown_paths(cx); + if let Some((id, si, ai)) = anchor_in(cx, shown.iter().copied(), p, tol) { + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let at = sp.anchors.get(ai)?.p; + let end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); + return Some(Grab::Anchor { id, si, ai, at, end }); + } + segment_in(cx, shown, p, tol).map(|(id, si, seg, _)| Grab::Segment { id, si, seg }) +} + +/// The cursor over `grab`: an open end shows that a click goes on drawing from it, another anchor +/// that it can be selected and moved, and a segment that it moves. +pub(super) fn cursor(cx: &ToolContext, grab: Grab) -> Cursor { + match grab { + Grab::Anchor { end: true, .. } => Cursor::PenContinue, + Grab::Anchor { id, si, ai, .. } if cx.selection.partial(id).is_some_and(|s| s.contains(&(si, ai))) => Cursor::DirectAnchorSelected, + Grab::Anchor { .. } => Cursor::DirectAnchor, + Grab::Segment { .. } => Cursor::Move, + } +} + +/// A press on an anchor or a segment of a selected path, while no path is being drawn. +pub(super) struct Edit { + pub(super) grab: Grab, + /// Where the press went down. + pub(super) start: Point, + pub(super) shift: bool, + /// Whether the press has dragged far enough to move what it holds (an undo step began). + pub(super) began: bool, + /// Whether the last drag left what the press holds away from where it started. + pub(super) moved: bool, + /// The document's revision ([`ToolContext::revision`]) after the drag's last preview. + pub(super) revision: Option<(u64, u64)>, + /// Whether another command changed the document or the selection during the drag: the drag + /// then previews no more, and its undo step keeps that edit with the move as last shown. + pub(super) interrupted: bool, + /// The grabbed path as the document had it when the press went down. + pressed: Option>, + /// The selection when the press went down. + pressed_selection: Selection, + snap: Option, + pub(super) guides: Vec, +} + +impl Edit { + pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { + let pressed = shared_node(cx.doc, grab.id()).cloned(); + let pressed_selection = cx.selection.clone(); + Self { + grab, + start, + shift, + began: false, + moved: false, + revision: None, + interrupted: false, + pressed, + pressed_selection, + snap: None, + guides: vec![], + } + } + + /// Whether the drag began and still previews: no other command changed the document or the + /// selection since its last preview. + pub(super) fn open(&mut self, cx: &ToolContext) -> bool { + if self.began && self.revision.is_some_and(|r| r != cx.revision) { + self.interrupted = true; + } + self.began && !self.interrupted + } + + /// What ends a drag that began when the press is let go: a commit, or a cancel when the drag + /// came back to where it started and no other command's edit is in its undo step. + pub(super) fn finish(&mut self, cx: &ToolContext) -> Option { + if !self.began { + return None; + } + Some(if self.open(cx) && !self.moved { Action::Cancel } else { Action::Commit }) + } + + /// Whether the grabbed path and the selection are as they were when the press went down. + pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { + let path = match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + }; + path && *cx.selection == self.pressed_selection + } + + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the + /// segment, unless it is already selected, and begins the undo step; a drag that starts on + /// one of several selected anchors moves them all. When the grabbed path or the selection + /// changed after the press went down, the drag does not begin, and after another command's edit during the + /// drag it moves nothing more. + pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if self.began && !self.open(cx) { + return out; + } + if !self.began { + let id = self.grab.id(); + if !self.unchanged(cx) { + return out; + } + let Some(picked) = self.grab.anchors(cx) else { return out }; + // A drag on one of several selected anchors moves them all; a drag on a segment moves + // its two ends alone and leaves that segment selected, not its ends as anchors. + let already = match self.grab { + Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), + Grab::Segment { si, seg, .. } => { + cx.selection.objects == [id] + && cx.selection.anchors.len() == 1 + && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + && cx.selection.segments.len() == 1 + && cx.selection.segments.get(&id).is_some_and(|s| s.len() == 1 && s.contains(&(si, seg))) + } + }; + let moving = if already { + cx.selection.clone() + } else { + out.push(match self.grab { + Grab::Anchor { si, ai, .. } => Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"})), + Grab::Segment { si, seg, .. } => { + Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]], "mode": "set"})) + } + }); + let mut sel = Selection { objects: vec![id], ..Selection::default() }; + sel.anchors.insert(id, picked.into_iter().collect::>()); + sel + }; + out.push(Action::Begin("Move".into())); + // A held anchor snaps; the anchors and segments that stay put are targets too. + if matches!(self.grab, Grab::Anchor { .. }) { + self.snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &moving))); + } + self.began = true; + } + let d = match (self.grab, &self.snap) { + (Grab::Anchor { at, .. }, Some(snap)) => { + let (q, guides) = snap.snap_from(cx, at + (p - self.start), None); + self.guides = guides; + q - at + } + _ => p - self.start, + }; + if d.x.is_finite() && d.y.is_finite() { + self.moved = d.x != 0.0 || d.y != 0.0; + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + } + out.push(Action::Notify(MOVED.into())); + out + } +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index ce6fd5ec4b..34311e9d96 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -196,6 +196,34 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// With no path being drawn, the cursor over a selected path shows what a press there does: an +/// anchor is selected and moved, a selected anchor shows as one, and a segment moves. A press there +/// waits for a drag or a release instead of starting a path. +#[test] +fn a_selected_paths_anchors_and_segments_show_the_edit_cursors() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchor); + assert_eq!(t.cursor(&cx, pt(150.0, 100.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 130.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "select.segments" && v["mode"] == "set"), "{a:?}"); + assert!(matches!(&a[2], Action::Preview(c, v) if c == "path.moveAnchors" && v["dy"] == 30.0 && v["interpolate"] == true), "{a:?}"); + assert_eq!(t.cursor(&cx, pt(150.0, 130.0), Mods::default()), Cursor::Move); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 130.0)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.busy()); + s.anchors.insert(id, (0..4).map(|ai| (0, ai)).collect()); + let cx = crate::testutil::cx(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); +} + /// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of /// less and more than a half circle, flipped, and continuous arcs; a line has none. #[test] diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 185450a1ca..7c9bd3ce81 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -80,6 +80,8 @@ const ROWS: &[Row] = &[ (&["ellipse"], None, &["anchors"]), // Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center. (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]), + // Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`). + (&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 154afe235d..95487e91c0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } wat = { workspace = true } diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index aca41a2620..6696e4b0d3 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -91,6 +91,12 @@ fn adjustment(i: usize) -> (&'static str, &'static str, &'static [AdjustValue]) ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) } +/// The adjustments' names in `lang`, in [`ADJUSTMENTS`] order: each effect's name as the Effect +/// menu, History and Edit › Undo show it ([`crate::i18n::effect_name`]). +fn adjustment_names(lang: crate::i18n::Lang) -> Vec { + ADJUSTMENTS.iter().map(|a| crate::i18n::effect_name(lang, a.0).unwrap_or_else(|| crate::i18n::tr(lang, a.1).to_string())).collect() +} + /// Object › Plug-ins › Color Effects. pub fn menu() -> Vec { let cmd = |(label, id, p): (&'static str, &'static str, Value)| cp(label, id, p); @@ -153,7 +159,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } let mut st = std::mem::take(&mut app.addon_panels.color); - let entries: Vec> = ADJUSTMENTS.iter().enumerate().map(|(i, a)| Entry::new(i, tl!(a.1).to_string())).collect(); + let entries: Vec> = adjustment_names(crate::i18n::current()).into_iter().enumerate().map(|(i, name)| Entry::new(i, name)).collect(); FieldGroup::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Field::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Select::new(tl!("Adjustment").to_string(), Bind::bound(&mut st.index), &entries).show(ui); diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index b3ab29fdaa..506327e399 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::{ADJUSTMENTS, Picked}; use crate::VectorcraftApp; +use crate::i18n::LangExt; /// An app in a window with a selected red rectangle. fn app() -> VectorcraftApp { @@ -62,6 +63,36 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } } +/// Apply as Filter records a step that History and Edit › Undo name as the panel names the +/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +#[test] +fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); + let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); + if let Some((key, _, (_, max), ..)) = fields.first() { + params[*key] = json!(max); + } + app.run("addon.color.filter", json!({ "effect": id, "params": params })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(*id), "the step Apply as Filter records for {params}"); + app.addon_panels.color = Picked { index: i, ..Picked::default() }; + let app = std::rc::Rc::new(std::cell::RefCell::new(app)); + let shown = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); + fixture.room(egui::vec2(320.0, 700.0)); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let step = crate::panels::history::shown(&h); + fixture.settle(); + let texts: Vec = fixture.texts().iter().map(|t| t.text.clone()).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(texts.contains(&step), "{} {id}: {step:?} in {texts:?}", lang.code()); + } + } +} + #[test] fn the_halftone_effect_dialog_has_the_command_fields_and_edits_the_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 55ad5dd64d..d29066a126 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -99,8 +99,8 @@ fn pump_commit(app: &mut VectorcraftApp) { let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); - // PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label) - let answer = preview.run(app, *previewing, spec.command, spec.command, params); + let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); + let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 9a24a362eb..eb24e09c37 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -247,6 +247,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() { } } +#[test] +fn keeping_an_add_on_preview_records_the_command_name() { + let mut app = two_rects(); + let undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + + assert!(confirm(&app, id)); + frame(&mut app); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid"); +} + #[test] fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() { let mut app = two_rects(); diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 8656e0f7ad..9e4d188ddc 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -1,12 +1,14 @@ //! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected -//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu -//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it -//! (clicking one selects its objects); each document's list is kept until that document changes. Its -//! Fold Preview button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], -//! `ui.foldPreview`). +//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold +//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold +//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches… +//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the +//! Check Fold Lines menu item, checks the fold lines (`addon.packaging.check`) and lists the issues +//! found under it (clicking one selects its objects); each document's list is kept until that +//! document changes. Its Fold Preview button, like the Fold Preview menu item, shows the blank folded +//! in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -14,11 +16,17 @@ use std::sync::{Arc, Weak}; use craft::keymap::CommandRef; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{ActivateOn, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, WordSetCx as _}; +use craft::ui::contract::{ + ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _, clicked, +}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::UnitKind; +use craft::ui::text::NumberField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::doc::Document; @@ -36,6 +44,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that sets or resets the fold angle of fold lines. +pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees. +pub const FOLD_ANGLES: std::ops::RangeInclusive = -180.0..=180.0; +/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is +/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the +/// place the field's fine steps (a tenth of a degree) round to. +pub fn angle_places(angle: Option) -> usize { + // f64's Display is the shortest text that reads back as the same number, without an exponent. + angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1) +} /// The command that shows the Fold Preview window. pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. @@ -54,6 +74,7 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Sep, c("Check Fold Lines", CHECK), + c("Set Fold Angle…", SET_FOLD_ANGLE), Sep, cp("Fold Preview", PREVIEW, json!({})), ] @@ -215,14 +236,22 @@ struct Rows { /// What they were read for: the document, its revision and its selection. key: Option<(u64, u64, Vec)>, rows: Vec, + /// Whether the rows count the selection (not the whole document). + selection: bool, + /// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change. + fold_lines: u64, + /// The angle they all fold at (`None`: they differ, or there are none). + angle: Option, + /// How many of them hold a stored angle, readable or not: what Reset takes away. + stored_angles: u64, } /// The rows for the active document as it is now, read again only when it changed. -fn rows(app: &mut VectorcraftApp) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; +fn read_rows(app: &mut VectorcraftApp) -> Rows { + let Some(st) = app.session.active() else { return Rows::default() }; let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); if app.addon_panels.fold.rows.key.as_ref() == Some(&key) { - return app.addon_panels.fold.rows.rows.clone(); + return app.addon_panels.fold.rows.clone(); } let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); let d = app.session.active().map(|st| st.doc.clone()); @@ -231,9 +260,74 @@ fn rows(app: &mut VectorcraftApp) -> Vec { let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) }; - let rows: Vec = answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(); - app.addon_panels.fold.rows = Rows { key: Some(key), rows: rows.clone() }; - rows + let kept = Rows { + key: Some(key), + rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(), + selection: answer["scope"] == "selection", + fold_lines: answer["foldLines"].as_u64().unwrap_or(0), + angle: answer["foldAngle"].as_f64(), + stored_angles: answer["storedAngles"].as_u64().unwrap_or(0), + }; + app.addon_panels.fold.rows = kept.clone(); + kept +} + +/// The role rows for the active document as it is now. +#[cfg(test)] +fn rows(app: &mut VectorcraftApp) -> Vec { + read_rows(app).rows +} + +/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle +/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK +/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is +/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is +/// the active one. The command's reason while it can't change any. +pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result, String> { + let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; + (command.enabled)(&app.session)?; + let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); + let ids: Vec = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect(); + let doc = app.session.active().map(|st| st.uid); + match json!({ "angle": angle, "__params": { "ids": ids }, "__doc": doc }) { + Value::Object(fields) => Ok(fields), + _ => Err("no fields".into()), + } +} + +/// Set Fold Angle…: opens the parameter dialog on [`dialog_fields`]. +pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result { + let fields = dialog_fields(app)?; + crate::dialogs::command::open(app, SET_FOLD_ANGLE, "Set Fold Angle", fields) +} + +/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle +/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which +/// takes away the angles of their own. +fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { + if !kept.selection || kept.fold_lines == 0 { + return; + } + let mut call = None; + let _ = Line::new().fill_width().show(ui, |ui, _| { + Field::new(tl!("Fold Angle")).show(ui, |ui, _| { + let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle)) + .unit_kind(UnitKind::Degrees) + .range(FOLD_ANGLES) + .max_decimals(angle_places(kept.angle)); + if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() { + call = Some(json!({ "angle": a })); + } + }); + if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) { + call = Some(json!({ "reset": true })); + } + }); + if let Some(p) = call + && let Err(e) = app.run(SET_FOLD_ANGLE, p) + { + app.status(e); + } } /// The label of role `role` (its id when it is none of [`ROLES`]). @@ -249,8 +343,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if !selected { Text::new(tl!("No objects are selected.").to_string()).show(ui); } - let rows = rows(app); - let source = Positional { rows: &rows, label: |row| role_label(&row.0) }; + let kept = read_rows(app); + let rows = &kept.rows; + let source = Positional { rows, label: |row| role_label(&row.0) }; let out = List::::new(tl!("Fold line roles").to_string()) .select(SelectMode::None) .activate(ActivateOn::Click) @@ -277,6 +372,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_angle(app, ui, &kept); show_check(app, ui); } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index fcaf37a7b5..4eca13035a 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -519,6 +519,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { order: vec![], hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], collisions: vec![(0, 1)], + stack: Default::default(), + origin: [0.0; 3], }; // The summary, the fold line errors, the other blanks, the open joint, the crossing panels. assert_eq!(status(3, Some((&Blank::default(), &f)), true).len(), 5); diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 80f59d2e34..8222b179d5 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -3,8 +3,9 @@ use std::sync::Arc; use serde_json::json; use vectorcraft_engine::Session; -use super::{CHECK, ID, SET_ROLE, follow_role, last_check, rows, run_check, select_issue}; +use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show}; use crate::i18n::LangExt as _; +use crate::tests::panel_harness::Panel; use crate::{VectorcraftApp, menus}; /// An app with two rectangles, nothing selected → (app, their ids). @@ -142,8 +143,67 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { + let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } } + +#[test] +fn set_fold_angle_is_listed_after_check_fold_lines() { + let (app, _, _) = app(); + let entries = menus::menu_entries(&app); + let items: Vec<&str> = entries.iter().filter(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"]).map(|e| e.label.as_str()).collect(); + let at = |label: &str| items.iter().position(|l| *l == label).unwrap_or_else(|| panic!("{label}: {items:?}")); + assert_eq!(at("Set Fold Angle…"), at("Check Fold Lines") + 1); + let item = entries.iter().find(|e| e.label == "Set Fold Angle…").expect("listed"); + assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE)); +} + +#[test] +fn a_fold_angle_field_shows_every_place_the_angle_has() { + use super::angle_places; + assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]); +} + +#[test] +fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.selection, kept.fold_lines, kept.angle, kept.stored_angles), (true, 1, Some(90.0), 0), "Reset is dimmed"); + app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}"); + let panel = Panel::new(app, show); + let values = panel.values(); + let mut app = panel.app(); + assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}"); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1)); + // Stored text that is not an angle: the field shows the role's angle, and Reset can still remove the text. + app.session + .edit("Test", |d, _| { + if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) { + n.edit_attrs(|at| { + at.data.retain(|(k, _)| k != "vc-fold-angle"); + at.data.push(("vc-fold-angle".into(), "wide".into())); + }); + } + Ok(()) + }) + .unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(90.0), 1)); + // Nothing selected: the rows count the document and no Fold Angle row shows. + app.run("select.none", json!({})).unwrap(); + assert!(!read_rows(&mut app).selection); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "{text}"); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 1914b37a36..8ad60b5fb4 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -17,10 +17,10 @@ pub mod tangent_circle; use craft::behavior::ColumnWidth; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::text::NumberField; @@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); return; } + Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui)); +} + +fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let readout = readout(app); let anchor = readout.anchor.as_ref(); let selected = app.session.active().is_some_and(|st| !st.selection.is_empty()); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index df2571a136..9a63194c34 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles); } +#[test] +fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { + let mut app = app(); + let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap(); + let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let mut panel = Panel::new(app, super::show); + let room = egui::vec2(220.0, 215.0); + panel.room(room).frame(); + panel.frame(); + let action = "Remove Points, Keep Shape"; + assert!(panel.rect(action).bottom() > room.y, "the action starts clipped"); + panel.focus(action); + let rect = panel.rect(action); + assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}"); + panel.focus("Make Smooth"); + panel.click("Make Smooth"); + let anchor = readout(&panel.app()).anchor.unwrap(); + assert!(anchor.lengths.iter().all(|length| *length > 0.0)); +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 00a8b9cd61..b7502126e1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,7 +31,7 @@ use super::state::SYSTEM_CLIPBOARD_POLL; use super::{ Arc, AutomationRoots, ControlRequest, Receiver, Session, UiState, VectorcraftApp, View, ViewInfo, background, canvas, chrome, credits, dialogs, edits, export_progress, file_access, file_asks, fileio, font_menu, i18n, io, menus, opening, palette, panel_docking, panels, place, placing, - plugin_runs, prefs_dialog, recovery, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, + plugin_runs, prefs_dialog, recovery, retype_runs, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, }; mod commands; @@ -224,6 +224,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + retype_runs: Default::default(), recovery: Default::default(), closing: None, prefs: None, @@ -234,6 +235,7 @@ impl VectorcraftApp { told: Default::default(), missing_font_edit_token: None, held: Default::default(), + document_setup_source: None, edit_scopes: Default::default(), command_dialog: Default::default(), effect_dialogs: Default::default(), @@ -346,6 +348,7 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + retype_runs::poll(self); } /// The language the UI is drawn in: the Preferences window's choice while it is open (so a @@ -512,6 +515,7 @@ impl VectorcraftApp { || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() + || self.retype_runs.running.is_some() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -707,14 +711,18 @@ impl VectorcraftApp { } } +/// Use the same supported scale for the interface and the canvas. Invalid saved values fall back to 100%. +fn applied_ui_scaling(saved: f64) -> f32 { + if saved.is_finite() && saved > 0.0 { saved.clamp(0.75, 2.0) as f32 } else { 1.0 } +} + /// The root values the preferences give every frame: the theme, the interface scale (UI Scaling /// over the display's `native_ppp`), Show Tool Tips, the zoom stops (100% at `print` screen points /// to an inch, [`crate::state::print_ppi`]) and which drags scrub a value (Scrub Numeric Fields: the /// side label only, or nothing). pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print: Option) -> RootEnv { let (theme, mode, accent) = theme::root_theme(prefs); - // A hand-edited preferences file must not scale the interface to nothing. - let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 }; + let scaling = applied_ui_scaling(prefs.ui_scaling); let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); root.sizes = theme::app_sizes(); root.values.set(view::zoom_scheme(print, native_ppp)); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1dbe830af4..fcd71714d3 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -327,7 +327,7 @@ impl VectorcraftApp { /// Preferences › User Interface › UI Scaling, as the interface applies it. pub(crate) fn ui_scaling(&self) -> f32 { - self.session.prefs.ui_scaling.clamp(0.75, 2.0) as f32 + super::applied_ui_scaling(self.session.prefs.ui_scaling) } /// Ask the active view's canvas to run `request` in its next pass; `bounds` are the layers' bounds diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 50fc760237..8acc12b360 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -23,7 +23,7 @@ use crate::doc_windows::Win; use crate::panel_drag::PanelDrag; use crate::panels::brushes::BrushKey; use crate::panels::brushes::BrushLibraries; -use crate::panels::graphic_styles::StyleKey; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::place::{CanvasDrop, CanvasFiles}; @@ -50,7 +50,7 @@ pub(crate) struct CarriedArt { #[derive(Clone, Debug)] enum Payload { Panel(PanelDrag), - Style(StyleKey), + Style(StyleDrag), Symbol(SymbolKey), Brush(BrushKey), Library(LibraryKey), @@ -171,14 +171,14 @@ impl Component for CanvasDrops<'_> { if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); - let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); + let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); let brush = Target::new(rect, view, covered, |d: &ListDrag| { (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); - let style = cx.drop_target::, _>(&style); + let style = cx.drop_target::(&style); let symbol = cx.drop_target::, _>(&symbol); let brush = cx.drop_target::, _>(&brush); let library = cx.drop_target::, _>(&library); @@ -347,11 +347,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), } }, Payload::Brush(_) => Ok(()), - Payload::Style(key) => { + Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; - run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) + run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } + Payload::Style(_) => Ok(()), Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" @@ -365,6 +366,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); + if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) { + if cmd == "paint.setStroke" { + gradient.remove("dither"); + } + params["keepModel"] = json!(true); + } run(app, cmd, params) } Payload::Panel(PanelDrag::Appearance(source)) => { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a4aad999aa..d27a7ee61d 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; use crate::panel_drag::PanelDrag; use crate::panels::brushes::{BrushKey, BrushLibraries}; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::{VectorcraftApp, canvas}; @@ -45,6 +46,71 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + let at = Point::new(250.0, 70.0); + let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + for operation in [DropOperation::Move, DropOperation::Copy] { + drop_at(&mut app, payload.clone(), at, operation).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "neither kind of foreign drop makes an edit"); + } +} + +fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + app.session.fill_active = fill; + let mut gradient = GradientPaint::new(Default::default()); + gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0); + gradient.gradient.dither = true; + let start = undo_len(app); + let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient))); + drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(app), start + 1); + id +} + +#[test] +fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, true); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") }; + assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(fill.gradient.dither); +} + +#[test] +fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, false); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") }; + assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(!stroke.gradient.dither); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol @@ -67,12 +133,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(swatch), on_b, Move).unwrap(); assert_eq!(app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(), red); assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); - let name = app.session.active().unwrap().doc.graphic_styles[2].name.clone(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Move).unwrap(); + let st = app.session.active().unwrap(); + let name = st.doc.graphic_styles[2].name.clone(); + let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); let items = st.doc.node(b).unwrap().appearance.items.len(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Copy).unwrap(); + drop_at(&mut app, style, on_b, Copy).unwrap(); let added = app.session.active().unwrap().doc.node(b).unwrap(); assert!(added.appearance.items.len() > items && added.extras().graphic_style.is_none(), "with Alt the style goes on top, unlinked"); let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(); diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 00abc89bc9..921a9e73e4 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets { impl SelectionWidgets { fn new(layout: Layout) -> Self { - SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets")) } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 50bcfc23d0..d560fd2b6b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -718,6 +718,121 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } +/// One frame of the whole app on `ctx` with `events`, in a 1600 × 850 window, as the hosts run it. +fn app_step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A Rectangle tool on a new 400 × 300 document in the whole app, after three frames, with Smart +/// Guides and Snap to Point off → (the app, its context, the canvas view). +fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasView) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let xf = app.canvas_view().unwrap(); + (app, ctx, xf) +} + +/// The bounds of the paths in the active document. +fn drawn_paths(app: &VectorcraftApp) -> Vec { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if n.path_data().is_some() { + found.extend(n.geometric_bounds()); + } + }); + found +} + +/// A primary button event at `pos` with `modifiers` held. +fn primary(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A press or release of Space. +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// A tool drag ends with the modifiers held when its button went up. Shift let go after the +/// release in the same frame still constrains the Rectangle tool's rectangle to a square, Shift +/// pressed after the release does not constrain it, and Alt held only at the release draws it +/// from its center. +#[test] +fn tool_drag_ends_with_the_modifiers_of_its_button_release() { + let draw = |held: egui::Modifiers, after: egui::Modifiers| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + app_step(&mut app, &ctx, vec![primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(to), egui::Event::ModifiersChanged(held), primary(to, false, held), egui::Event::ModifiersChanged(after)], + ); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + let r = draw(egui::Modifiers::SHIFT, egui::Modifiers::NONE); + assert!(near(r.width(), r.height()), "Shift held at the release draws a square: {r:?}"); + let r = draw(egui::Modifiers::NONE, egui::Modifiers::SHIFT); + assert!(near(r.width(), 60.0) && near(r.height(), 30.0), "Shift pressed after the release does not constrain: {r:?}"); + let r = draw(egui::Modifiers::ALT, egui::Modifiers::NONE); + assert!(near(r.width(), 120.0) && near(r.x0, 40.0), "Alt held at the release draws from the center: {r:?}"); +} + +/// Shift pressed only in the frame of a tool drag's release, with the pointer held still since +/// the drag's last frame, still constrains the Rectangle tool's rectangle to a square. +#[test] +fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + assert!((paths[0].width() - paths[0].height()).abs() < 1e-3, "Shift pressed at a still release draws a square: {:?}", paths[0]); +} + +/// The move in the frame of a tool drag's release counts for the drag: the Rectangle tool's last +/// move sizes the rectangle, and with Space held through the release it moves the rectangle +/// instead, at the size the drag had before that move. +#[test] +fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { + let draw = |space: bool| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + if space { + app_step(&mut app, &ctx, vec![space_key(true)]); + } + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); + app_step(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + assert_eq!(draw(false), Rect::new(100.0, 100.0, 160.0, 130.0), "the last move sizes the rectangle"); + assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); +} + /// #6369: only the selection box remains over the temporary halftone, and the original /// selection's outlines come back when Preview is turned off or the dialog is cancelled. #[test] @@ -4029,6 +4144,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.active().unwrap().selection.objects[0].0 } +#[test] +fn the_canvas_type_editor_uses_the_interface_language() { + use crate::i18n::LangExt as _; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let former = crate::i18n::current(); + start_typing(&mut app, &ctx); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]); + crate::i18n::set_current(former); + + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte"))); +} + /// Returns a key press and its release. fn tap(key: egui::Key) -> [egui::Event; 2] { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 0ccc63be2c..64dca524b3 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -92,3 +92,20 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() { } } } + +#[test] +fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() { + let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0)); + for (saved, expected) in [(0.5, 0.75), (3.0, 2.0), (0.0, 1.0), (f64::NAN, 1.0)] { + let (mut app, ctx, jobs) = shown(1.0, 1.5); + app.run("view.actualSize", json!({})).unwrap(); + frame(&mut app, &ctx, (1.0, 1.5), vec![]); + let before = device_length(rendered(&jobs), a, b); + app.session.prefs.ui_scaling = saved; + let scale = crate::app::root_env(&app.session.prefs, 1.0, None).scale.0; + assert_eq!(scale, expected, "interface scale from saved value {saved}"); + frame(&mut app, &ctx, (1.0, scale), vec![]); + let length = device_length(rendered(&jobs), a, b); + assert!((length - before).abs() < 1e-4, "saved scale {saved} changes 128 pt from {before} to {length} pixels"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 5bda6d918e..af12608aa5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -150,6 +150,18 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } + /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones + /// included (the pointer frame's `pick_mods`), instead of as they are at the end of the pass: a modifier pressed or + /// let go after the release does not count for it. Space and Backtick stay as the host holds them. Unchanged in a + /// pass where that button did not come up. + fn at_release(&self, pointer: &ToolPointer, mut ev: PointerEvent) -> PointerEvent { + let frame = craft::ui::runtime::pointer::frame(&self.ctx); + if frame.release == Some(pointer.button) { + ev.mods = tool_mods(frame.pick_mods, ev.mods.space); + } + ev + } + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { @@ -322,7 +334,8 @@ impl CanvasTool for SessionTool<'_> { let covered = self.covered(pointer); let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { - let ev = pointer_event(PointerKind::Drag, pointer, cx); + // The moves of the pass that releases the press came before its release, with the keys held then. + let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); dispatch(&mut self.app(), &ev, self.view); self.app().canvas.last_drag = Some((pointer.pos, ev)); } @@ -340,21 +353,31 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); + // The press ends where it went up, with the keys held at its release. + let up = self.at_release(pointer, pointer_event(PointerKind::Up, pointer, cx)); let covered = self.covered(pointer); let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); - if cx.over_drop_target() || carried.is_some() { + let given_up = cx.over_drop_target() || carried.is_some(); + if given_up { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. let _ = self.app().session.cancel_interaction(); } if let Some(art) = carried.filter(|_| !cx.over_drop_target()) { // Released over a pane in the frame the pointer reached it: no target could take it yet. - let op = if pointer.mods.alt { DropOperation::Copy } else { DropOperation::Move }; + let op = if up.mods.alt { DropOperation::Copy } else { DropOperation::Move }; let mut app = self.app(); app.canvas.panes.released = super::drops::released_on_pane(&app, art, pointer.pos, op); } self.app().canvas.grab = None; - self.send(PointerKind::Up, pointer, cx); + // When the pointer moved or the keys changed since the drag's last move, the tool gets a move where the press went + // up first, as it does while held: the last move of the release's pass still sizes the shape, and Shift pressed in + // that pass still draws a square. A move that was given up gets none. + let last = self.app().canvas.last_drag.map(|(_, ev)| ev); + if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) { + dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view); + } + dispatch(&mut self.app(), &up, self.view); if self.app().canvas.last_drag.is_some() { // A press that dragged is no click, and the framework counts presses: the next press starts a new run. self.app().ui.trace_pick_clicks = pointer.clicks; @@ -367,7 +390,7 @@ impl CanvasTool for SessionTool<'_> { _ => return, }; let before = self.app().session.tool_id(); - self.send(follow, pointer, cx); + dispatch(&mut self.app(), &PointerEvent { kind: follow, ..up }, self.view); // A double click on type switched a selection tool to the Type tool: the caret goes where the type was // clicked, so typing edits it at once. let switched = follow == PointerKind::DoubleClick && before != "type" && self.app().session.tool_id() == "type"; diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 204853bd98..2545d16761 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -275,7 +275,7 @@ impl ShapeWidgets { } fn new(marks: Vec) -> Self { - ShapeWidgets { common: Common::new(), marks }.label("Shape widgets") + ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets")) } } @@ -334,7 +334,7 @@ impl Component for ShapeWidgets { } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { - access.description("Shape widgets"); + access.description(tl!("Shape widgets")); } fn finish(self, cx: Cx<'_, Self>) -> Response { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index a0d69c55c5..5401e9800f 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -120,48 +120,21 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } -/// The selected paths' eligible corners, as document lengths, beside the anchor controls. -/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). +/// The Corners link and the radius of the selected paths' picked corners +/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners +/// pop-up for those corners; a narrow bar leaves out the link and the field together. fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some(st) = app.session.active() else { return }; - let mut items = Vec::new(); - let mut radius: Option = None; - let mut mixed = false; - for &id in &st.selection.objects { - let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; - let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); - if corners.is_empty() { - continue; - } - for &k in &corners { - // Keep absolute requested radii, even when their drawing is fitted smaller. Relative - // storage is a fraction, but the field and setLiveShape both consume document lengths. - let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; - if let Some(first) = radius { - mixed |= (first - value).abs() >= 1e-9; - } else { - radius = Some(value); - } - } - items.push(json!({"id": id, "corners": corners})); - } - if items.is_empty() { - return; - } + let Some(picked) = crate::panels::picked_corners(app) else { return }; let label = tl!("Corner Radius:"); - let shown = if mixed { None } else { radius }; - // PLAN: assumed `crate::canvas::general_lengths(app) -> LengthUnits` (cv.B5b, canvas-w15). let lengths = crate::canvas::general_lengths(app); let mut typed = None; group(ui, rank::GROUP, |ui| { - Field::new(label).show(ui, |ui, _| { - let number = NumberField::length(label, Bind::given(shown), lengths).show(ui); - typed = number.edit.events.committed().copied().flatten().or(typed); - }); + crate::panels::corners_link(app, ui); + let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui); + typed = number.edit.events.committed().copied().flatten().or(typed); }); if let Some(radius) = typed { - // App::run reports any command failure in the status bar, as the other inline fields do. - app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)})); } } diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 04a7240cf7..aef6749bbc 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -32,7 +32,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) .unwrap_or_default(); let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); - let rotation = app.view().map_or(0.0, |v| v.rotation); + let view = app.view(); + let rotation = view.map_or(0.0, |v| v.rotation); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 // turns the -0 of a small negative angle into 0. @@ -80,6 +81,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) .placeholder(angle.clone()) .look(SelectLook::Filled) + .enabled(view.is_some()) .show(ui) .value() .copied(); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 6484290054..63935c2863 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -743,6 +743,20 @@ fn the_status_bar_rotation_box_shows_the_view_angle() { assert_eq!(bar.tree().value_of(rotation.node), Some("-45°")); } +#[test] +fn the_status_bar_rotation_picker_requires_a_document_view() { + let mut bar = status_readout_app(); + bar.app().run("file.close", json!({})).unwrap(); + assert!(bar.app().view().is_none()); + bar.settle().click("Rotation").settle(); + assert!(bar.find("-45°").is_none(), "the picker stays closed without a view"); + + bar.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + bar.settle().click("Rotation").settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); +} + /// While background work runs the status bar shows it where the message was, with the count of the jobs after the /// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress. #[test] @@ -2832,6 +2846,34 @@ fn the_anchor_points_group_holds_convert_and_anchors() { assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); } +/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners +/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step. +#[test] +fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { + use vectorcraft_geom::shapes::CornerKind; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 400.0)).frame(); + assert!(bar.shows("Corners") && !bar.shows("Chamfer"), "the pop-up starts closed"); + bar.click("Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius", "Relative", "Absolute"] { + assert!(bar.shows(name), "the pop-up has {name}"); + } + let depth = bar.app().session.doc().unwrap().history.undo.len(); + bar.click("Chamfer"); + assert_eq!(bar.app().session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9d729c31d4..b550182214 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1457,6 +1457,7 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val Some(Some("cancel")) => Some("ui.dialog.cancel"), Some(_) => return err("`action` must be confirm or cancel"), }; + let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() @@ -1472,7 +1473,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { - craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) + // A Save PDF settings object keeps the options it leaves out. + match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, ¶ms)) { + Some(set) => Some(set.map(|()| Value::Null)), + None => craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms), + } } else { Some(Ok(Value::Null)) }; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index e7e617a74e..d267ab460e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -912,6 +912,7 @@ fn pointer_replies_name_the_key_object() { /// A Shape Builder click on a large selection merges on another thread: the frames go on, and /// the `ui.pointer` reply comes once the merge is applied, with the selection after it. +#[cfg(not(target_arch = "wasm32"))] #[test] fn pointer_reply_waits_for_a_merge_on_another_thread() { let (tx, rx) = std::sync::mpsc::channel(); @@ -933,8 +934,10 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert_eq!(hover.try_recv().unwrap()["ok"], true, "a hover is answered at once"); app.session.tool_poll(app.view_info(), true).unwrap(); let revision = app.session.active().unwrap().revision; + let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); + merge.wait_started().unwrap(); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. let hover = send(&mut app, json!([{"kind": "move", "x": 35, "y": 10}])); @@ -944,32 +947,20 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(press.try_recv().is_err(), "a Cmd-click during the merge waits for it"); let hover = send(&mut app, json!([{"kind": "move", "x": 45, "y": 10}])); assert_eq!(hover.try_recv().map(|r| r["ok"].clone()), Ok(json!(true)), "a hover after the held Cmd-click"); - let start = std::time::Instant::now(); - let reply = loop { - if let Ok(r) = click.try_recv() { - break r; - } - assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply"); - std::thread::sleep(std::time::Duration::from_millis(2)); - // A frame: the canvas checks on the tool, then the replies are answered. - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); + assert_eq!(app.session.active().unwrap().revision, revision); + merge.release(); + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let reply = click.try_recv().expect("the merge was applied before answering the click"); assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); assert_ne!(app.session.active().unwrap().revision, revision); - let press = loop { - if let Ok(r) = press.try_recv() { - break r; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let press = press.try_recv().expect("the held Cmd-click was applied after the merge"); assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 86e918f876..6fcff63221 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,6 +28,7 @@ pub(crate) mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod curvature_circle_options; pub mod custom_dictionary; pub mod dimension; mod document_setup; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 705913d428..4b2b79a02d 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,6 +8,7 @@ //! empty, or Data Sets without a document, is an error and the dialog stays open. use std::hash::Hash; +use std::sync::Arc; use craft::automation::actions::Action; use craft::host::PickRequest; @@ -131,6 +132,8 @@ pub(crate) enum Folder { /// The Batch dialog on the dialog host. pub struct BatchDialog { id: DialogId, + /// Identifies this opening even when another Batch dialog reuses `id`. + folder_owner: Arc<()>, /// The index of the action's set. pub set: usize, /// The index of the action in its set. @@ -150,13 +153,13 @@ impl BatchDialog { &self.form.values } - /// The Browse presses since the last call. - pub(crate) fn take_asked(&mut self) -> Vec { - std::mem::take(&mut self.asked) + /// The Browse presses since the last call and the opening that made them. + pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec) { + (self.folder_owner.clone(), std::mem::take(&mut self.asked)) } /// Writes the folder the picker answered into its row. - pub(crate) fn set_folder(&mut self, which: Folder, path: String) { + fn set_folder(&mut self, which: Folder, path: String) { match which { Folder::Source => self.form.values.folder = path, Folder::Destination => self.form.values.destination_folder = path, @@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result, which: Folder) { let title = match which { Folder::Source => crate::i18n::t("Source Folder"), Folder::Destination => crate::i18n::t("Destination Folder"), @@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) { if let Some(path) = picked.paths().first() && let Some(dialogs) = app.dialogs() { - let path = path.to_string_lossy().into_owned(); dialogs.with(|host| { - if let Some(dialog) = host.get_mut::() { - dialog.set_folder(which, path); + if let Some(dialog) = host.get_mut::().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) { + dialog.set_folder(which, path.to_string_lossy().into_owned()); } }); } @@ -437,6 +440,44 @@ mod tests { }); } + #[test] + fn batch_folder_answers_belong_to_the_dialog_that_asked() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let mut app = app_with(vec![step]); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let request_folders = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.get_mut::().unwrap().asked.extend([Folder::Source, Folder::Destination])); + pump(app, &ctx); + }; + let folders = || { + dialogs.with(|host| { + let fields = host.get::().unwrap().fields(); + (fields.folder.clone(), fields.destination_folder.clone()) + }) + }; + let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| { + picker.answer(&[destination]); + picker.answer(&[source]); + file_asks::poll(app); + }; + + open(&mut app, 0, 0).unwrap(); + request_folders(&mut app); + assert_eq!(picker.requests().len(), 2); + dialogs.with(|host| host.cancel::(&ctx)); + open(&mut app, 0, 0).unwrap(); + set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]); + answer(&mut app, "old-source", "old-destination"); + assert_eq!(folders(), ("new-source".into(), "new-destination".into())); + + request_folders(&mut app); + assert_eq!(picker.requests().len(), 4); + answer(&mut app, "picked-source", "picked-destination"); + assert_eq!(folders(), ("picked-source".into(), "picked-destination".into())); + } + /// Batch plays an action recorded with a key its command no longer reads, as Play does. #[test] fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() { diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index acb6065d7a..9f8ae5af95 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -19,6 +19,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row as Line; use craft::ui::list::{List, ListRow}; +use craft::ui::primitives::Revision; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; use egui::{Context, Ui}; @@ -258,6 +259,7 @@ impl StackDialog for InsertMenuItemDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let rows = &self.rows; + let rows_key = self.key; self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| { FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| { let before = fields.find.clone(); @@ -284,16 +286,18 @@ impl StackDialog for InsertMenuItemDialog { } let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect(); let texts: Vec = listed.iter().map(|row| row.shown.clone()).collect(); - let lead = listed.iter().position(|row| picked(fields, row)); - let mut selection = lead.map_or_else(Selection::default, Selection::single); + let selected = listed.iter().position(|row| picked(fields, row)); + let mut selection = selected.map_or_else(Selection::default, Selection::single); List::::new(label("Menu Items")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&(rows_key, &fields.find, selected)).get()) .selection(Bind::bound(&mut selection)) .sizing(Sizing::Content) .max_rows(8) .show_items(ui, &Listed(&texts), &mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default())); - if selection.lead != lead - && let Some(row) = selection.lead.and_then(|at| listed.get(at)) + let chosen = selection.items.first().copied(); + if chosen != selected + && let Some(row) = chosen.and_then(|at| listed.get(at)) { pick(fields, row); } @@ -336,10 +340,13 @@ impl StackDialog for InsertMenuItemDialog { #[cfg(test)] mod tests { + use craft::automation::actions::Action; use craft::menu::Node; + use egui::{Key, Modifiers}; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; fn fields(find: &str, command: &str) -> InsertMenuItemFields { InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() } @@ -359,6 +366,61 @@ mod tests { assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick"); } + #[test] + fn arrow_navigation_inserts_the_command_after_the_selected_filtered_result() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.actions = Default::default(); + app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("View", Vec::new()) }).unwrap(); + let available = build(Lang::EN, true, &menus::Listed::default()); + let fit_params = available.iter().find(|row| row.command == "view.fitArtboard").unwrap().params.clone(); + let rows = [ + ("view.zoomIn", "First command", "first command"), + ("view.zoomOut", "Second command", "remaining commands"), + ("view.fitArtboard", "Third command", "remaining commands"), + ("view.outline", "Fourth command", "remaining commands"), + ] + .into_iter() + .map(|(command, shown, haystack)| Row { + command: command.into(), + params: available.iter().find(|row| row.command == command).unwrap().params.clone(), + shown: shown.into(), + haystack: haystack.into(), + }) + .collect(); + let mut panel = Panel::new(app, |app, ui| app.dialogs().unwrap().with(|host| host.run(ui))); + let dialog = InsertMenuItemDialog { + id: dialog_id(KEY), + target: Target::new(Some((0, 0)), None), + form: Form::new(InsertMenuItemFields::default(), check), + rows, + key: None, + }; + open_or_say(&mut panel.app(), dialog); + panel.frame(); + panel.frame(); + + let dialogs = panel.app().dialogs().unwrap(); + let command = || dialogs.with(|host| host.get::().unwrap().form.values.command.clone()); + panel.click("First command"); + assert_eq!(command(), "view.zoomIn"); + dialogs.with(|host| { + host.set_json_field(panel.ctx(), dialog_id(KEY), "find", json!("remaining")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "command", json!("view.fitArtboard")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "params", fit_params).unwrap(); + }); + panel.frame(); + assert!(!panel.shows("First command")); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(command(), "view.outline"); + panel.click(tl!("OK")); + let mut app = panel.app(); + pump(&mut app, panel.ctx()); + let steps = &app.ui.actions.action(0).unwrap().steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].command, "view.outline"); + } + /// The list holds the menu items that run an engine command, and the View menu items that the /// app runs itself, without asking for values first, outside the application, File, Window and /// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand, diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 7d52338be2..8a6de85fe4 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -363,13 +363,13 @@ fn push_app_data(app: &VectorcraftApp) { } } -/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose -/// answer is written into the dialog. +/// Files the folder picks the Batch dialog asked for with the identity of that opening. fn ask_batch_folders(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked).unwrap_or_default()); - for which in asked { - super::action_batch::ask_folder(app, which); + let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked)); + let Some((owner, folders)) = asked else { return }; + for which in folders { + super::action_batch::ask_folder(app, owner.clone(), which); } } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..cb1c6337e5 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -137,8 +137,7 @@ impl ArtboardOptionsValue { } } -/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's -/// document, presets and preferences cannot change while it is open. +/// What the dialog shows but does not edit, read from the app when it opens. struct Setup { /// The lengths the fields keep and show. lengths: LengthUnits, @@ -152,9 +151,17 @@ struct Setup { fit_bounds: [Option; 2], } +#[derive(Clone, Copy)] +struct Target { + document: u64, + /// The current artboard's ID, or no ID while creating a new artboard. + artboard: Option, +} + /// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests. pub struct ArtboardOptionsDialog { id: DialogId, + target: Target, value: ArtboardOptionsValue, setup: Setup, held: HeldAnswer, @@ -162,8 +169,8 @@ pub struct ArtboardOptionsDialog { } impl ArtboardOptionsDialog { - fn new(value: ArtboardOptionsValue, setup: Setup) -> Self { - ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } + fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self { + ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } } } @@ -546,13 +553,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { /// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog /// shows read from the app. -fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result { +fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; + let st = app.session.active().ok_or("no document")?; + let target = Target { document: st.uid, artboard }; + let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); let fills = fill_colors(app); value.seed_customs(&fills); - let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc)); let setup = Setup { lengths: crate::canvas::rulers::general_lengths(app), origin: app.ruler_origin(), @@ -560,7 +569,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result< fills, fit_bounds: [artwork, app.selection_bounds()], }; - host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup))); + host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup))); Ok(json!({ "dialog": KIND })) } @@ -569,6 +578,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let index = active_index(app); let st = app.session.active().ok_or("no document")?; let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let artboard = a.id; let r = a.rect; let value = ArtboardOptionsValue { index, @@ -585,7 +595,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { pixel_aspect: a.video_ruler_pixel_aspect_ratio, ..Default::default() }; - present(app, value) + present(app, value, Some(artboard)) } /// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new @@ -605,7 +615,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { pixel_aspect: 1.0, ..Default::default() }; - present(app, value) + present(app, value, None) } /// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it @@ -613,12 +623,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { /// point picked in the dialog. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; - let Some((held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.held.take(), d.value.reference))) else { return }; + let Some((target, held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.target, d.held.take(), d.value.reference))) + else { + return; + }; if app.ui.transform_panel.reference_point != reference { app.ui.transform_panel.reference_point = reference; } if let Some(value) = held { - let answer = confirm(app, &value).map(drop).map_err(Label::from); + let answer = confirm(app, target, &value).map(drop).map_err(Label::from); host.with(|h| { if let Some(d) = h.get_mut::() { d.held.answer(answer); @@ -633,21 +646,28 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// used (its column and row), all in one undo step. Fitting applies only to this artboard and never /// moves its artwork. The Global checkboxes' preferences are set only after the artboard command /// succeeds, so an error leaves them as they were. -fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result { +fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result { + let st = app + .session + .active() + .filter(|st| st.uid == target.document) + .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; set_globals(app, globals)?; return Ok(r); } - let p = v.params(); - let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect); - let changed = |k: &str, old: Option| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6)); - let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let (index, board) = + st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?; + let mut p = v.params(); + p["index"] = json!(index); + let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6); + let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height())); let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2); let mut entries = vec![]; if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) { - for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { let (w, h) = if let Some(choice) = v.size_choice { let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue }; @@ -753,6 +773,69 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn confirmation_follows_the_original_artboard_after_reorder() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + let original = app.session.active().unwrap().doc.artboards[0].id; + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original); + let undo = undo_len(&app); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed")); + assert_eq!(undo_len(&app), undo + 1); + } + + #[test] + fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() { + for create in [false, true] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + if create { + open_new(&mut app).unwrap(); + } else { + open(&mut app).unwrap(); + } + set(&app, &[("name", json!("Source"))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1")); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!(artboards.len(), if create { 2 } else { 1 }); + assert_eq!(artboards.last().unwrap().name, "Source"); + } + } + + #[test] + fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2"); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + } + /// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document. #[test] fn position_moves_art_only_with_the_tool_option_on() { diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 97965e26dc..46d2a44802 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -44,6 +44,8 @@ struct Open { preview: LivePreview, /// Set Role Swatch: the role the Swatch row was last filled for. filled_for: Option, + /// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle. + doc: Option, /// Names this dialog's own open among reopenings of the same command, for its OK and Cancel. token: Arc<()>, } @@ -66,7 +68,8 @@ impl Setting { } /// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the -/// fixed ones and `__rowGutterLinked` for Area Type Options' linked Row Gutter). +/// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter and `__doc` for the uid of the document +/// whose objects the dialog edits). pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; if let Some(old) = app.command_dialog.open.take() { @@ -77,6 +80,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par _ => Map::new(), }; let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64()); + let doc = params.remove("__doc").and_then(|v| v.as_u64()); params.retain(|k, _| !k.starts_with("__")); let previews = previews(command, ¶ms); let setting = Setting::of(app); @@ -104,6 +108,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par previews, preview: LivePreview::default(), filled_for: None, + doc, token, }); Ok(Value::Null) @@ -162,9 +167,14 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) { } /// OK: runs the command on the dialog's values (keeping a preview as the one undo step) and closes the dialog; an -/// error keeps it open with the reason under its rows. +/// error keeps it open with the reason under its rows. A dialog opened on one document's objects (`__doc`, its uid) +/// closes as Cancel does and runs nothing once another document is the active one. fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> Result { let open = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)).ok_or("the dialog is gone")?; + if open.doc.is_some() && open.doc != app.session.active().map(|st| st.uid) { + open.preview.cancel(app); + return Ok(Value::Null); + } let params = command_params(&open.command, &open.opening, Setting::of(app)); let value = call(&open.command, &open.fixed, open.linked, form::json_of(¶ms, fields)); let result = if open.previews { @@ -222,7 +232,17 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option Param::new(key, label, ParamKind::bool(*on)), Value::Number(n) => { let whole = n.is_i64() || n.is_u64(); - let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, if whole { 0 } else { 3 }); + let range = number_range(command, key); + // A ranged number (a fold angle) is shown to every place it keeps. + let decimals = match range { + Some(_) => u32::try_from(crate::addons::packaging::angle_places(n.as_f64())).unwrap_or(u32::MAX), + None if whole => 0, + None => 3, + }; + let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, decimals); + if let Some(range) = range { + param = param.bounds(Some(*range.start()), Some(*range.end())); + } if lengths(command).contains(&key) { param = param.length(setting.units); if let Some(range) = length_range(command, key) { @@ -358,6 +378,15 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option Option> { + match (command, key) { + (crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES), + _ => None, + } +} + /// The order the fields of the commands this dialog edits come in, where the order of their /// names isn't it (the rest follow, by name). fn order(command: &str) -> &'static [&'static str] { @@ -781,4 +810,134 @@ mod tests { } } } + + use crate::addons::packaging::{SET_FOLD_ANGLE, SET_ROLE}; + + /// A window app with two rectangles, `a` a crease and `b` a cut line, nothing selected → (app, a, b). + fn fold_lines() -> (VectorcraftApp, u64, u64) { + let mut app = windowed(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 100.0)); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, a, b) + } + + /// The angle the open Set Fold Angle… dialog shows. + fn shown_angle(app: &VectorcraftApp) -> Option { + let id = id_of(app); + app.dialogs().unwrap().with(|h| h.get_by_id::(id).and_then(|d| d.fields().number("angle"))) + } + + /// Set Fold Angle… from its menu item → the angle its dialog opens on, the dialog then canceled; `None` when no + /// dialog opens. + fn opened_angle(app: &mut VectorcraftApp) -> Option { + crate::menus::invoke(app, SET_FOLD_ANGLE, json!({})); + app.command_dialog.open.as_ref()?; + pump(app); + let angle = shown_angle(app); + answer_cancel(app); + angle + } + + /// The angle the selection's fold lines fold at, after selecting `id`. + fn fold_angle(app: &mut VectorcraftApp, id: u64) -> Option { + app.run("select.set", json!({"ids": [id]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + } + + #[test] + fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { + let (mut app, a, b) = fold_lines(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own"); + app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(45.0)); + // The cut line does not fold, so the crease's angle is still the one shown. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(45.0)); + // Lines that differ open on 90°. + let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap(); + app.run("select.set", json!({"ids": [a, c]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(90.0)); + // With only a cut line selected there is nothing to set: no dialog opens, and ui.menuDialog gives the reason. + app.run("select.set", json!({"ids": [b]})).unwrap(); + assert_eq!(opened_angle(&mut app), None); + assert!(app.command_dialog.open.is_none()); + let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err(); + assert!(e.contains("select a crease, partial cut or perforation line"), "{e}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap(); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(45.0)); + answer_cancel(&mut app); + // The options dialog opened with an angle keeps it. + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}})); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(30.0)); + } + + /// Set Fold Angle…'s OK changes the lines the dialog opened on, even when the selection changes while it is open + /// (a remote command can change it): the other crease keeps its angle. + #[test] + fn set_fold_angle_s_ok_changes_the_lines_the_dialog_opened_on() { + let (mut app, a, b) = fold_lines(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + app.run("select.set", json!({"ids": [b]})).unwrap(); + set(&mut app, "angle", json!(30.0)); + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none(), "OK closes the dialog"); + assert_eq!(fold_angle(&mut app, a), Some(30.0), "the line the dialog opened on"); + assert_eq!(fold_angle(&mut app, b), Some(90.0), "the line selected later keeps its role's angle"); + } + + /// Set Fold Angle…'s OK changes nothing once another document is the active one, even a line there with the same + /// id as the line the dialog opened on. + #[test] + fn set_fold_angle_s_ok_changes_nothing_in_another_document() { + let (mut app, a, _) = fold_lines(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "the same id in the other document"); + app.run(SET_ROLE, json!({"role": "crease", "ids": [other]})).unwrap(); + set(&mut app, "angle", json!(30.0)); + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none(), "OK closes the dialog"); + assert_eq!(fold_angle(&mut app, other), Some(90.0), "the other document's line keeps its role's angle"); + assert!(app.session.set_active(0)); + assert_eq!(fold_angle(&mut app, a), Some(90.0), "the first document's line is left as it was"); + } + + /// Set Fold Angle…'s Angle row takes -180° to 180°, the range the command takes, and shows every place the angle + /// it opens on has. + #[test] + fn set_fold_angle_s_angle_row_keeps_the_commands_range() { + let (mut app, a, _) = fold_lines(); + app.run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let param = row(SET_FOLD_ANGLE, "angle", &json!(179.999999), Setting::of(&app)).expect("a row"); + match param.kind { + ParamKind::Number { min, max, decimals, .. } => assert_eq!((min, max, decimals), (Some(-180.0), Some(180.0), 6)), + _ => panic!("a number row"), + } + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(179.999999)); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), id_of(&app)); + assert!(app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "angle", json!(181))).is_err(), "past the range"); + set(&mut app, "angle", json!(-180)); + answer_ok(&mut app); + assert_eq!(fold_angle(&mut app, a), Some(-180.0)); + } } diff --git a/crates/ui-egui/src/dialogs/curvature_circle_options.rs b/crates/ui-egui/src/dialogs/curvature_circle_options.rs new file mode 100644 index 0000000000..7b0aecf47d --- /dev/null +++ b/crates/ui-egui/src/dialogs/curvature_circle_options.rs @@ -0,0 +1,84 @@ +//! Curvature Circle Tool Options (double-click the Curvature Circle tool, or `tool.options`): Snap +//! Tolerance is how near, in screen points, a path pulls the pointer (Smart Guides' Snapping +//! Tolerance applies when it is larger); with Snap with Smart Guides Off unchecked, the pointer +//! reaches no further than the selection tolerance while Smart Guides are off; Annotate Radius +//! off hides the radius label; Anchors at Standard Positions off gives the circle an anchor where +//! it touches the path and one every 90° from there; Use the Radius of Circular Arcs off gives the +//! curve's own curvature on the curve of a circular arc too. OK sets them with +//! `tool.setOption {tool: "curvatureCircle", values}`; they last across tool switches and are saved +//! with the preferences. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; +use vectorcraft_tools::curvature_circle::{DEFAULT_SNAP, ID as TOOL, SNAP_RANGE}; + +use super::{form, host, tool_options}; +use crate::VectorcraftApp; + +/// The dialog kind of Curvature Circle Tool Options. +pub const KIND: &str = "curvatureCircleOptions"; + +/// The switches the dialog edits, in the order it shows them, with their labels. +const SWITCHES: [(&str, &str); 4] = [ + ("snapWithoutGuides", "Snap with Smart Guides Off"), + ("annotateRadius", "Annotate Radius"), + ("standardAnchors", "Anchors at Standard Positions"), + ("constantRadius", "Use the Radius of Circular Arcs"), +]; + +/// The rows: Snap Tolerance, then the switches. +fn params() -> Vec { + let (min, max) = SNAP_RANGE; + let snap = Param::number("snapTolerance", tl!("Snap Tolerance:"), DEFAULT_SNAP, 1.0, 1).unit(UnitKind::Pixels).bounds(Some(min), Some(max)); + std::iter::once(snap).chain(SWITCHES.iter().map(|(key, label)| Param::new(*key, tl!(*label), ParamKind::bool(true)))).collect() +} + +/// Open the tool's options with their current values; an error when there is no window to show them in. +pub fn open(app: &mut VectorcraftApp) -> Result { + let params = params(); + let options = app.session.tool_options_of(TOOL); + let fields = options.as_object().map(|m| form::fields_of(¶ms, m)).unwrap_or_default(); + let (title, shown) = (tool_options::title(TOOL), params.clone()); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| tool_options::set_options(app, TOOL, form::json_of(¶ms, &result.fields)); + let opened = app.ui_ctx.clone().and_then(|ctx| { + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), shown.clone()).values(Bind::bound(f))); + host::open_held(app, dialog, ok) + }); + if opened.is_none() { + let message = tl!("No window to show the dialog in.").to_string(); + app.status(message.clone()); + return Err(message); + } + Ok(json!({ "dialog": KIND })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + for values in [ + json!({"annotateRadius": false, "constantRadius": "no"}), + json!({"annotateRadius": false, "snapTolerance": 0}), + json!({"annotateRadius": false, "size": 3}), + ] { + assert!(app.run("tool.setOption", json!({"tool": TOOL, "values": values})).is_err(), "{values}"); + assert_eq!(app.session.tool_options_of(TOOL)["annotateRadius"], json!(true)); + } + } + + /// Without a window the dialog cannot open, and `tool.options` says so instead of reporting it open. + #[test] + fn without_a_window_opening_the_options_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(app.run("tool.options", json!({"tool": TOOL})).is_err()); + } +} diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 195d2759f9..c3aa0ef099 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values) }); super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?; + app.document_setup_source = Some(source); Ok(Value::Null) } @@ -185,6 +186,9 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { + if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); let color = color_commands(app, &map)?; @@ -220,9 +224,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); - let edit = dialogs.with(|host| { - host.get_by_id::(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone()) - }); + let Some(edit) = dialogs.with(|host| { + host.get_by_id::(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone())) + }) else { + app.document_setup_source = None; + return; + }; if let Some(fields) = edit { match confirm(app, &fields) { Ok(_) => { @@ -645,6 +652,54 @@ mod tests { app.session.active().unwrap().history.undo.len() } + fn check_source_document(edit_artboards: bool) { + let (mut app, ctx) = new_app(); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + set(&app, &ctx, "colorMode", json!("cmyk")); + + let apply = |app: &mut VectorcraftApp| { + if edit_artboards { + set(app, &ctx, "editArtboards", json!(true)); + super::pump(app, &ctx); + !is_open(app) + } else { + press_ok(app, &ctx) + } + }; + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_steps(&app); + let accepted = apply(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, destination); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings"); + assert_eq!(undo_steps(&app), undo); + assert_eq!(app.session.tool_id(), "selection"); + assert!(!accepted && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(apply(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, source); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1)); + assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" }); + assert!(!is_open(&app)); + } + + #[test] + fn source_document_is_required_to_confirm_document_setup() { + check_source_document(false); + } + + #[test] + fn source_document_is_required_to_edit_artboards_from_document_setup() { + check_source_document(true); + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); @@ -1123,4 +1178,76 @@ mod tests { let preset = fields(json!({"gridColors": "blue"})); assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")])); } + + /// The grid preview the open dialog draws in `ctx`, in frames run as the hosts run them + /// ([`crate::testing::part_frame_uploads`]): its rect, the span of its texture + /// coordinates (two cells per unit) and the four pixels of the texture it draws. `tiles` holds + /// the pixels of each 2 × 2 texture uploaded so far in `ctx`, so every frame drawn in `ctx` + /// goes through this function. The preview is the largest rect drawn with such a texture. + fn drawn_preview( + app: &mut VectorcraftApp, + ctx: &egui::Context, + tiles: &mut std::collections::HashMap>, + ) -> (Rect, egui::Vec2, Vec) { + let mut preview = None; + for _ in 0..4 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; + let mut out = crate::testing::part_frame_uploads(app, ctx, raw, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| h.run(ui)); + } + }); + for (id, deltas) in &out.textures_delta.set { + if let Some(d) = deltas.last() { + let egui::ImageData::Color(img) = &d.image; + if img.size == [2, 2] { + tiles.insert(*id, img.pixels.clone()); + } + } + } + out.textures_delta.clear(); + preview = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) => { + r.brush.as_ref().filter(|b| tiles.contains_key(&b.fill_texture_id)).map(|b| (r.rect, b.uv, b.fill_texture_id)) + } + _ => None, + }) + .max_by(|a, b| a.0.area().total_cmp(&b.0.area())); + } + let (rect, uv, texture) = preview.unwrap_or_else(|| panic!("no grid preview")); + let pixels = tiles.get(&texture).cloned().unwrap_or_else(|| panic!("no tile for {texture:?}")); + (rect, uv.size(), pixels) + } + + /// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells. + fn tile(a: &str, b: &str) -> Vec { + let c = |h| crate::panels::c32(&hex(h)); + vec![c(a), c(b), c(b), c(a)] + } + + /// In an open dialog, the preview follows each edit of Grid Colors and Grid Size: after a + /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. + #[test] + fn the_grid_preview_follows_edits_in_the_open_dialog() { + let (mut app, ctx) = setup_open(); + let mut tiles = std::collections::HashMap::new(); + set(&app, &ctx, "tab", json!("Transparency")); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); + set(&app, &ctx, "gridColors", json!(["#ff0000", "#0000ff"])); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); + set(&app, &ctx, "gridSize", json!("large")); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); + set(&app, &ctx, "gridColors", json!("Dark")); + let (_, _, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); + assert_eq!(undo_steps(&app), 0); + } } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 97dc95426d..7849d98124 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -10,6 +10,7 @@ //! effect's defaults for the rest. use std::path::PathBuf; +use std::sync::Arc; use craft::host::{PickRequest, Picked}; use craft::ui::contract::Bind; @@ -48,6 +49,8 @@ pub(crate) struct EffectDialogs { pub(crate) struct Open { /// The dialog's id; while [`asking`](Open::asking), the question's. pub id: DialogId, + /// Identity of this opening, since effect dialogs reuse the same dialog ID. + opening: Arc<()>, /// The item the effect goes to, resolved. target: Value, /// The parameters that find the applied effect (`item`, `aligned`). @@ -107,6 +110,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let target = edit_target.get("item").cloned().unwrap_or(target); let mut open = Open { id: DialogId::NULL, + opening: Arc::new(()), target: target.clone(), edit_target, index: None, @@ -144,6 +148,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) - vectorcraft_effects::effect_info(effect).ok_or_else(|| format!("unknown effect `{effect}`"))?; let open = Open { id: DialogId::NULL, + opening: Arc::new(()), target: Value::Null, edit_target: json!({}), index: None, @@ -465,7 +470,18 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) { let _ = open.preview.run(app, previewing, &english, cmd, ¶ms); if let Some(request) = path { let (id, key) = (open.id, request.key); - pick_texture(app, Owner::Document, move |app, path, fields| { + let opening = Arc::clone(&open.opening); + let is_current = move |app: &VectorcraftApp| { + app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, ¤t.opening)) + }; + let same_opening = is_current.clone(); + let is_live = move |app: &VectorcraftApp| { + same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| { + if !is_current(app) { + return; + } let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|h| { if let Some(d) = h.get_mut_by_id::(id) { @@ -486,11 +502,20 @@ pub(super) fn pick_texture( app: &mut VectorcraftApp, owner: Owner, then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static, +) { + pick_texture_while(app, owner, |_| true, then); +} + +fn pick_texture_while( + app: &mut VectorcraftApp, + owner: Owner, + current: impl FnOnce(&VectorcraftApp) -> bool + 'static, + then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static, ) { use vectorcraft_engine::cmd::fileio; let rasters = fileio::FORMATS.iter().filter(|f| f.read && f.raster); let request = rasters.fold(PickRequest::open("texture"), |r, f| r.filter(f.label, fileio::read_extensions(f))); - file_asks::ask(app, request, owner, move |app: &mut VectorcraftApp, picked: Picked| { + file_asks::ask_while(app, request, owner, current, move |app: &mut VectorcraftApp, picked: Picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let bytes = match picked { Picked::Contents(mut files) if !files.is_empty() => files.swap_remove(0).1, @@ -668,6 +693,77 @@ mod tests { } } + #[test] + fn a_delayed_texture_reply_only_reaches_the_effect_opening_that_requested_it() { + use std::cell::RefCell; + use std::rc::Rc; + + use craft::ui::testing::{Fixture, Room}; + use vectorcraft_effects::pixel::TEXTURE_IMAGE; + + let mut png = Vec::new(); + let img: image::DynamicImage = image::RgbaImage::from_pixel(6, 4, image::Rgba([40, 60, 90, 255])).into(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + for (reopen, switch_document) in [(true, false), (false, true), (false, false)] { + let mut app = app(); + rect(&mut app, 10); + app.run("select.all", json!({})).unwrap(); + let app = Rc::new(RefCell::new(app)); + let shown = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui)); + fixture.in_room(Room::Window); + let ctx = fixture.ctx().clone(); + app.borrow_mut().ui_ctx = Some(ctx.clone()); + let picker = crate::tests::picks::scripted(&mut app.borrow_mut()); + let open = || app.borrow_mut().run("effect.dialog", json!({"effect": ROUGH_PASTELS})).unwrap(); + open(); + fixture.settle(); + let browse = fixture.by_label("Browse…").expect("the Load Texture Browse button"); + fixture.click(&browse).settle(); + assert_eq!(picker.requests().len(), 1, "Browse requested a file"); + + if reopen || switch_document { + let dialog = id(&app.borrow()); + assert!(app.borrow().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog))); + } + if switch_document { + let mut app = app.borrow_mut(); + let original = app.session.active().unwrap().uid; + // The reply arrives before the host pump has cleared the closed effect's app record. + app.session.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let active = app.session.active().unwrap().uid; + assert_ne!(active, original, "a different document is active"); + let status = app.ui.status.clone(); + picker.answer_contents(&[("invalid.png", b"not an image")]); + crate::file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, active, "a stale reply cannot switch documents"); + assert_eq!(app.ui.status, status, "a stale reply cannot report a texture error"); + continue; + } + if reopen { + fixture.settle(); + open(); + fixture.settle(); + } + let current = || { + let app = app.borrow(); + fields(&app, id(&app)) + }; + let before = current(); + picker.answer_contents(&[("texture.png", &png)]); + crate::file_asks::poll(&mut app.borrow_mut()); + fixture.settle(); + let after = current(); + if reopen { + assert_eq!(after.text("texture"), before.text("texture"), "a reopened effect keeps its own texture choice"); + assert_eq!(after.text(TEXTURE_IMAGE), before.text(TEXTURE_IMAGE), "the previous effect's image is absent"); + } else { + assert_eq!(after.text("texture"), Some("loaded"), "the originating effect loads the picked texture"); + assert!(after.text(TEXTURE_IMAGE).and_then(vectorcraft_effects::pixel::texture).is_some()); + } + } + } + /// A Pathfinder effect opens with its own Pathfinder Options (or, saved without them, the /// values it evaluates with); OK with nothing changed records no step, a change one step. #[test] diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6fc5ad7813..a515addb0e 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,6 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -117,7 +118,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let shown = dialogs.with(|host| { host.get_mut_by_id::(id).map(|dialog| { let visible = dialog.entries(true); - (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), dialog.asked.take()) + let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); + (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) }) }); let Some((on, batch, asked)) = shown else { @@ -127,18 +129,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { // `run` reports a failed preview itself. let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); app.effect_dialogs.gallery = Some(open); - if let Some(layer) = asked { - ask_texture(app, id, layer); + if let Some((opening, layer)) = asked { + ask_texture(app, id, opening, layer); } } -/// Asks for the image Load Texture reads into the layer `layer`. The answer finds the layer by its own id, wherever -/// it moved, and is dropped for a layer deleted since or a gallery that closed (a layer id is never used twice). -fn ask_texture(app: &mut VectorcraftApp, id: DialogId, layer: LayerId) { +/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. +fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { - if let Some(dialog) = host.get_mut_by_id::(id) { + if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { dialog.answer_texture(layer, fields); } }); @@ -234,6 +235,8 @@ fn entries_of(layers: &[EffectLayer], index: &FilterIndex, visible_only: bool) - /// [`FilterGallerySession`], with a preview of the visible layers and OK held for [`commit`]. pub(crate) struct EffectGalleryDialog { id: DialogId, + /// Dialog IDs and layer IDs can both be reused when the gallery opens again. + opening: Arc<()>, open: bool, catalog: Catalog, index: FilterIndex, @@ -255,6 +258,7 @@ impl EffectGalleryDialog { let session = FilterGallerySession::new(&first, &catalog); EffectGalleryDialog { id: dialog_id(KEY), + opening: Arc::new(()), open: true, catalog, index, @@ -456,7 +460,7 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } fn effect_label(id: &str) -> String { - vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } /// Where the preview rasters sit: one document point per pixel, origin at the top-left. @@ -652,8 +656,7 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); } - /// Load Texture… in the Settings, answered after the stack changed: the image goes into the layer that asked - /// wherever it moved, and an answer for a deleted layer is dropped. + /// A delayed Load Texture… reply follows its layer when it moves and is dropped when the layer or its gallery closes. #[test] fn settings_load_texture_answers_into_the_gallery() { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; @@ -677,10 +680,13 @@ mod tests { }) .collect() }; - // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the stack before the answer. - let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&VectorcraftApp)| { + let rough_pastels = || { let layer = json!({ "filter": "artistic.roughPastels", "visible": true, "params": {} }); - set(app, &ctx, "effects", json!([layer, layer])); + json!([layer, layer]) + }; + // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the gallery before the answer. + let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&mut VectorcraftApp)| { + set(app, &ctx, "effects", rough_pastels()); set(app, &ctx, "select", json!(row)); // The Texture row's Browse press, as the dialog's pass records it. app.dialogs().unwrap().with(|host| { @@ -696,6 +702,18 @@ mod tests { assert_eq!(ask(&mut app, 1, &|_| {}), [false, true], "the selected layer asked"); assert_eq!(ask(&mut app, 0, &|app| set(app, &ctx, "move", json!({"from": 0, "to": 1}))), [false, true], "the layer that asked moved"); assert_eq!(ask(&mut app, 1, &|app| set(app, &ctx, "delete", json!(true))), [false], "the layer that asked was deleted"); + let reopen = |app: &mut VectorcraftApp| { + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(app, &ctx); + super::open(app, &json!({})).unwrap(); + }; + // Both openings start with identical stacks, which gives their corresponding layers the same session-local IDs. + reopen(&mut app); + let answers = ask(&mut app, 0, &|app| { + reopen(app); + set(app, &ctx, "effects", rough_pastels()); + }); + assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index ef5b2a5ea4..5876d9265e 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -177,16 +177,14 @@ pub(crate) fn heading(cx: &EffectCx) -> String { } } -/// The effect's name in the UI language: the catalog may carry it with or without its trailing -/// ellipsis. A plug-in effect's name is shown as it is. +/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`]). +/// A plug-in effect's name is shown as it is. pub(crate) fn label(id: &str) -> String { let name = vectorcraft_effects::effect_info(id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()); if vectorcraft_plugins::effect::plugin_id(id).is_some() { return name; } - let dotted = format!("{name}…"); - let shown = tl!(&dotted); - if shown != dotted { shown.trim_end_matches('…').to_string() } else { tl!(&name).to_string() } + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or(name) } /// Film Grain's bounded, whole-number controls, in the same order as its parameter docs. diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5e765e306c..0211830949 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -996,17 +996,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let key = app.session.active().map(|st| (st.uid, st.revision)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((stale, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; - if stale { + if shown != key { let (doc, thumbs) = document_view(app, ctx); dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { @@ -1031,7 +1031,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from); + // OK validated its selection against the document the dialog showed before refreshing. + let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) { + params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) + } else { + Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) + }; dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { d.held.answer(answer); diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index e43435b5ae..fffa334f21 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -55,8 +55,14 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ()); - crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; + let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| { + if !app.session.active().is_some_and(|active| active.uid == *document) { + return Err(tl!("File Info can only change the document it was opened for.").to_owned()); + } + app.run("file.info", Value::Object(fields.clone())).map(|_| ()) + }; + crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?; Ok(Value::Null) } @@ -215,6 +221,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, + document: u64, open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -230,9 +237,10 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(value: Info) -> Self { + fn new(document: u64, value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), + document, open: true, hold: false, value, @@ -371,15 +379,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = Info; + type Answer = (u64, Info); fn held_ok(mut self) -> Self { self.hold = true; self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|fields| (self.document, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -674,6 +682,58 @@ mod tests { assert!(with_dialog(&app, |_| ()).is_some()); } + #[test] + fn a_file_info_confirmation_stays_with_its_document() { + let mut app = windowed(); + for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": title, "author": author})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Source")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application"); + + activate(&mut app, 1); + let before = app.session.active().unwrap(); + let document = before.doc.clone(); + let b_undo = before.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched"); + assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched"); + assert_eq!(after.history.undo.len(), b_undo); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft"); + let source = app.session.active().unwrap(); + assert_eq!(source.doc.info_title(), "Revised Source"); + assert_eq!(source.doc.metadata.author, "Ada"); + assert_eq!(source.doc.metadata.keywords, ["print"]); + assert_eq!(source.history.undo.len(), a_undo + 1); + } + + #[test] + fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() { + let mut app = windowed(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Destination")).unwrap(); + assert!(press_ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().history.undo.is_empty()); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 300d5543a3..a02e3d12cd 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -77,6 +77,7 @@ fn ok_sets_each_tools_options() { let layers = app.session.doc().unwrap().doc.layers.clone(); let circle = vectorcraft_tools::circle::ID; let arc = vectorcraft_tools::three_point_arc::ID; + let curvature = vectorcraft_tools::curvature_circle::ID; // The tool opened, the fields set, the tool whose options are read, and the options expected there. let rows: Vec<(&str, Value, &str, Value)> = vec![ ( @@ -107,6 +108,12 @@ fn ok_sets_each_tools_options() { circle, json!({"radii": false, "standardAnchors": false, "dragThird": false, "color": "magenta"}), ), + ( + curvature, + json!({"snapTolerance": 8, "annotateRadius": false, "standardAnchors": false}), + curvature, + json!({"snapTolerance": 8.0, "snapWithoutGuides": true, "annotateRadius": false, "standardAnchors": false, "constantRadius": true}), + ), (arc, json!({"direction": true}), arc, json!({"direction": true})), ("objectsOnPath", json!({"pivot": 7, "rotate": 30}), "objectsOnPath", json!({"pivot": 7, "rotate": 30.0})), ( diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 2ac4764bf5..ffcc511501 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -18,6 +18,7 @@ //! empties it). use std::collections::BTreeMap; +use std::sync::Arc; use craft::behavior::{EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; @@ -395,8 +396,12 @@ fn can_import(app: &VectorcraftApp) -> bool { file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() } -/// Import Data's answer: a tab-separated text file's rows into the sheet. -fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { +/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. +fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result { + let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) }; + if !dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) { + return Ok(Value::Null); + } let bytes = match picked { Picked::Paths(paths) => { let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) }; @@ -420,15 +425,14 @@ fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { return Err("the file is larger than 1 MB".into()); } let grid = grid_from_text(&decode(&bytes)); - if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); - } + dialogs.with(|host| host.get_mut::().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid))); Ok(Value::Null) } /// What the window asked of the app since the last [`pump`]. struct Asks { graph: Option, + import_owner: Arc<()>, apply: Option, actions: Vec, } @@ -444,7 +448,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { d.take_asks() }) }); - let Some(Asks { graph, apply: filed, actions }) = asked else { return }; + let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; if let Some(sheet) = filed { if let Err(e) = apply(app, &sheet, graph) { app.status(e); @@ -455,7 +459,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); - file_asks::ask(app, request, Owner::Document, import); + let owner = import_owner.clone(); + let current = import_owner.clone(); + file_asks::ask_while( + app, + request, + Owner::Document, + move |app| { + app.dialogs().is_some_and(|dialogs| { + dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, ¤t))) + }) + }, + move |app, picked| import(app, &owner, picked), + ); } Action::Revert => match graph_grid(app, graph) { Ok(grid) => { @@ -636,6 +652,8 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { /// sheet for [`pump`], which sends it to the graph and keeps the window open. pub(crate) struct GraphDataDialog { id: DialogId, + /// Identifies this opening even when another Graph Data dialog reuses `id`. + import_owner: Arc<()>, sheet: Sheet, state: GridState, entry: Entry, @@ -658,6 +676,7 @@ impl GraphDataDialog { load(&sheet, &state, &mut entry); GraphDataDialog { id: dialog_id(KIND), + import_owner: Arc::new(()), sheet, state, entry, @@ -672,7 +691,7 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. @@ -959,6 +978,62 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let files = Arc::new(ScriptedFiles::held()); + app.services.read = Some(Box::new(|_| Err("this picker answers with bytes".into()))); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1); + + let app = h.state_mut(); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + open(app).unwrap(); + let series = |h: &Harness| read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)); + assert!(files.answer(Picked::Contents(vec![("first.txt".into(), b"\tstale\nQ1\t7".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "second"); + + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert!(files.answer(Picked::Contents(vec![("second.txt".into(), b"\timported\nQ2\t8".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "imported"); + } + + #[test] + fn graph_data_import_does_not_reactivate_the_document_of_a_closed_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + let first = app.session.active().unwrap().uid; + open(&mut app).unwrap(); + edit(&app, |d| d.actions.push(Action::Import)); + pump(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1); + + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + let second = app.session.active().unwrap().uid; + assert_ne!(first, second); + assert_eq!(app.session.documents().len(), 2); + open(&mut app).unwrap(); + + picker.answer_contents(&[("first.txt", b"\tstale\nQ1\t7")]); + file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, second); + assert_eq!(read(&app, |d| cell_of(&d.sheet.grid, 0, 1)), "second"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 2bfdf7b913..348287e7bd 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,13 +519,14 @@ impl GraphDesignDialog { } true }); - if let Some(options) = shown.accepted { - self.column = options; + if shown.closed.is_some() { + return Some(DialogResult::Cancel); + } + if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); - return None; } - shown.closed.map(|_| DialogResult::Cancel) + None } } @@ -836,6 +837,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { + use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; use super::GraphDesignDialog; @@ -879,6 +881,48 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { + for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_type); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + if dismiss { + h.get_by_label("OK").click_accesskit(); + h.input_mut().events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Default::default(), + }); + } else { + h.get_by_label("OK").click(); + } + h.run_steps(4); + + let app = h.state_mut(); + assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); + let expected = if dismiss { Value::Null } else { json!("New Design") }; + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], expected); + } + } + #[test] fn marker_lists_the_designs_and_applies_the_one_picked() { let (mut app, ctx) = app_with_design(); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..df899ee1c3 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,14 +372,13 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } - match (out.accepted, out.closed) { - (Some(_), _) => { - self.ok(); - None - } - (None, Some(_)) => Some(DialogResult::Cancel), - (None, None) => None, + if out.closed.is_some() { + return Some(DialogResult::Cancel); } + if out.picked == Some(0) && !waiting { + self.ok(); + } + None } } @@ -630,17 +629,17 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ p } -/// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a -/// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no -/// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. An empty `password` is none, so a place from a path with Link on and an empty -/// `password` stays linked. +/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a password), +/// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no +/// `textAs`. Bytes are a PDF by their content ([`places_pdf`]). A linked page shows the file's own +/// text, and a `.ai` or `.ait` file is placed as it says. An empty `password` is none, so a place +/// from a path with Link on and an empty `password` stays linked. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !gives_password(p); - if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { + if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || !places_pdf(p, path, name) { return; } if let Some(o) = p.as_object_mut() { @@ -648,6 +647,21 @@ pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) } } +/// Do the `file.place` params `p` place a PDF (not a `.ai` or `.ait` file, which is PDF inside): +/// a `path` by its extension, as [`place_source`] picks one, and `dataBase64` by its content, as +/// `file.place` reads it ([`fileio::detect`]: bytes that start with `%PDF`), so bytes without a +/// `name` or with another extension count too. Only the first bytes are decoded. +fn places_pdf(p: &Value, path: Option<&str>, name: &str) -> bool { + let ext = fileio::extension(name); + match (path, p.get("dataBase64").and_then(Value::as_str)) { + (None, Some(b64)) => { + let head: String = b64.chars().filter(|c| !c.is_ascii_whitespace()).take(8).collect(); + !matches!(ext.as_str(), "ai" | "ait") && vectorcraft_format::base64_decode(&head).is_some_and(|b| b.starts_with(b"%PDF")) + } + _ => ext == "pdf", + } +} + /// Keeps the Text choice OK confirmed in the `pdfTextAs` preference. fn keep_text_as(app: &mut VectorcraftApp, text_as: TextAs) { if preferred_text_as(app) != text_as { diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index 01e3012abe..d15f561816 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -16,12 +16,13 @@ use craft::behavior::{Selection, keyed}; use craft::host::PickRequest; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::patterns::form_dialogs::PathRow; +use craft::ui::primitives::Revision; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Value, json}; @@ -199,22 +200,22 @@ const LIST_ROWS: u16 = 6; fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { let source = keyed(files, |(linked, _): &(String, String)| linked.clone()); - let selection = - selected_row(files, &form.selected).and_then(|i| files.get(i)).map(|(linked, _)| Selection::single(linked.clone())).unwrap_or_default(); - let list = List::::options(tl!("Linked files")) + let selected = selected_row(files, &form.selected).map(|i| &files[i].0); + let mut selection = selected.map(|linked| Selection::single(linked.clone())).unwrap_or_default(); + List::new(tl!("Linked files")) + .select(SelectMode::Single) + .rows_stamp(Revision::of(&selected).get()) .min_rows(LIST_ROWS) .max_rows(LIST_ROWS) - .selection(Bind::given(selection)) + .selection(Bind::bound(&mut selection)) .sizing(Sizing::FillWidth) .empty(tl!("No JavaScript files linked")) .show_items(ui, &source, &mut |key, _| { // Paths and URLs are data: shown as they are. ListRow::new(files.iter().find(|(linked, _)| linked == key).map_or_else(String::new, |(_, shown)| shown.clone())) }); - for event in list.events { - if let CollectionEvent::Activate(key) = event { - form.selected = key; - } + if selection.items.first() != selected { + form.selected = selection.items.into_iter().next().unwrap_or_default(); } Field::new(caption("File or URL:")).show(ui, |ui, _| { let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); @@ -243,6 +244,7 @@ mod tests { use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; use craft::ui::testing::Fixture; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -288,6 +290,31 @@ mod tests { assert_eq!(json_selected(&panel), json!("https://example.com/b.js")); } + #[test] + fn arrow_navigation_changes_which_javascript_file_remove_unlinks() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for file in ["scripts/first.js", "scripts/second.js"] { + app.run("svgInteractivity.addFile", json!({"file": file})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap(); + panel.frame(); + panel.frame(); + + panel.click("scripts/first.js"); + assert_eq!(json_selected(&panel), "scripts/first.js"); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + // A selection changed outside the list gives the next arrow its new starting row. + set_field(&panel, "selected", "scripts/first.js"); + panel.frame(); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + panel.click(tl!("Remove")); + assert_eq!(panel.app().session.active().unwrap().doc.svg_scripts, ["scripts/first.js"]); + } + /// In a frame drawn with read roots in force, the list names a linked file outside them by its /// file name alone, and that name unlinks it; the person sees the whole path. #[test] diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 3ed57d9471..944051cf7d 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); Ok(Value::Null) } @@ -410,6 +411,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { /// the dialog open with the reason under its rows. pub(crate) struct LayerOptionsDialog { id: DialogId, + document: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -421,8 +423,8 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } } /// The OK filed by the user, once. @@ -571,7 +573,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let Some((document, value)) = dialogs.with(|host| { + let dialog = host.get_mut::()?; + Some((dialog.document, dialog.take_filed()?)) + }) else { + return; + }; let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), @@ -579,8 +586,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => None, }; // Isolation mode can start while the dialog is open. - let answer = match sublayer { - Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + let answer = match app.session.active().filter(|st| st.uid == document) { + None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } _ => { @@ -681,6 +689,48 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + #[test] + fn layer_options_and_new_layers_follow_their_document() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let mut app = app(); + let source_id = app.session.active().unwrap().doc.layers[0].id; + app.run("file.new", json!({"width": 160, "height": 160})).unwrap(); + let destination_id = app.session.active().unwrap().doc.layers[0].id; + assert_eq!(destination_id, source_id, "the two documents reuse a layer ID"); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + app.run(command, arguments).unwrap(); + set(&mut app, "name", json!("Source Draft")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = open_id(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + + let layers = |app: &VectorcraftApp| { + let mut names = vec![]; + app.session.active().unwrap().doc.walk(|node| { + if node.is_layer() { + names.push(node.display_name()); + } + }); + names + }; + activate(&mut app, 1); + let before = layers(&app); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert!(layers(&app).iter().any(|name| name == "Source Draft")); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } + /// Two layers with different options, the first plain and the second green, locked, in /// outline view and dimmed to 30%. fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) { diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index e0e68d0eda..4e36bbaddc 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -220,6 +220,33 @@ mod tests { assert!(!manager_open(&app), "Close"); } + #[test] + fn a_late_preset_import_keeps_the_reopened_managers_selection() { + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + let exported = app.run("pdf.preset.export", json!({"names": ["Mine"]})).unwrap(); + let bytes = exported["data"].as_str().unwrap().as_bytes(); + + open(&mut app, Some("PDF/X-4:2010")); + press(&mut app, ManagerAction::Import); + assert_eq!(picker.requests().len(), 1, "Import requested a file"); + host(&app, |h| h.cancel_by_id(&ctx(&app), dialog_id(KEY))); + open(&mut app, Some("Press Quality")); + let ctx = ctx(&app); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert!(app.session.prefs.pdf_presets.iter().any(|preset| preset.name == "Mine 2"), "the late reply still imports: {}", app.ui.status); + assert_eq!(manager_fields(&mut app)["selected"], "Press Quality"); + + press(&mut app, ManagerAction::Import); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert_eq!(manager_fields(&mut app)["selected"], "Mine 3", "the original manager selects its own import"); + } + #[test] fn import_and_export_go_through_files() { let dir = std::env::temp_dir().join(format!("vc-pdfpresets-ui-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index bed5ab085b..d75a811a74 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, + app.session.active().map(|st| st.uid), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, + /// The document whose grid Define Grid edits. + source_document: Option, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -190,10 +193,18 @@ pub(super) struct GridDialog { } impl GridDialog { - fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String) -> Self { + fn new( + def: GridDefinition, + mode: GridMode, + source_document: Option, + (ppi, bare_points): (f64, bool), + presets: Vec, + new_name: String, + ) -> Self { let mut dialog = GridDialog { id: dialog_id(KIND), mode, + source_document, draft: GridDraft { def }, presets: Vec::new(), rows: Vec::new(), @@ -516,9 +527,12 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { + if app.session.active().map(|st| st.uid) != source_document { + return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } @@ -546,10 +560,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let filed = dialogs.with(|host| { let dialog = host.get_mut::()?; dialog.set_presets(presets, new_name); - dialog.held.take().map(|def| (dialog.mode.clone(), def)) + dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def)) }); - let Some((mode, def)) = filed else { return }; - let next = file(app, &mode, &def); + let Some((mode, source_document, def)) = filed else { return }; + let next = file(app, &mode, source_document, &def); if let Err(why) = &next { app.status(why.clone()); } diff --git a/crates/ui-egui/src/dialogs/preset_manager.rs b/crates/ui-egui/src/dialogs/preset_manager.rs index 319d3a49b3..ed62539226 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -160,8 +160,8 @@ pub(crate) fn above(saved: Option, built_ins: usize) -> usize { (saved.unwrap_or(0) + built_ins).saturating_sub(1) } -/// Ask for a preset file and run `command` on it, then select the first preset it imported in the open manager -/// `key`. Returns at once: the answer arrives later. +/// Ask for a preset file and run `command` on it. Select the first imported preset if the manager +/// that opened the picker is still open. pub(crate) fn import( app: &mut VectorcraftApp, key: &'static str, @@ -169,14 +169,20 @@ pub(crate) fn import( filter: &str, exts: &[&str], ) -> Result, String> { - // PLAN: assumed `file_asks::open_params(&Picked) -> Option>` (fl.A23) also names a picked file - // of the web, which the import commands may not read yet. + let id = dialog_id(key); + let opening = with_manager(app, id, |manager| Arc::clone(&manager.opening)); let request = PickRequest::open(key).filter(filter, exts); file_asks::ask(app, request, Owner::Free, move |app, picked| { - let params = file_asks::open_params(&picked).ok_or("cancelled")?; + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + // Preset import commands take the file contents without the browser's suggested name. + params.remove("name"); let imported = app.run(command, Value::Object(params))?; - if let Some(first) = imported["imported"].get(0).and_then(Value::as_str) { - with_manager(app, dialog_id(key), |manager| manager.selected = first.to_owned()); + if let (Some(opening), Some(first)) = (opening, imported["imported"].get(0).and_then(Value::as_str)) { + with_manager(app, id, |manager| { + if Arc::ptr_eq(&opening, &manager.opening) { + manager.selected = first.to_owned(); + } + }); } Ok(imported) }); @@ -220,6 +226,8 @@ fn with_manager(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut Prese /// A preset manager dialog: draws the rows and the detail it holds and queues the user's events. pub(crate) struct PresetManager { id: DialogId, + /// Distinguishes successive openings that share the same dialog ID. + opening: Arc<()>, source: &'static Source, title: Label, rows: Vec, @@ -237,6 +245,7 @@ impl PresetManager { fn new(source: &'static Source, rows: Vec, selected: String, stored: Value, detail: Vec) -> Self { let mut manager = PresetManager { id: dialog_id(source.key), + opening: Arc::new(()), source, title: Label::from((source.title)()), rows: Vec::new(), diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 1ffc090a25..fc415fbcda 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -475,6 +475,7 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(count(&app), before + 1); swatch_conflicts_are_asked_again_when_they_change(&mut app); all_artboards_leaves_backgrounds_out(&mut app); + all_artboards_asks_no_swatch_conflict_for_backgrounds(&mut app); // It changes the working space: last. app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); an_answer_waits_for_the_question_it_answers(&mut app, &tagged); @@ -500,3 +501,27 @@ fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } + +/// Swatch Conflict for Paste on All Artboards asks about the colors it brings, without the +/// backgrounds of copied artboards: pasting back into the document the art came from, where only +/// the RGB background now has another profile, converts nothing, so the edited CMYK swatch is no +/// conflict and the paste runs. A plain paste converts the background and asks. +fn all_artboards_asks_no_swatch_conflict_for_backgrounds(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": null })).unwrap(); + app.run("swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})).unwrap(); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + answer_cancel(app, swatch_conflict::id(app).expect("Swatch Conflict is open")); + let r = app.run(ALL_ARTBOARDS, json!({"profileMismatch": "convert"})).unwrap(); + assert!(r.get("dialog").is_none() && r["ids"].as_array().is_some_and(|ids| !ids.is_empty()), "{r}"); + assert!(swatch_conflict::id(app).is_none()); +} diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index b4982f3710..a5987f699b 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -17,7 +17,7 @@ //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{PickRequest, Picked, Wake}; @@ -32,7 +32,7 @@ use vectorcraft_render::proof; use super::host::{HeldOptions, open_held_with}; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask}; +use crate::file_asks::{Owner, ask, ask_while}; use crate::menus::Node; /// The dialog kind of Proof Setup › Customize. @@ -53,6 +53,8 @@ const LOAD_BUTTON: &str = "load"; pub(crate) struct Open { /// The dialog on the window's stack. id: DialogId, + /// The identity of this opening, since Proof Setup reuses the dialog ID. + opening: Arc<()>, /// The proof view the dialog found, which Cancel puts back after a preview. before: proof::ProofView, /// The proof view the preview last put on the canvas; `None` while no preview of this dialog is shown. @@ -89,7 +91,7 @@ pub fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KIND, fields, build); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) { - Some(id) => app.ui.proof_setup = Some(Open { id, before, shown: None, sent: None }), + Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }), None => app.status(tl!("There is no window to show Proof Setup in.")), } } @@ -330,12 +332,17 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { /// Load…: the picked file's settings fill the dialog `id` (Preview then shows them). fn load(app: &mut VectorcraftApp, id: DialogId) { + let Some(opening) = app.ui.proof_setup.as_ref().filter(|open| open.id == id).map(|open| Arc::clone(&open.opening)) else { return }; let mut request = PickRequest::open("proof-setups").filter("Proof setups", &[EXT]); // Before a setup is saved there is no folder, and the picker starts in its own default folder. if let Some(dir) = app.session.proof_setup_dir().filter(|dir| dir.is_dir()) { request = request.directory(dir); } - ask(app, request, Owner::Free, move |app, picked| { + let is_live = move |app: &VectorcraftApp| { + app.ui.proof_setup.as_ref().is_some_and(|open| open.id == id && Arc::ptr_eq(&opening, &open.opening)) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + ask_while(app, request, Owner::Free, is_live, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; let fields = [ @@ -345,7 +352,6 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { ("simulatePaper", "simulatePaper"), ("simulateBlack", "simulateBlack"), ]; - // The dialog may have closed while the picker was open: then there is nothing to fill. // PLAN: sh.K23's `set_json_fields` refuses a row that is disabled by the file's own device (an RGB // device disables paper and black ink), so the whole load would fail; the values are set unchecked. if let Some(dialogs) = app.dialogs() { @@ -811,6 +817,39 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-delayed-load"); + let file = dir.join(format!("Pending.{EXT}")); + app.run("view.proofSetup.save", json!({"path": file.to_string_lossy(), "target": WORKING, "intent": "saturation"})).unwrap(); + let files = scripted(&mut app, ScriptedFiles::held()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 1, "Load requested a file"); + cancel_dialog(&mut app, &ctx); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "intent", json!("perceptual")); + set(&mut app, &ctx, "preview", json!(true)); + let view = proof::view(); + + files.answer(Picked::Paths(vec![file.clone()])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "perceptual", "the reopened dialog keeps its own rendering intent"); + assert_eq!(proof::view(), view, "the reopened dialog keeps its own proof preview"); + + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 2, "Load in the current opening requested a file"); + files.answer(Picked::Paths(vec![file])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "saturation", "a reply to the current opening fills the dialog"); + assert_eq!(proof::view().setup.intent, Intent::Saturation, "the current opening previews the loaded setup"); + cancel_dialog(&mut app, &ctx); + } + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind; the /// folder stays while the picker is open and when a file is saved in it. #[test] diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e9c0760844..3768c182d2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1505,6 +1505,7 @@ impl Feed { /// What the pump works on with the app, out of the host: the values, their steps and what `show` /// asked for. struct Work { + opening: Arc<()>, fields: Fields, steps: Steps, filed: Filed, @@ -1544,7 +1545,7 @@ impl Work { randomize(app, &mut self.fields, sb); } if filed.library { - pick_library(app); + pick_library(app, Arc::clone(&self.opening)); } let d = &mut self.fields; if let Some(before) = filed.edited { @@ -1591,16 +1592,16 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. -fn pick_library(app: &mut VectorcraftApp) { +fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); - // PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| { + // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. + crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("swatch.library.load", json!({ "path": path }))?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { - if let Some(d) = host.get_mut::() { + if let Some(d) = host.get_mut_by_id::(dialog_id(KIND)).filter(|d| Arc::ptr_eq(&opening, &d.opening)) { d.fields.fields.insert("limitTo".into(), library); } }); @@ -1765,6 +1766,8 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { /// commits the recolour. pub(crate) struct RecolorDialog { id: DialogId, + /// The identity of this opening, since Recolor Artwork reuses its dialog ID. + opening: Arc<()>, fields: Fields, steps: Steps, held: HeldAnswer, @@ -1787,6 +1790,7 @@ impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { id: dialog_id(KIND), + opening: Arc::new(()), feed: Feed::of(app, &fields), steps: Steps::opened(snapshot(&fields)), fields, @@ -1803,6 +1807,7 @@ impl RecolorDialog { /// The values, steps and requests, for the pump to work on with the app. fn take_work(&mut self) -> Work { Work { + opening: Arc::clone(&self.opening), fields: std::mem::take(&mut self.fields), steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())), filed: std::mem::take(&mut self.filed), diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index d6b74551f5..6eb9001c3b 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -19,14 +19,15 @@ pub(crate) const CMD: &str = "artboard.rename"; /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - (indices, name.to_owned()) - }); + let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; + let document = st.uid; + let selected: Vec<_> = + crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); + let name = match selected.as_slice() { + [one] => one.name.clone(), + _ => String::new(), + }; + let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { @@ -39,6 +40,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if name.trim().is_empty() { return Ok(()); } + let st = + app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + let indices = artboards + .iter() + .map(|id| st.doc.artboards.iter().position(|board| board.id == *id)) + .collect::>>() + .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { app.status(e); } @@ -105,6 +113,51 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } + #[test] + fn rename_follows_the_original_artboards_after_reordering() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap(); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + } + + #[test] + fn rename_waits_for_the_document_it_opened_in() { + let mut app = app(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open(), "the original document can still answer"); + + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]); + assert!(!app.any_dialog_open()); + } + + #[test] + fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.delete", json!({"index": 2})).unwrap(); + app.run("artboard.duplicate", json!({"index": 1})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open()); + } + /// OK with an empty name or the name the artboard already has records no undo step. #[test] fn nothing_changes_for_an_empty_or_unchanged_name() { diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index 32ac3dd51a..6689cc6cc9 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -135,7 +135,8 @@ fn stopped_prompt(fields: &Value) -> StandardPrompt { /// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the /// plug-ins load, without the stopped ones for Disable and Continue (kept off for later launches -/// too). +/// too), then the startup scripts run ([`crate::script_runs::run_at_launch`]), without a disabled +/// one. fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { let items = stopped_items(&app.ui.stopped_plugin.take().unwrap_or(Value::Null)); // When a disabled plug-in can't be saved for the next launch, that launch asks again. Every @@ -154,6 +155,8 @@ fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { } safe_mode::set_active(None); vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut app.session); + // The launch's startup scripts waited for Safe Mode to end. + crate::script_runs::run_at_launch(app); } /// Help › Safe Mode: the disabled plug-ins, none ticked for Enable on Re-launch. A plug-in disabled diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 82a613dfc5..e003cf6a7e 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -14,7 +14,7 @@ use std::sync::Arc; -use craft::ui::dialog::DialogId; +use craft::ui::dialog::{DialogHost, DialogId}; use craft::ui::patterns::form_dialogs::{ HostedPdfExport, ParamResult, PdfArtboards, PdfExportAnswer, PdfExportMode, PdfExportWords, PdfPresetEvent, PresetDraft, }; @@ -378,6 +378,119 @@ pub(crate) fn dialog_set(app: &mut VectorcraftApp, params: &Value) -> Option Option> { + let named = (params["dialog"] == "top" && host.open_dialogs().last().map(|d| d.id) == Some(id)) + || params["dialog"] == id.value() + || params["dialog"].as_str() == Some(id.value().to_string().as_str()); + let known = params.as_object()?.keys().all(|k| matches!(k.as_str(), "dialog" | "field" | "value" | "fields")); + if !named || !known { + return None; + } + let item = |f: &Value| Some((f.get("field")?.as_str()?.to_owned(), f.get("value").cloned().unwrap_or(Value::Null))); + let items: Vec<(String, Value)> = match params.get("fields") { + Some(_) if params.get("field").is_some() || params.get("value").is_some() => return None, + Some(list) => { + list.as_array().filter(|l| l.len() <= craft::automation::dialogs::MAX_DIALOG_FIELDS)?.iter().map(item).collect::>()? + } + None => vec![item(params)?], + }; + let settings = |host: &DialogHost| host.get_by_id::(id).and_then(|d| serde_json::to_value(d.settings()).ok()); + let now = settings(host)?; + if !items.iter().any(|(field, _)| option_at(&now, field).is_some_and(Value::is_object)) { + return None; + } + let before = dialog_fields(host, id); + let passwords = host.get_by_id::(id).map(|d| { + let security = &d.settings().security; + [("security.openPassword", security.open_password.clone()), ("security.permissionsPassword", security.permissions_password.clone())] + }); + let mut changed = false; + for (field, value) in &items { + let set = match settings(host).as_ref().and_then(|s| option_at(s, field)).filter(|v| v.is_object()) { + Some(_) if !value.is_object() => Err(format!("`{field}` must be an object of options, not {value}")), + Some(old) => { + let mut merged = old.clone(); + merge_options(&mut merged, value); + host.set_json_field(ctx, id, field, merged) + } + None => host.set_json_field(ctx, id, field, value.clone()), + }; + if let Err(e) = set { + // A refused field leaves the dialog as it was, so only the fields set before it go back. + if changed { + restore_fields(host, ctx, id, before, passwords); + } + return Some(Err(e)); + } + changed = true; + } + Some(Ok(())) +} + +/// The JSON fields of the open dialog `id`. +fn dialog_fields(host: &DialogHost, id: DialogId) -> Option { + host.open_dialogs().into_iter().find(|d| d.id == id).and_then(|d| d.fields) +} + +/// The option at the dotted `path` (`compression.color`) of the settings `settings`. +fn option_at<'a>(settings: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(settings, |at, key| at.get(key)) +} + +/// Set the options `over` holds on `base`, object by object; any other value replaces `base`. +fn merge_options(base: &mut Value, over: &Value) { + match (base, over) { + (Value::Object(b), Value::Object(o)) => { + for (k, v) in o { + match b.get_mut(k) { + Some(slot) => merge_options(slot, v), + None => { + b.insert(k.clone(), v.clone()); + } + } + } + } + (b, o) => *b = o.clone(), + } +} + +/// Set the dialog `id`'s fields that differ from `before` back to it. The preset goes first, since choosing it +/// replaces every setting and clears the passwords. The `passwords` the dialog had, which its fields leave out, are set +/// back last when they differ. +fn restore_fields(host: &mut DialogHost, ctx: &egui::Context, id: DialogId, before: Option, passwords: Option<[(&str, String); 2]>) { + let Some(Value::Object(before)) = before else { return }; + let preset = before.get("preset").filter(|old| dialog_fields(host, id).as_ref().and_then(|now| now.get("preset")) != Some(*old)); + if let Some(old) = preset { + let _ = host.set_json_field(ctx, id, "preset", old.clone()); + } + // The standard goes next, since it enables and sets other fields. A field that another one still disables is set + // again in a later pass, once that one is back; one that stays disabled keeps its value, as the framework's own + // rollback leaves it. + let rest = || before.get_key_value("standard").into_iter().chain(before.iter().filter(|(k, _)| !matches!(k.as_str(), "preset" | "standard"))); + for _ in 0..3 { + let now = dialog_fields(host, id).unwrap_or(Value::Null); + let differ: Vec<_> = rest().filter(|(name, old)| now.get(name.as_str()) != Some(*old)).collect(); + if differ.is_empty() { + break; + } + for (name, old) in differ { + let _ = host.set_json_field(ctx, id, name, old.clone()); + } + } + let now = host + .get_by_id::(id) + .map(|d| [d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone()]); + for ((name, password), now) in passwords.into_iter().flatten().zip(now.into_iter().flatten()) { + if password != now { + let _ = host.set_json_field(ctx, id, name, Value::String(password)); + } + } +} + /// The dialog's `settings` with the job's Custom… flattener options, as the export gets them. fn with_custom(open: &SavePdfOpen, mut settings: Value) -> Value { if let Some(options) = open.job.as_ref().and_then(|job| job.flattener.as_ref()).and_then(|f| serde_json::to_value(f).ok()) { diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index f41ee64794..2f1ea8b8e2 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -640,6 +640,121 @@ fn presets_reset_the_settings_and_fields_fall_back_to_defaults() { assert!(!is_open(&app)); } +/// `ui.dialog.set` with `params` as a control request, and its reply. +fn dialog_request(app: &mut VectorcraftApp, params: Value) -> Value { + let ctx = app.ui_ctx.clone().expect("a UI context"); + let (req, _) = craft::automation::ControlRequest::new("ui.dialog.set", params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("ui.dialog.set answered later") }; + r +} + +/// The four bleed sides the dialog shows: top, bottom, left, right. +fn bleed_sides(app: &VectorcraftApp) -> [Value; 4] { + ["top", "bottom", "left", "right"].map(|side| fget(app, &format!("bleed.{side}"))) +} + +/// A settings object `ui.dialog.set` sets changes only the options it holds: the others keep the dialog's values, +/// so linking the bleed gives every side the top value the dialog shows. +#[test] +fn a_settings_object_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Low", "compression": {"color": {"ppi": 123}}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + + dialog_set(&mut app, "bleed", json!({"useDocument": false})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "the sides left out keep their values"); + dialog_set(&mut app, "bleedLinked", json!(true)); + assert_eq!(bleed_sides(&app), [3.0; 4].map(Value::from), "linking gives every side the top value"); + dialog_set(&mut app, "bleed", json!({"bottom": 5})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "only the side set changes"); + let r = dialog_request(&mut app, json!({"fields": [{"field": "bleed", "value": {"top": 4}}, {"field": "bleed", "value": {"left": 6}}]})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(bleed_sides(&app), [4.0, 5.0, 6.0, 3.0].map(Value::from), "each object of a list builds on the one before"); + + // Every settings object, not only the bleed. + set_field(&app, "preset", json!("Marked")); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); + + // An object inside a settings object, set whole or by its dotted name. + set_field(&app, "preset", json!("Low")); + dialog_set(&mut app, "compression", json!({"color": {}, "compressText": false})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.compressText")), (json!(123.0), json!(false))); + dialog_set(&mut app, "compression.color", json!({"abovePpi": 200})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.color.abovePpi")), (json!(123.0), json!(200.0))); + + // A value that isn't an object is refused, and the dialog stays as it was. + let before = fields(&app); + for bad in [json!(5), json!("3 mm"), json!([false, 3, 3, 3, 3]), Value::Null] { + let r = dialog_request(&mut app, json!({"field": "bleed", "value": bad})); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`bleed` must be an object of options")), "{bad}: {r}"); + assert_eq!(fields(&app), before, "{bad}"); + } +} + +/// The preset editor's settings objects keep the options they leave out too. +#[test] +fn a_settings_object_in_the_preset_editor_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + open_preset(&mut app, &json!({"name": "Marked"})).unwrap(); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); +} + +/// A `fields` list whose later field is refused leaves the whole dialog as it was before the request: the settings +/// objects an earlier field set, and a bleed that differs from the chosen preset's. +#[test] +fn a_refused_field_leaves_the_whole_request_unset() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + dialog_set(&mut app, "bleed", json!({"top": 7})); + let before = fields(&app); + let r = dialog_request( + &mut app, + json!({"fields": [ + {"field": "bleed", "value": {"top": 1, "bottom": 2, "left": 3, "right": 4}}, + {"field": "marks", "value": {"trim": true}}, + {"field": "bleedLinked", "value": "yes"}, + ]}), + ); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(fields(&app), before, "the dialog is unchanged"); + assert_eq!(fget(&app, "bleed.top"), 7.0); +} + +/// A refused settings object keeps the passwords the dialog holds, whether it is refused at once, after an earlier +/// settings object was set, after a preset the request chose, after a password the request set, or after a standard +/// that disables other fields. +#[test] +fn a_refused_settings_object_keeps_the_passwords() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({})).unwrap(); + set_field(&app, "security.openPassword", json!("open")); + set_field(&app, "security.permissionsPassword", json!("own")); + let passwords = + |app: &VectorcraftApp| with_pdf(app, |d| (d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone())); + let requests = [ + json!({"field": "bleed", "value": null}), + json!({"fields": [{"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "preset", "value": "Uneven"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "security.openPassword", "value": "other"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "standard", "value": "pdfX1a"}, {"field": "bleed", "value": 5}]}), + ]; + for request in requests { + let before = fields(&app); + let r = dialog_request(&mut app, request.clone()); + assert_eq!(r["ok"], false, "{request}: {r}"); + assert_eq!(fields(&app), before, "{request}"); + assert_eq!(passwords(&app), ("open".to_string(), "own".to_string()), "{request}"); + } +} + /// The bytes and status a save writes after `setup` and the given field writes. fn written_with(setup: impl FnOnce(&mut VectorcraftApp), options: &[(&str, Value)]) -> (Vec, String) { let (mut app, written) = app(); diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index d14a41fb74..0bbf1e89ea 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -137,6 +137,7 @@ impl ItemSource for Shown<'_> {} /// The saved-names dialog of one kind. pub(crate) struct SavedNamesDialog { id: DialogId, + document: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -147,10 +148,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(names: SavedNames, list: Vec) -> Self { + fn new(document: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -326,8 +327,9 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); Ok(()) } @@ -335,18 +337,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec)> = dialogs.with(|host| { + let filed: Vec<_> = dialogs.with(|host| { host.open_dialogs() .into_iter() .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.names.command, edits)) }) .collect() }); - for (id, command, edits) in filed { - let outcome = app.run(command, json!({ "edits": edits })); + for (id, document, command, edits) in filed { + let outcome = if app.session.active().is_some_and(|active| active.uid == document) { + app.run(command, json!({ "edits": edits })) + } else { + Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + }; if let Err(reason) = &outcome { app.status(reason.clone()); } @@ -357,3 +363,62 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_names_edits_stay_with_their_document() { + for is_view in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + for size in [100, 200] { + app.run("file.new", json!({"width": size, "height": size})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + } + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let kind = if is_view { + crate::dialogs::edit_views::open(&mut app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(&mut app).unwrap(); + crate::dialogs::edit_selection::KIND + }; + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + h.confirm_by_id(&ctx, id); + }); + + activate(&mut app, 1); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + host.with(|h| h.confirm_by_id(&ctx, id)); + pump(&mut app, &ctx); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } +} diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 7e15614537..488fb70e57 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -4,7 +4,8 @@ //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show -//! External Script Warning off, the chosen script runs at once. The warning (kind `scriptRun`) is a +//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts +//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a //! prompt: its `choice` field (`proceed` runs, `cancel` does not) and `skip` (true: turn the //! warning off). The growth question (`scriptGrowth`) and the question quitting asks //! (`scriptClose`) have the `choice` field alone. @@ -421,6 +422,11 @@ pub(crate) fn with_host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost, Some(app.dialogs()?.with(|host| f(host, &ctx))) } +/// Whether the question asked on quitting with a script running is open. +pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.is_open::()).unwrap_or(false) +} + /// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) @@ -477,7 +483,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result() { let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - let run = |app: &mut VectorcraftApp| app.run("script.run", params).map(drop); + let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop); let automated = automated || app.automation_asked(); if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) { app.status(e); @@ -593,19 +599,42 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } None => {} } + answer_close(app, close); + if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { + choose(app); + } +} + +/// Takes the answer to the quit question given between two queued runs, before the next run +/// starts. True when it stopped the runs. +pub(crate) fn answer_close_between_runs(app: &mut VectorcraftApp) -> bool { + let Some(close) = with_host(app, |host, _| host.take::()).flatten() else { + return false; + }; + answer_close(app, Some(close)); + !app.session.script_running() +} + +/// With Stop as the answer to the quit question, stops the run, or between two queued runs, the +/// runs not yet started. +fn answer_close(app: &mut VectorcraftApp, close: Option::Result>>) { + let startup = app.session.startup_script_running(); + // Between two queued runs: none runs, and the report is the last run's. + let between = app.session.script_running() && app.session.script_name().is_none(); if let Some(DialogResult::Ok(answer)) = close && answer.choice == PromptChoice::Proceed && app.session.script_abandon() { - let error = app.session.script_failure_text().unwrap_or_default(); - crate::script_runs::failed(app, error); + if between { + crate::script_runs::stopped_between_runs(app); + } else { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::ended_with_error(app, startup, error); + } forget::(app); forget::(app); app.sync_views(); } - if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { - choose(app); - } } /// Gives the running script the answer of its dialog. Cancel is Cancel for a prompt, No for a diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 03adb3ea1b..b0d7b34fa0 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -220,7 +220,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option bool { - found(app, params).is_some_and(|now| Value::Array(now) != *asked) +/// Whether the conflicts paste `command` with `params` raises are no longer the `asked` ones (another profile +/// converts the pasted swatches meanwhile): it asks about them again. +pub(crate) fn changed(app: &mut VectorcraftApp, command: &str, params: &Value, asked: &Value) -> bool { + found(app, command, params).is_some_and(|now| Value::Array(now) != *asked) } -/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as -/// the paste brings them: converted from another profile when it converts. -fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { +/// The swatch conflicts paste `command` with `params` raises (`clipboard.conflicts`), with the +/// swatches as the paste brings them: converted from another profile when it converts, and for +/// Paste on All Artboards without the backgrounds of copied artboards, which it leaves behind. +fn found(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { let mut q = json!({}); if let Some(m) = params.get("profileMismatch") { q["profileMismatch"] = m.clone(); } + if command == "edit.pasteOnAllArtboards" { + q["allArtboards"] = json!(true); + } let found = app.session.execute("clipboard.conflicts", &q).ok()?; found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..622756a1bd 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -1,6 +1,7 @@ //! The Import PDF dialog: opening and placing multi-page and password-protected PDFs. use craft::ui::dialog::{HeldOk, StackDialog}; +use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; @@ -72,6 +73,50 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } +fn click_page_footer_ok(app: VectorcraftApp, dismiss: bool) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::import_pdf::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + if dismiss { + h.get_by_label("OK").focus(); + h.run_steps(2); + h.get_by_label("OK").click_accesskit(); + h.input_mut().events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Default::default(), + }); + } else { + h.get_by_label("OK").click(); + } + h.run_steps(4); + assert!(!is_open(h.state())); + h +} + +#[test] +fn pdf_page_footer_ok_opens_the_chosen_range() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); + + let h = click_page_footer_ok(app, false); + assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); +} + #[test] fn opening_a_multi_page_pdf_asks_for_the_pages() { let mut app = app(); @@ -228,6 +273,24 @@ fn place(app: &mut VectorcraftApp, bytes: &[u8], extra: serde_json::Value) -> Re crate::place::run(app, &p) } +#[test] +fn pdf_page_footer_ok_places_the_chosen_page_unless_dismissed() { + for dismiss in [false, true] { + let mut app = app(); + place(&mut app, &three_pages(), json!({"at": [100, 120], "link": false})).unwrap(); + set(&mut app, "page", json!(2)); + set(&mut app, "cropTo", json!("art")); + + let h = click_page_footer_ok(app, dismiss); + if dismiss { + assert!(h.state().session.active().unwrap().selection.objects.is_empty()); + } else { + let (_, bounds) = placed(h.state()); + assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); + } + } +} + #[test] fn placing_a_pdf_page_asks_for_the_page_and_crop_box() { let mut app = app(); @@ -493,6 +556,81 @@ fn the_text_choice_applies_to_embedded_places_only() { assert_eq!(type_objects(&app), before, "placed as outlines"); } +/// `file.place` run as a command (MCP, scripts) without the dialog takes the PDF Text preference for +/// an embedded PDF with no `textAs`, as a place by the user does; a `textAs` given and a linked +/// place keep their own text. +#[test] +fn file_place_without_the_dialog_takes_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-at-once"); + let path = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(2)).unwrap(); + let embedded = json!({"path": path, "link": false, "showImportOptions": false}); + crate::place::run(&mut app, &embedded).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "the preference: outlines"); + + let one = json!({"name": "one.pdf", "dataBase64": vectorcraft_format::base64_encode(&text_pages(1))}); + crate::place::run(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 0, "one page from bytes: outlines"); + + let mut given = embedded.clone(); + given["textAs"] = json!("text"); + crate::place::run(&mut app, &given).unwrap(); + assert_eq!(type_objects(&app), 1, "a textAs given is kept"); + + crate::place::run(&mut app, &json!({"path": path, "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + + // `file.place` reads an empty password as none, so the page stays linked. + crate::place::run(&mut app, &json!({"path": path, "password": "", "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "an empty password: linked: {:?}", placed.kind); + + set_pdf_text(&mut app, "text"); + crate::place::run(&mut app, &embedded).unwrap(); + assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); +} + +/// PDF bytes placed without a `name`, or under another extension, are a PDF by their content, as +/// `file.place` reads them, and take the PDF Text preference; under a `.ai` name they are placed as +/// the file says. +#[test] +fn pdf_bytes_without_a_pdf_name_take_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let data = vectorcraft_format::base64_encode(&text_pages(1)); + crate::place::run(&mut app, &json!({"dataBase64": data, "showImportOptions": false})).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "unnamed bytes: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.bin", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 0, "another extension: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.ai", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 1, "a .ai file: its own text"); +} + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without a `password` does. +#[test] +fn an_empty_password_asks_for_the_password_of_an_encrypted_pdf() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + place(&mut app, &bytes, json!({"password": "", "showImportOptions": false})).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert!(!is_open(&app)); + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).and_then(|n| n.geometric_bounds()).unwrap(); + assert!((b.width() - 120.0).abs() < 0.01, "placed once unlocked: {}", b.width()); +} + /// `file.place` reads an empty or null `password` as none: a place from a path with Link on stays /// linked with the PDF Text preference at Outlines, and only a password that is given embeds it. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 90af85ee0c..089296ae7a 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -104,6 +104,39 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() { assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle())); } +#[test] +fn define_grid_applies_only_to_the_document_where_it_opened() { + let mut app = app(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let destination = app.session.active().unwrap(); + let destination_uid = destination.uid; + let destination_undo = destination.history.undo.len(); + let destination_grid = grid(&app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let source_uid = app.session.active().unwrap().uid; + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#112233")).unwrap(); + let ctx = window(&app); + let id = dialog_id(super::perspective_grid::KIND); + host(&app, |h| { + assert!(!h.confirm_by_id(&ctx, id)); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + super::perspective_grid::pump(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().uid, destination_uid); + assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source_uid); + ok(&mut app); + assert_eq!(kind(&app), None); + assert_eq!(grid(&app).right_color.hex(), "#112233"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 8a73810d89..af68809f46 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -67,6 +67,36 @@ fn stays_open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, log) = app(1, true); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + open(&mut app); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + export_for_screens::pump(&mut app, &ctx); + + assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Destination.png"]); +} + fn temp_folder(tag: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id())) } diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 8345aad401..1bf8a87680 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -55,6 +55,8 @@ pub(crate) struct Data { pub bevels_file: bool, /// The active document, for the symbol pictures. pub doc: Option>, + /// The document that owns the object IDs accepted by the Graphics drop target. + pub document_uid: Option, /// The active document's version. pub revision: u64, /// Whether the active document has a selection. @@ -77,6 +79,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map Option { Text::new(tl!("Graphics")).show(ui); let mut action = None; - let (Some(doc), true) = (data.doc.clone(), true) else { return action }; + let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let keys = crate::panels::symbols::document_symbols(&doc, data.revision); let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str())); - let mut dropped = DropAction::::new(|drag| matches!(drag, PanelDrag::Art { .. })).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid)); + let mut dropped = drop_art.show(ui, |ui, _| { TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| { let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) }; let (doc, keys, name) = (doc.clone(), keys.clone(), name.clone()); diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index c8170460a3..8ec6e39b37 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -1,7 +1,8 @@ //! The progress window of the work that runs in the background: a Background Export (artboard by //! artboard, file by file for Export for Screens, as a share for an exporter plug-in that reports //! its progress, busy for one artboard and for formats made in one go), a Background Save, a -//! heavy plug-in filter, an Image Trace, a file being opened and a file being read for Place. Each +//! heavy plug-in filter, an Image Trace, a file being opened, a file being read for Place and +//! Retype's search of the installed fonts. Each //! job table answers [`Shown`] for its first job the window shows; [`show`] draws the first //! table's window once its job has run [`DELAY`], with Cancel and, where the job can go on without //! it, Continue in Background. @@ -53,6 +54,7 @@ fn first(app: &VectorcraftApp) -> Option { .or_else(|| crate::trace_runs::shown(app)) .or_else(|| crate::opening::shown(app)) .or_else(|| crate::placing::shown(app)) + .or_else(|| crate::retype_runs::shown(app)) } /// Draws the progress window of the first job that has one, once it has run [`DELAY`] seconds and diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index ba6a6f57dd..b5df477b42 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -21,6 +21,8 @@ use crate::VectorcraftApp; use crate::dialogs::confirm::{ReplaceFiles, ReplaceFilesPrompt}; type Then = Box Result>; +/// Whether the part of the app that requested a pick is still waiting for it. +type PickGuard = Box bool>; /// What proceeding past a replace question runs. type Proceed = Box Result>; @@ -45,6 +47,7 @@ struct Waiting { scope: ScopeHandle, /// Automation asked ([`VectorcraftApp::automation_asked`]): the continuation runs as its. automated: bool, + current: Option, then: Then, } @@ -120,7 +123,18 @@ pub(crate) fn ask( owner: Owner, then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result + 'static, ) -> Value { - start(app, owner, |files| files.pick(request), then) + start(app, owner, |files| files.pick(request), None, then) +} + +/// Like [`ask`], but drops a reply if its requester is gone, before choosing a document or reporting a picker error. +pub(crate) fn ask_while( + app: &mut VectorcraftApp, + request: PickRequest, + owner: Owner, + current: impl FnOnce(&VectorcraftApp) -> bool + 'static, + then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result + 'static, +) -> Value { + start(app, owner, |files| files.pick(request), Some(Box::new(current)), then) } /// Save `bytes` as the file service saves them (`Files::save`: the desktop asks where with `request` and @@ -133,7 +147,7 @@ pub(crate) fn save( owner: Owner, then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result + 'static, ) -> Value { - start(app, owner, |files| files.save(request, bytes), then) + start(app, owner, |files| files.save(request, bytes), None, then) } /// Asks the file service with `ask` and files `then` for its answer. @@ -141,6 +155,7 @@ fn start( app: &mut VectorcraftApp, owner: Owner, ask: impl FnOnce(&dyn Files) -> PickId, + current: Option, then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result + 'static, ) -> Value { let Some(host) = app.ui_ctx.as_ref().and_then(Host::try_of_ctx) else { return Value::Null }; @@ -150,7 +165,7 @@ fn start( Owner::Free => None, }; let (scope, automated) = (ScopeHandle::capture(), app.automation_asked()); - app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, then: Box::new(then) }); + app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, current, then: Box::new(then) }); json!({ "pending": "fileDialog" }) } @@ -289,6 +304,9 @@ pub(crate) fn poll(app: &mut VectorcraftApp) { } } for (w, picked) in answered { + if w.current.is_some_and(|current| !current(app)) { + continue; + } match &picked { Picked::Cancelled => continue, Picked::Unavailable(why) => { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ec1296192f..3a04ae86fb 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -301,6 +301,33 @@ pub fn t_id<'a>(id: &str, label: &'a str) -> &'a str { tr_id(current(), id, label) } +/// The Effect menu's label of effect `id` in `lang`: an `@id` row for the effect's id, else the +/// row of its English menu label. A plug-in effect's label is the plug-in's own text. `None` for +/// an id that names no effect. The Effect menu, History, Edit › Undo and Redo, the Appearance +/// panel and the effect dialogs all name an effect through this lookup. +pub fn effect_menu_label(lang: Lang, id: &str) -> Option { + match built_in_effect_label(id) { + Some(label) => Some(tr_id(lang, id, label).to_string()), + None => vectorcraft_plugins::effect::plugin_id(id).and_then(|_| vectorcraft_effects::effect_info(id)).map(|info| info.label.to_string()), + } +} + +/// [`effect_menu_label`] without its trailing ellipsis: an effect's name in `lang`. +pub fn effect_name(lang: Lang, id: &str) -> Option { + effect_menu_label(lang, id).map(|s| s.trim_end_matches('…').to_string()) +} + +/// Does `lang`'s catalog name built-in effect `id`: an `@id` row for the id, or a row for its +/// English menu label? +pub fn has_effect_name(lang: Lang, id: &str) -> bool { + built_in_effect_label(id).is_some_and(|label| i18n().get(lang, "@id", id).is_some() || has(lang, label)) +} + +/// The English Effect menu label of built-in effect `id`. +fn built_in_effect_label(id: &str) -> Option<&'static str> { + vectorcraft_effects::built_in_effect(id).map(|(_, label)| label) +} + /// Fill `{name}` placeholders in one pass: a value that holds `{name}` text stays as it is. /// Unknown placeholders are left as written. pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cbc03abcfc..fe6dc33df5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4920,6 +4920,14 @@ axis Both И двете The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. Allow Once Разреши веднъж Always Allow This Script Винаги разрешавай този скрипт + No script has kept file access. Няма скрипт със запазен достъп до файлове. + Read file Четене на файл + Read and write file Четене и запис на файл + Read and write folder Четене и запис на папка + Revoke Отнемане + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Отнемането премахва достъпа, запазен за всяка версия на скрипта. Достъпът до папка обхваща всичко в нея. +@msg Script file access revoked Достъпът на скрипта до файлове е отнет +@msg The script file access was already revoked Достъпът на скрипта до файлове вече е отнет Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение @@ -6624,6 +6632,8 @@ arrowhead Feather Перо VectorCraft Default По подразбиране за VectorCraft VectorCraft Defaults Стандартни настройки на VectorCraft VectorCraft Generic CMYK (SWOP-like) Общ CMYK за VectorCraft (подобен на SWOP) + VectorCraft Coated CMYK (FOGRA51) Мелиран CMYK за VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) Немелиран CMYK за VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Образци на VectorCraft (.vcswatches) Vertical Align Вертикално подравняване Vertical Area Type Вертикално въвеждане в област @@ -8601,6 +8611,11 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Fold Angle Ъгъл на сгъване + Set Fold Angle… Задай ъгъл на сгъване… + Set Fold Angle Задай ъгъл на сгъване + Reset Fold Angle Нулирай ъгъла на сгъване +@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита Check Провери Check Fold Lines Провери линиите на сгъване @msg No cut lines are in the selection. В селекцията няма линии за рязане. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 4548a6576a..03096c373e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -657,6 +657,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft generički CMYK (sličan SWOP-u) + VectorCraft Coated CMYK (FOGRA51) VectorCraft premazani CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nepremazani CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Naslijeđeni Macintosh RGB (gama 1.8) Internet Standard RGB (sRGB) Internet standardni RGB (sRGB) Monitor RGB RGB monitora @@ -5139,6 +5141,14 @@ imageTrace Outline Obris The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. Allow Once Dozvoli jednom Always Allow This Script Uvijek dozvoli ovu skriptu + No script has kept file access. Nijedna skripta nema sačuvan pristup datotekama. + Read file Čitanje datoteke + Read and write file Čitanje i pisanje datoteke + Read and write folder Čitanje i pisanje foldera + Revoke Opozovi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Opozovi uklanja pristup sačuvan za svaku verziju skripte. Pristup folderu obuhvata sve u njemu. +@msg Script file access revoked Pristup skripte datotekama je opozvan +@msg The script file access was already revoked Pristup skripte datotekama je već opozvan Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje @@ -7985,6 +7995,11 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Fold Angle Ugao savijanja + Set Fold Angle… Postavi ugao savijanja… + Set Fold Angle Postavi ugao savijanja + Reset Fold Angle Poništi ugao savijanja +@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena Check Provjeri Check Fold Lines Provjeri linije savijanja @msg No cut lines are in the selection. U odabiru nema linija rezanja. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e17017d95b..b818b2e8d6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5970,6 +5970,8 @@ digits Malayalam Malaiàlam VectorCraft didn't quit normally last time. These documents had unsaved changes: VectorCraft no es va tancar correctament l’última vegada. Aquests documents tenien canvis no desats: VectorCraft documents: one locked object, updated when the file changes. Documents de VectorCraft: un objecte bloquejat, actualitzat quan canvia el fitxer. VectorCraft Generic CMYK (SWOP-like) CMYK genèric de VectorCraft (similar a SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK estucat de VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucat de VectorCraft (FOGRA52) VectorCraft Help… Ajuda de VectorCraft… VectorCraft on getartcraft.com VectorCraft a getartcraft.com VectorCraft on GitHub VectorCraft al GitHub @@ -6446,6 +6448,14 @@ digits Malayalam Malaiàlam The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. Allow Once Permet un cop Always Allow This Script Permet sempre aquest script + No script has kept file access. Cap script no ha conservat accés als fitxers. + Read file Lectura del fitxer + Read and write file Lectura i escriptura del fitxer + Read and write folder Lectura i escriptura de la carpeta + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca elimina l’accés conservat per a cada versió de l’script. L’accés a una carpeta inclou tot el que conté. +@msg Script file access revoked S’ha revocat l’accés de l’script als fitxers +@msg The script file access was already revoked L’accés de l’script als fitxers ja s’havia revocat Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís @@ -6643,6 +6653,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop @msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu @msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg the script file permissions could not be read: {e} no s’han pogut llegir els permisos de fitxers dels scripts: {e} @msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada @msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora @@ -7968,6 +7979,21 @@ variable-list-end {0}, {1} {0} i {1} @msg time budget pressupost de temps @msg memory budget (the selection is too large to hand over) pressupost de memòria (la selecció és massa gran per passar-la) @msg output size ({what} is {len} bytes, limit {max}) mida de la sortida ({what} fa {len} bytes, límit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} línia {line}, columna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget pressupost de memòria +@msg call depth profunditat de crides +@msg run(input, params) returned no output object run(input, params) no ha retornat cap objecte de sortida +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" necessita `script`: el nom del fitxer .js del complement, al costat del manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` ha de ser el nom d’un fitxer .js a la carpeta del manifest: 1-128 bytes, sense carpeta, sense `:`, sense començar per `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` és el text de l’script i només es dona en el JSON que pren el dataBase64 de plugin.install: un fitxer .vcplugin anomena el seu script a `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" el manifest d’un complement de JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" és per a un filtre d’objectes (`kind` "filter"), no per a `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un complement de JavaScript no pot incloure el permís `{name}`: dels permisos de l’amfitrió pot incloure `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in el manifest d’un mòdul WebAssembly omet `runtime`: "js" és per a un complement de JavaScript +@msg a JavaScript plug-in makes no command calls un complement de JavaScript no crida ordres +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) pren dos nombres +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) pren un nivell, 0 (error), 1 (avís), 2 (informació) o 3 (depuració), i una cadena @msg the plug-in's grant can't be removed from the plug-in store el permís del complement no es pot treure del magatzem de complements @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permís `{shown}` està reservat per a una API de complements posterior; aquest amfitrió no el concedeix @msg unknown permission `{shown}` permís desconegut `{shown}` @@ -9049,6 +9075,11 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Fold Angle Angle de plegat + Set Fold Angle… Defineix l’angle de plegat… + Set Fold Angle Defineix l’angle de plegat + Reset Fold Angle Restableix l’angle de plegat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada Check Comprova Check Fold Lines Comprova les línies de plegat @msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2433a0b12e..8d823d08a4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -669,6 +669,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft obecný CMYK (podobný SWOP) + VectorCraft Coated CMYK (FOGRA51) VectorCraft natíraný CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nenatíraný CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Starší Macintosh RGB (gama 1,8) Internet Standard RGB (sRGB) Standardní internetové RGB (sRGB) Monitor RGB RGB monitoru @@ -5254,6 +5256,14 @@ imageTrace Outline Obrys The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. Allow Once Povolit jednou Always Allow This Script Vždy povolit tento skript + No script has kept file access. Žádný skript nemá uložený přístup k souborům. + Read file Čtení souboru + Read and write file Čtení a zápis souboru + Read and write folder Čtení a zápis složky + Revoke Odvolat + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odvolat odebere přístup uložený pro každou verzi skriptu. Přístup ke složce zahrnuje vše, co obsahuje. +@msg Script file access revoked Přístup skriptu k souborům byl odvolán +@msg The script file access was already revoked Přístup skriptu k souborům už byl odvolán Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat @@ -5428,6 +5438,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop @msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte @msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg the script file permissions could not be read: {e} oprávnění skriptů k souborům nelze přečíst: {e} @msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou @msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice @msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány @@ -7581,6 +7592,21 @@ axis Y Axis osa Y @msg time budget časový rozpočet @msg memory budget (the selection is too large to hand over) rozpočet paměti (výběr je příliš velký na předání) @msg output size ({what} is {len} bytes, limit {max}) velikost výstupu ({what} má {len} bajtů, limit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} řádek {line}, sloupec {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget rozpočet paměti +@msg call depth hloubka volání +@msg run(input, params) returned no output object run(input, params) nevrátila žádný výstupní objekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" vyžaduje `script`: název souboru .js zásuvného modulu vedle manifestu +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` musí být název souboru .js ve složce manifestu: 1-128 bajtů, bez složky, bez `:`, nesmí začínat `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` je text skriptu a uvádí se jen v JSON, které přijímá dataBase64 příkazu plugin.install: soubor .vcplugin uvádí svůj skript v `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest zásuvného modulu v JavaScriptu uvádí `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" je pro filtr objektů (`kind` "filter"), ne pro `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` zásuvný modul v JavaScriptu nemůže uvést oprávnění `{name}`: z oprávnění hostitele smí uvést `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest modulu WebAssembly vynechává `runtime`: "js" je pro zásuvný modul v JavaScriptu +@msg a JavaScript plug-in makes no command calls zásuvný modul v JavaScriptu nevolá žádné příkazy +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) přijímá dvě čísla +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) přijímá úroveň, 0 (chyba), 1 (varování), 2 (informace) nebo 3 (ladění), a řetězec @msg the plug-in's grant can't be removed from the plug-in store oprávnění zásuvného modulu nelze odebrat z úložiště zásuvných modulů @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it oprávnění `{shown}` je vyhrazeno pro pozdější API zásuvných modulů; tento hostitel ho neuděluje @msg unknown permission `{shown}` neznámé oprávnění `{shown}` @@ -10832,6 +10858,11 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Fold Angle Úhel skladu + Set Fold Angle… Nastavit úhel skladu… + Set Fold Angle Nastavit úhel skladu + Reset Fold Angle Obnovit úhel skladu +@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Místo popisku zobrazí kartu s tím, co dělá nástroj z panelu a co dělají jeho klávesy; vyžaduje Zobrazovat popisky nástrojů. Selects whole objects and groups to move, resize or rotate them. Vybírá celé objekty a skupiny, abyste je mohli přesunout, změnit jejich velikost nebo je otočit. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4fbda43ec7..2affee0aff 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -100,6 +100,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop @msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis @msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg the script file permissions could not be read: {e} scriptets filtilladelser kunne ikke læses: {e} @msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang @msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang @msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt @@ -761,6 +762,21 @@ liquify-list-end {0}, {1} {0} og {1} @msg time budget tidsbudget @msg memory budget (the selection is too large to hand over) hukommelsesbudget (markeringen er for stor til at blive overdraget) @msg output size ({what} is {len} bytes, limit {max}) outputstørrelse ({what} fylder {len} byte, grænse {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} linje {line}, kolonne {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget hukommelsesbudget +@msg call depth kaldedybde +@msg run(input, params) returned no output object run(input, params) returnerede intet outputobjekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" kræver `script`: navnet på plug-in'ets .js-fil ved siden af manifestet +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` skal være navnet på en .js-fil i manifestets mappe: 1-128 byte, ingen mappe, intet `:`, må ikke starte med `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` er scriptets tekst og angives kun i den JSON, som dataBase64 i plugin.install tager: en .vcplugin-fil navngiver sit script i `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" et JavaScript-plug-ins manifest angiver `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" er til et objektfilter (`kind` "filter"), ikke `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` et JavaScript-plug-in kan ikke angive tilladelsen `{name}`: af værtens tilladelser må det angive `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in et WebAssembly-moduls manifest udelader `runtime`: "js" er til et JavaScript-plug-in +@msg a JavaScript plug-in makes no command calls et JavaScript-plug-in kalder ingen kommandoer +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) tager to tal +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) tager et niveau, 0 (fejl), 1 (advarsel), 2 (information) eller 3 (fejlsøgning), og en streng @msg the plug-in's grant can't be removed from the plug-in store plug-in'ets tilladelse kan ikke fjernes fra plug-in-lageret @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it tilladelsen `{shown}` er reserveret til et senere plug-in-API; denne vært tildeler den ikke @msg unknown permission `{shown}` ukendt tilladelse `{shown}` @@ -3441,6 +3457,8 @@ liquify-list-end {0}, {1} {0} og {1} RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraft-generisk CMYK (SWOP-lignende) + VectorCraft Coated CMYK (FOGRA51) VectorCraft bestrøget CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft ubestrøget CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Ældre Macintosh RGB (gamma 1,8) Internet Standard RGB (sRGB) Internetstandard-RGB (sRGB) Monitor RGB Skærm-RGB @@ -7743,6 +7761,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. Allow Once Tillad én gang Always Allow This Script Tillad altid dette script + No script has kept file access. Intet script har gemt adgang til filer. + Read file Læs fil + Read and write file Læs og skriv fil + Read and write folder Læs og skriv mappe + Revoke Tilbagekald + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Tilbagekald fjerner den adgang, der er gemt for hver version af scriptet. Adgang til en mappe omfatter alt i den. +@msg Script file access revoked Scriptets adgang til filer er tilbagekaldt +@msg The script file access was already revoked Scriptets adgang til filer var allerede tilbagekaldt Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen @@ -10920,6 +10946,11 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Fold Angle Foldevinkel + Set Fold Angle… Angiv foldevinkel… + Set Fold Angle Angiv foldevinkel + Reset Fold Angle Nulstil foldevinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult Check Kontrollér Check Fold Lines Kontrollér foldelinjer @msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7d788abf48..d970f5a1e4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4842,6 +4842,14 @@ theme Appearance Erscheinungsbild The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. Allow Once Einmal erlauben Always Allow This Script Dieses Skript immer erlauben + No script has kept file access. Kein Skript hat einen gespeicherten Dateizugriff. + Read file Datei lesen + Read and write file Datei lesen und schreiben + Read and write folder Ordner lesen und schreiben + Revoke Widerrufen + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. „Widerrufen“ entfernt den Zugriff, der für jede Version des Skripts gespeichert ist. Der Zugriff auf einen Ordner umfasst seinen gesamten Inhalt. +@msg Script file access revoked Dateizugriff des Skripts widerrufen +@msg The script file access was already revoked Der Dateizugriff des Skripts wurde bereits widerrufen Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen @@ -5007,6 +5015,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop @msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab @msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg the script file permissions could not be read: {e} die Dateiberechtigungen der Skripte konnten nicht gelesen werden: {e} @msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden @msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben @msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen @@ -7164,6 +7173,21 @@ axis Y Axis Y-Achse @msg time budget Zeitbudget @msg memory budget (the selection is too large to hand over) Speicherbudget (die Auswahl ist zu groß zum Übergeben) @msg output size ({what} is {len} bytes, limit {max}) Ausgabegröße ({what} ist {len} Byte groß, Grenze {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} Zeile {line}, Spalte {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget Speicherbudget +@msg call depth Aufruftiefe +@msg run(input, params) returned no output object run(input, params) hat kein Ausgabeobjekt zurückgegeben +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" braucht `script`: den Namen der .js-Datei des Plug-ins neben dem Manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` muss der Name einer .js-Datei im Ordner des Manifests sein: 1-128 Byte, kein Ordner, kein `:`, nicht mit `.` beginnend +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` ist der Text des Skripts und steht nur in dem JSON, das dataBase64 von plugin.install übernimmt: eine .vcplugin-Datei nennt ihr Skript in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" das Manifest eines JavaScript-Plug-ins gibt `runtime` "js" an +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" gilt für einen Objektfilter (`kind` "filter"), nicht für `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ein JavaScript-Plug-in kann die Berechtigung `{name}` nicht aufführen: von den Berechtigungen des Hosts darf es `progress` aufführen +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in das Manifest eines WebAssembly-Moduls lässt `runtime` weg: "js" gilt für ein JavaScript-Plug-in +@msg a JavaScript plug-in makes no command calls ein JavaScript-Plug-in ruft keine Befehle auf +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) nimmt zwei Zahlen +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) nimmt eine Stufe, 0 (Fehler), 1 (Warnung), 2 (Information) oder 3 (Debug), und eine Zeichenfolge @msg the plug-in's grant can't be removed from the plug-in store die Berechtigung des Plug-ins kann nicht aus dem Plug-in-Speicher entfernt werden @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it die Berechtigung `{shown}` ist für eine spätere Plug-in-API reserviert; dieser Host gewährt sie nicht @msg unknown permission `{shown}` unbekannte Berechtigung `{shown}` @@ -10474,6 +10498,11 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Fold Angle Faltwinkel + Set Fold Angle… Faltwinkel festlegen… + Set Fold Angle Faltwinkel festlegen + Reset Fold Angle Faltwinkel zurücksetzen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zeigt statt des Tooltips eine Karte, was ein Werkzeug der Werkzeugleiste und seine Tasten tun; erfordert Tooltips anzeigen. Selects whole objects and groups to move, resize or rotate them. Wählt ganze Objekte und Gruppen aus, um sie zu verschieben, zu skalieren oder zu drehen. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2e7c180df4..30203ad7c3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2639,6 +2639,14 @@ axis Both Και τα δύο The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. Allow Once Να επιτραπεί μία φορά Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + No script has kept file access. Κανένα σενάριο δεν έχει αποθηκευμένη πρόσβαση σε αρχεία. + Read file Ανάγνωση αρχείου + Read and write file Ανάγνωση και εγγραφή αρχείου + Read and write folder Ανάγνωση και εγγραφή φακέλου + Revoke Ανάκληση + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Η ανάκληση αφαιρεί την πρόσβαση που έχει αποθηκευτεί για κάθε έκδοση του σεναρίου. Η πρόσβαση σε φάκελο καλύπτει όλο το περιεχόμενό του. +@msg Script file access revoked Η πρόσβαση του σεναρίου σε αρχεία ανακλήθηκε +@msg The script file access was already revoked Η πρόσβαση του σεναρίου σε αρχεία είχε ήδη ανακληθεί Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση @@ -2837,6 +2845,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop @msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε @msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg the script file permissions could not be read: {e} δεν ήταν δυνατή η ανάγνωση των αδειών αρχείων των σεναρίων: {e} @msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά @msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία @msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν @@ -6625,6 +6634,8 @@ arrowhead Feather Φτερό VectorCraft Default Προεπιλογή VectorCraft VectorCraft Defaults Προεπιλογές VectorCraft VectorCraft Generic CMYK (SWOP-like) Γενικό CMYK του VectorCraft (τύπου SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK επιχρισμένου χαρτιού του VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK μη επιχρισμένου χαρτιού του VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Δείγματα χρωμάτων VectorCraft (.vcswatches) Vertical Align Κατακόρυφη στοίχιση Vertical Area Type Κατακόρυφο κείμενο περιοχής @@ -7571,6 +7582,21 @@ axis Y Axis Άξονας Y @msg time budget χρονικός προϋπολογισμός @msg memory budget (the selection is too large to hand over) προϋπολογισμός μνήμης (η επιλογή είναι πολύ μεγάλη για να παραδοθεί) @msg output size ({what} is {len} bytes, limit {max}) μέγεθος εξόδου ({what}: {len} byte, όριο {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} γραμμή {line}, στήλη {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget προϋπολογισμός μνήμης +@msg call depth βάθος κλήσεων +@msg run(input, params) returned no output object η run(input, params) δεν επέστρεψε αντικείμενο εξόδου +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest το `runtime` "js" χρειάζεται `script`: το όνομα του αρχείου .js του προσθέτου, δίπλα στο αρχείο δηλώσεων +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` το `script` πρέπει να είναι το όνομα ενός αρχείου .js στον φάκελο του αρχείου δηλώσεων: 1-128 byte, χωρίς φάκελο, χωρίς `:`, χωρίς να αρχίζει με `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` το `source` είναι το κείμενο του σεναρίου και δίνεται μόνο στο JSON που δέχεται το dataBase64 της plugin.install: ένα αρχείο .vcplugin ονομάζει το σενάριό του στο `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" το αρχείο δηλώσεων ενός προσθέτου JavaScript δίνει `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" το `runtime` "js" είναι για φίλτρο αντικειμένων (`kind` "filter"), όχι για `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ένα πρόσθετο JavaScript δεν μπορεί να δηλώσει την άδεια `{name}`: από τις άδειες του κεντρικού υπολογιστή μπορεί να δηλώσει την `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in το αρχείο δηλώσεων μιας μονάδας WebAssembly παραλείπει το `runtime`: το "js" είναι για πρόσθετο JavaScript +@msg a JavaScript plug-in makes no command calls ένα πρόσθετο JavaScript δεν καλεί εντολές +@msg vc.progress(done, total) takes two numbers η vc.progress(done, total) δέχεται δύο αριθμούς +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string η vc.log(level, text) δέχεται ένα επίπεδο, 0 (σφάλμα), 1 (προειδοποίηση), 2 (πληροφορία) ή 3 (εντοπισμός σφαλμάτων), και μια συμβολοσειρά @msg the plug-in's grant can't be removed from the plug-in store η άδεια του πρόσθετου δεν μπορεί να αφαιρεθεί από τον χώρο αποθήκευσης πρόσθετων @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it το δικαίωμα `{shown}` είναι δεσμευμένο για μεταγενέστερο API προσθέτων· αυτός ο κεντρικός υπολογιστής δεν το παραχωρεί @msg unknown permission `{shown}` άγνωστο δικαίωμα `{shown}` @@ -9022,6 +9048,11 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Fold Angle Γωνία δίπλωσης + Set Fold Angle… Ορισμός γωνίας δίπλωσης… + Set Fold Angle Ορισμός γωνίας δίπλωσης + Reset Fold Angle Επαναφορά γωνίας δίπλωσης +@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή Check Έλεγχος Check Fold Lines Έλεγχος γραμμών δίπλωσης @msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 37eea18b4c..fccfda5b27 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4918,6 +4918,14 @@ axis Both Ambos The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. Allow Once Permitir una vez Always Allow This Script Permitir siempre este script + No script has kept file access. Ningún script tiene acceso a archivos guardado. + Read file Leer archivo + Read and write file Leer y escribir archivo + Read and write folder Leer y escribir carpeta + Revoke Revocar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revocar quita el acceso guardado para cada versión del script. El acceso a una carpeta abarca todo su contenido. +@msg Script file access revoked Acceso del script a archivos revocado +@msg The script file access was already revoked El acceso del script a archivos ya estaba revocado Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia @@ -5115,6 +5123,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop @msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue @msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg the script file permissions could not be read: {e} no se pudieron leer los permisos de archivos de los scripts: {e} @msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez @msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron @@ -6795,6 +6804,8 @@ mark-style Japanese Japonesas Variation Variación VectorCraft Default Predeterminado de VectorCraft VectorCraft Generic CMYK (SWOP-like) CMYK genérico de VectorCraft (similar a SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK estucado de VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucado de VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Muestras de VectorCraft (.vcswatches) Vertical Area Type Texto de área vertical Vertical Type Texto vertical @@ -7557,6 +7568,21 @@ axis Y Axis Eje Y @msg time budget presupuesto de tiempo @msg memory budget (the selection is too large to hand over) presupuesto de memoria (la selección es demasiado grande para entregarla) @msg output size ({what} is {len} bytes, limit {max}) tamaño de salida ({what} ocupa {len} bytes, límite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} línea {line}, columna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget presupuesto de memoria +@msg call depth profundidad de llamadas +@msg run(input, params) returned no output object run(input, params) no devolvió ningún objeto de salida +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" necesita `script`: el nombre del archivo .js del plugin, junto al manifiesto +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` debe ser el nombre de un archivo .js en la carpeta del manifiesto: 1-128 bytes, sin carpeta, sin `:`, sin empezar por `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` es el texto del script y solo se da en el JSON que toma el dataBase64 de plugin.install: un archivo .vcplugin nombra su script en `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" el manifiesto de un plugin de JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" es para un filtro de objetos (`kind` "filter"), no para `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plugin de JavaScript no puede incluir el permiso `{name}`: de los permisos del host puede incluir `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in el manifiesto de un módulo WebAssembly omite `runtime`: "js" es para un plugin de JavaScript +@msg a JavaScript plug-in makes no command calls un plugin de JavaScript no llama a comandos +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) recibe dos números +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) recibe un nivel, 0 (error), 1 (advertencia), 2 (información) o 3 (depuración), y una cadena @msg the plug-in's grant can't be removed from the plug-in store el permiso del plugin no se puede quitar del almacén de plugins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permiso `{shown}` está reservado para una API de plugins posterior; este host no lo concede @msg unknown permission `{shown}` permiso desconocido `{shown}` @@ -10766,6 +10792,11 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Fold Angle Ángulo de plegado + Set Fold Angle… Definir ángulo de plegado… + Set Fold Angle Definir ángulo de plegado + Reset Fold Angle Restablecer ángulo de plegado +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta Check Comprobar Check Fold Lines Comprobar líneas de plegado @msg No cut lines are in the selection. No hay líneas de corte en la selección. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c95d681244..41f455edbd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -663,6 +663,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) VectorCraftin yleinen CMYK (SWOP-tyyppinen) + VectorCraft Coated CMYK (FOGRA51) VectorCraftin päällystetty CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraftin päällystämätön CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Vanha Macintosh RGB (gamma 1.8) Internet Standard RGB (sRGB) Internetin standardi-RGB (sRGB) Monitor RGB Näytön RGB @@ -5159,6 +5161,14 @@ imageTrace Outline Ääriviiva The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. Allow Once Salli kerran Always Allow This Script Salli tämä komentosarja aina + No script has kept file access. Millään komentosarjalla ei ole tallennettua tiedostojen käyttöoikeutta. + Read file Tiedoston luku + Read and write file Tiedoston luku ja kirjoitus + Read and write folder Kansion luku ja kirjoitus + Revoke Peruuta oikeus + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Peruuta oikeus poistaa käyttöoikeuden, joka on tallennettu komentosarjan jokaiselle versiolle. Kansion käyttöoikeus kattaa kaiken sen sisällön. +@msg Script file access revoked Komentosarjan tiedostojen käyttöoikeus peruttu +@msg The script file access was already revoked Komentosarjan tiedostojen käyttöoikeus oli jo peruttu Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen @@ -5356,6 +5366,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop @msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä @msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg the script file permissions could not be read: {e} komentosarjojen tiedostolupia ei voitu lukea: {e} @msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran @msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön @msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois @@ -7648,6 +7659,21 @@ axis Y Axis Y-akseli @msg time budget aikabudjetti @msg memory budget (the selection is too large to hand over) muistibudjetti (valinta on liian suuri luovutettavaksi) @msg output size ({what} is {len} bytes, limit {max}) tulosteen koko ({what}: {len} tavua, raja {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} rivi {line}, sarake {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget muistibudjetti +@msg call depth kutsusyvyys +@msg run(input, params) returned no output object run(input, params) ei palauttanut tulosobjektia +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" tarvitsee avaimen `script`: laajennuksen .js-tiedoston nimen manifestin vieressä +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` on oltava manifestin kansiossa olevan .js-tiedoston nimi: 1-128 tavua, ei kansiota, ei merkkiä `:`, ei alussa merkkiä `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` on komentosarjan teksti, ja se annetaan vain JSONissa, jonka plugin.install-komennon dataBase64 ottaa: .vcplugin-tiedosto nimeää komentosarjansa avaimessa `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript-laajennuksen manifesti antaa `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" on objektisuodattimelle (`kind` "filter"), ei arvolle `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript-laajennus ei voi luetella lupaa `{name}`: isännän luvista se voi luetella luvan `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly-moduulin manifesti jättää avaimen `runtime` pois: "js" on JavaScript-laajennukselle +@msg a JavaScript plug-in makes no command calls JavaScript-laajennus ei kutsu komentoja +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) ottaa kaksi lukua +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) ottaa tason, 0 (virhe), 1 (varoitus), 2 (tieto) tai 3 (virheenjäljitys), ja merkkijonon @msg the plug-in's grant can't be removed from the plug-in store laajennuksen käyttöoikeutta ei voi poistaa laajennusvarastosta @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it käyttöoikeus `{shown}` on varattu myöhemmälle laajennus-API:lle; tämä isäntä ei myönnä sitä @msg unknown permission `{shown}` tuntematon käyttöoikeus `{shown}` @@ -9105,6 +9131,11 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Fold Angle Taittokulma + Set Fold Angle… Aseta taittokulma… + Set Fold Angle Aseta taittokulma + Reset Fold Angle Palauta taittokulma +@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu Check Tarkista Check Fold Lines Tarkista taittoviivat @msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index efab0b71ea..6d7488c935 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4900,6 +4900,14 @@ axis Both Les deux The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. Allow Once Autoriser une fois Always Allow This Script Toujours autoriser ce script + No script has kept file access. Aucun script n’a conservé d’accès aux fichiers. + Read file Lire le fichier + Read and write file Lire et écrire le fichier + Read and write folder Lire et écrire le dossier + Revoke Révoquer + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Révoquer supprime l’accès conservé pour chaque version du script. L’accès à un dossier couvre tout son contenu. +@msg Script file access revoked Accès du script aux fichiers révoqué +@msg The script file access was already revoked L’accès du script aux fichiers était déjà révoqué Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement @@ -5074,6 +5082,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop @msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez @msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg the script file permissions could not be read: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être lues : {e} @msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois @msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @@ -6906,6 +6915,8 @@ arrowhead Feather Empennage VectorCraft Default VectorCraft par défaut VectorCraft Defaults Valeurs par défaut de VectorCraft VectorCraft Generic CMYK (SWOP-like) CMJN générique VectorCraft (de type SWOP) + VectorCraft Coated CMYK (FOGRA51) CMJN couché VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMJN non couché VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Nuances VectorCraft (.vcswatches) Vertical Align Alignement vertical Vertical Area Type Texte captif vertical @@ -7578,6 +7589,21 @@ axis Y Axis Axe Y @msg time budget budget de temps @msg memory budget (the selection is too large to hand over) budget mémoire (la sélection est trop grande pour être transmise) @msg output size ({what} is {len} bytes, limit {max}) taille de sortie ({what} fait {len} octets, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} ligne {line}, colonne {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budget mémoire +@msg call depth profondeur d’appel +@msg run(input, params) returned no output object run(input, params) n’a renvoyé aucun objet de sortie +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" a besoin de `script`, le nom du fichier .js du plug-in placé à côté du manifeste +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` doit être le nom d’un fichier .js dans le dossier du manifeste (1-128 octets, sans dossier, sans `:`, ne commençant pas par `.`) +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` est le texte du script, donné uniquement dans le JSON que prend le dataBase64 de plugin.install, et un fichier .vcplugin nomme son script dans `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" le manifeste d’un plug-in JavaScript indique `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" est réservé à un filtre d’objets (`kind` "filter"), pas à `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plug-in JavaScript ne peut pas lister l’autorisation `{name}`, et parmi les autorisations de l’hôte, il peut lister `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in le manifeste d’un module WebAssembly omet `runtime`, car "js" est réservé à un plug-in JavaScript +@msg a JavaScript plug-in makes no command calls un plug-in JavaScript n’appelle aucune commande +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) prend deux nombres +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) prend un niveau, 0 (erreur), 1 (avertissement), 2 (information) ou 3 (débogage), et une chaîne @msg the plug-in's grant can't be removed from the plug-in store l’autorisation du plug-in ne peut pas être retirée du magasin de plug-ins @msg unknown permission `{shown}` autorisation inconnue `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants « {name} » demande les autorisations {asked} : une personne doit les approuver dans l’application de bureau, ou passez `grant` dans une session démarrée avec --allow-plugin-grants @@ -10827,6 +10853,11 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Fold Angle Angle de pliage + Set Fold Angle… Définir l’angle de pliage… + Set Fold Angle Définir l’angle de pliage + Reset Fold Angle Réinitialiser l’angle de pliage +@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée Tap Appui bref Clear Hold Effacer le maintien Hold Shortcuts Raccourcis de maintien diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index fb9295675a..aa4bc4b193 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3999,6 +3999,15 @@ arrowhead Feather પીંછું Show East Asian Options પૂર્વ એશિયન વિકલ્પો બતાવો Show Edges કિનારીઓ બતાવો Show External Script Warning બાહ્ય સ્ક્રિપ્ટ ચેતવણી બતાવો + Script File Access સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ + No script has kept file access. કોઈ સ્ક્રિપ્ટ પાસે સાચવેલ ફાઇલ ઍક્સેસ નથી. + Read file ફાઇલ વાંચો + Read and write file ફાઇલ વાંચો અને લખો + Read and write folder ફોલ્ડર વાંચો અને લખો + Revoke પરવાનગી પાછી ખેંચો + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. પરવાનગી પાછી ખેંચવાથી સ્ક્રિપ્ટના દરેક સંસ્કરણ માટે સાચવેલ ઍક્સેસ દૂર થાય છે. ફોલ્ડરની ઍક્સેસમાં તેની અંદરનું બધું આવે છે. +@msg Script file access revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પાછી ખેંચી +@msg The script file access was already revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પહેલેથી પાછી ખેંચાઈ હતી Show Find Field શોધ ફીલ્ડ બતાવો Show Font Height Options ફોન્ટ ઊંચાઈ વિકલ્પો બતાવો Show Font Names in English ફોન્ટ નામો અંગ્રેજીમાં બતાવો @@ -5666,6 +5675,11 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Fold Angle ફોલ્ડ ખૂણો + Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો… + Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો + Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો +@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય Check ચેક કરો Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો @msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 082e4c8e03..88c591d896 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6399,6 +6399,8 @@ arrowhead Feather पंख VectorCraft didn't quit normally last time. These documents had unsaved changes: पिछली बार VectorCraft सामान्य तरीके से बंद नहीं हुआ था। इन डॉक्यूमेंट्स में बिना सेव किए बदलाव थे: VectorCraft documents: one locked object, updated when the file changes. VectorCraft डॉक्यूमेंट्स: एक लॉक्ड ऑब्जेक्ट, जो फ़ाइल बदलने पर अपडेट होता है। VectorCraft Generic CMYK (SWOP-like) वेक्टर क्रेफ्ट जेनेरिक CMYK (SWOP-like) + VectorCraft Coated CMYK (FOGRA51) वेक्टर क्रेफ्ट कोटेड CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) वेक्टर क्रेफ्ट अनकोटेड CMYK (FOGRA52) VectorCraft Help… VectorCraft मदद… VectorCraft on getartcraft.com getartcraft.com पर VectorCraft VectorCraft on GitHub GitHub पर VectorCraft @@ -7636,6 +7638,14 @@ arrowhead Feather पंख The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। Allow Once एक बार अनुमति दें Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + No script has kept file access. किसी भी स्क्रिप्ट के पास रखी गई फ़ाइल पहुँच नहीं है। + Read file फ़ाइल पढ़ें + Read and write file फ़ाइल पढ़ें और लिखें + Read and write folder फ़ोल्डर पढ़ें और लिखें + Revoke वापस लें + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. वापस लें स्क्रिप्ट के हर संस्करण के लिए रखी गई पहुँच हटा देता है। किसी फ़ोल्डर की पहुँच में उसके भीतर का सब कुछ शामिल है। +@msg Script file access revoked स्क्रिप्ट की फ़ाइल पहुँच वापस ली गई +@msg The script file access was already revoked स्क्रिप्ट की फ़ाइल पहुँच पहले ही वापस ली जा चुकी थी Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ @@ -7834,6 +7844,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें @msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} +@msg the script file permissions could not be read: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ पढ़ी नहीं जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं @@ -8813,6 +8824,21 @@ liquify-list-end {0}, {1} {0} और {1} @msg outlineText {v}: true or false outlineText {v}: true या false @msg output intent profile: {e} उत्पादन आशय प्रोफ़ाइल: {e} @msg output size ({what} is {len} bytes, limit {max}) आउटपुट का आकार ({what} {len} बाइट्स का है, सीमा {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} पंक्ति {line}, स्तंभ {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget स्मृति बजट +@msg call depth कॉल गहराई +@msg run(input, params) returned no output object run(input, params) ने कोई आउटपुट ऑब्जेक्ट नहीं लौटाया +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" को `script` चाहिए: मैनिफ़ेस्ट के पास प्लग-इन की .js फ़ाइल का नाम +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` मैनिफ़ेस्ट के फ़ोल्डर में किसी .js फ़ाइल का नाम होना चाहिए: 1-128 बाइट्स, कोई फ़ोल्डर नहीं, कोई `:` नहीं, `.` से शुरू नहीं +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` स्क्रिप्ट का टेक्स्ट है, जो केवल उस JSON में दिया जाता है जिसे plugin.install का dataBase64 लेता है: .vcplugin फ़ाइल अपनी स्क्रिप्ट का नाम `script` में देती है +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript प्लग-इन का मैनिफ़ेस्ट `runtime` "js" देता है +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" ऑब्जेक्ट फ़िल्टर (`kind` "filter") के लिए है, `kind` "{kind}" के लिए नहीं +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript प्लग-इन अनुमति `{name}` सूचीबद्ध नहीं कर सकता: होस्ट की अनुमतियों में से वह `progress` सूचीबद्ध कर सकता है +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly मॉड्यूल का मैनिफ़ेस्ट `runtime` छोड़ देता है: "js" JavaScript प्लग-इन के लिए है +@msg a JavaScript plug-in makes no command calls JavaScript प्लग-इन कोई कमांड कॉल नहीं करता +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) दो संख्याएँ लेता है +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) एक स्तर, 0 (त्रुटि), 1 (चेतावनी), 2 (जानकारी) या 3 (डीबग), और एक स्ट्रिंग लेता है @msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है @msg output.destination: {e} output.destination: {e} @msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: "{name}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है @@ -10450,6 +10476,11 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Fold Angle फ़ोल्ड कोण + Set Fold Angle… फ़ोल्ड कोण सेट करें… + Set Fold Angle फ़ोल्ड कोण सेट करें + Reset Fold Angle फ़ोल्ड कोण रीसेट करें +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. टूलबार का टूल और उसकी कुंजियाँ क्या करती हैं, यह टिप की जगह एक कार्ड में दिखाता है; इसके लिए टूल युक्तियाँ दिखाएँ चालू होना चाहिए। Selects whole objects and groups to move, resize or rotate them. पूरे ऑब्जेक्ट और समूह चुनता है, ताकि उन्हें खिसकाया, आकार बदला या घुमाया जा सके। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 669e5723c9..382e093bc0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5344,6 +5344,8 @@ mark-style Japanese Japán VectorCraft didn't quit normally last time. These documents had unsaved changes: A VectorCraft legutóbb nem szabályosan lépett ki. Ezekben a dokumentumokban mentetlen módosítások voltak: VectorCraft documents: one locked object, updated when the file changes. VectorCraft-dokumentumok: egyetlen zárolt objektum, amely a fájl változásakor frissül. VectorCraft Generic CMYK (SWOP-like) VectorCraft általános CMYK (SWOP-szerű) + VectorCraft Coated CMYK (FOGRA51) VectorCraft mázolt CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft mázolatlan CMYK (FOGRA52) VectorCraft Help… VectorCraft súgó… VectorCraft on getartcraft.com A VectorCraft a getartcraft.com oldalon VectorCraft on GitHub A VectorCraft a GitHubon @@ -5774,6 +5776,14 @@ imageTrace Outline Körvonal The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. Allow Once Engedélyezés egyszer Always Allow This Script A parancsfájl engedélyezése mindig + No script has kept file access. Egy parancsfájlnak sincs megőrzött fájlhozzáférése. + Read file Fájl olvasása + Read and write file Fájl olvasása és írása + Read and write folder Mappa olvasása és írása + Revoke Engedély visszavonása + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Az Engedély visszavonása a parancsfájl minden verziójához megőrzött hozzáférést eltávolítja. Egy mappához való hozzáférés a teljes tartalmára kiterjed. +@msg Script file access revoked A parancsfájl fájlhozzáférése visszavonva +@msg The script file access was already revoked A parancsfájl fájlhozzáférése már vissza volt vonva Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés @@ -5949,6 +5959,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop @msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el @msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg the script file permissions could not be read: {e} a parancsfájlok fájlengedélyeit nem sikerült beolvasni: {e} @msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető @msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti @msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak @@ -7566,6 +7577,21 @@ axis Y Axis Y tengely @msg time budget időkeret @msg memory budget (the selection is too large to hand over) memóriakeret (a kijelölés túl nagy az átadáshoz) @msg output size ({what} is {len} bytes, limit {max}) kimenet mérete ({what}: {len} bájt, korlát {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, {line}. sor, {column}. oszlop) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget memóriakeret +@msg call depth hívási mélység +@msg run(input, params) returned no output object a run(input, params) nem adott vissza kimeneti objektumot +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest a `runtime` "js" értékhez `script` kell: a bővítmény .js fájljának neve a leíró mellett +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` a `script` a leíró mappájában lévő .js fájl neve legyen: 1-128 bájt, mappa nélkül, `:` nélkül, és nem kezdődhet `.` karakterrel +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` a `source` a parancsfájl szövege, és csak abban a JSON-ban adható meg, amelyet a plugin.install dataBase64 paramétere fogad: a .vcplugin fájl a `script` kulcsban nevezi meg a parancsfájlját +@msg a JavaScript plug-in's manifest gives `runtime` "js" egy JavaScript-bővítmény leírója `runtime` "js" értéket ad meg +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" a `runtime` "js" objektumszűrőhöz való (`kind` "filter"), nem `kind` "{kind}" értékhez +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` egy JavaScript-bővítmény nem sorolhatja fel a(z) `{name}` engedélyt: a gazdagép engedélyei közül a `progress` engedélyt sorolhatja fel +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in egy WebAssembly-modul leírója elhagyja a `runtime` kulcsot: a "js" JavaScript-bővítményhez való +@msg a JavaScript plug-in makes no command calls egy JavaScript-bővítmény nem hív parancsokat +@msg vc.progress(done, total) takes two numbers a vc.progress(done, total) két számot vár +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string a vc.log(level, text) egy szintet, 0 (hiba), 1 (figyelmeztetés), 2 (információ) vagy 3 (hibakeresés), és egy karakterláncot vár @msg the plug-in's grant can't be removed from the plug-in store a bővítmény engedélye nem távolítható el a bővítménytárból @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a(z) `{shown}` engedély egy későbbi bővítmény-API számára van fenntartva; ez a gazdaprogram nem adja meg @msg unknown permission `{shown}` ismeretlen engedély: `{shown}` @@ -10820,6 +10846,11 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Fold Angle Hajtásszög + Set Fold Angle… Hajtásszög beállítása… + Set Fold Angle Hajtásszög beállítása + Reset Fold Angle Hajtásszög visszaállítása +@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Az elemleírás helyett kártyán mutatja, mit csinál az eszköztár egy eszköze és a billentyűi; ehhez az Elemleírások megjelenítése szükséges. Selects whole objects and groups to move, resize or rotate them. Teljes objektumokat és csoportokat jelöl ki áthelyezéshez, átméretezéshez vagy forgatáshoz. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 725ef12327..65e680716e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -643,6 +643,21 @@ @msg time budget anggaran waktu @msg memory budget (the selection is too large to hand over) anggaran memori (seleksi terlalu besar untuk diserahkan) @msg output size ({what} is {len} bytes, limit {max}) ukuran keluaran ({what} berukuran {len} byte, batas {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} baris {line}, kolom {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget anggaran memori +@msg call depth kedalaman panggilan +@msg run(input, params) returned no output object run(input, params) tidak mengembalikan objek keluaran +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" memerlukan `script`: nama file .js plug-in, di samping manifes +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` harus berupa nama file .js di folder manifes: 1-128 byte, tanpa folder, tanpa `:`, tidak diawali `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` adalah teks skrip dan hanya diberikan dalam JSON yang diterima dataBase64 plugin.install: file .vcplugin menamai skripnya di `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifes plug-in JavaScript memberikan `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" untuk filter objek (`kind` "filter"), bukan `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` plug-in JavaScript tidak dapat mencantumkan izin `{name}`: dari izin host, plug-in ini boleh mencantumkan `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifes modul WebAssembly menghilangkan `runtime`: "js" untuk plug-in JavaScript +@msg a JavaScript plug-in makes no command calls plug-in JavaScript tidak memanggil perintah +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) menerima dua angka +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) menerima level, 0 (kesalahan), 1 (peringatan), 2 (informasi), atau 3 (debug), dan string @msg the plug-in's grant can't be removed from the plug-in store izin yang diberikan kepada plug-in tidak dapat dihapus dari penyimpanan plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it izin `{shown}` dicadangkan untuk API plug-in yang lebih baru; host ini tidak memberikannya @msg unknown permission `{shown}` izin tidak dikenal `{shown}` @@ -1316,6 +1331,8 @@ RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) CMYK generik VectorCraft (mirip SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK kertas berlapis VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK kertas tanpa lapisan VectorCraft (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) RGB Macintosh lama (Gamma 1.8) Internet Standard RGB (sRGB) RGB standar Internet (sRGB) Monitor RGB RGB monitor @@ -5607,6 +5624,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. Allow Once Izinkan Sekali Always Allow This Script Selalu Izinkan Skrip Ini + No script has kept file access. Tidak ada skrip yang memiliki akses berkas tersimpan. + Read file Baca Berkas + Read and write file Baca dan Tulis Berkas + Read and write folder Baca dan Tulis Folder + Revoke Cabut + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Cabut menghapus akses yang disimpan untuk setiap versi skrip. Akses ke folder mencakup semua isinya. +@msg Script file access revoked Akses berkas skrip dicabut +@msg The script file access was already revoked Akses berkas skrip sudah dicabut Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi @@ -8701,6 +8726,11 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Fold Angle Sudut lipat + Set Fold Angle… Atur sudut lipat… + Set Fold Angle Atur sudut lipat + Reset Fold Angle Atur ulang sudut lipat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden pilih garis lekuk, garis potong sebagian, atau garis perforasi yang tidak terkunci dan tidak tersembunyi Check Periksa Check Fold Lines Periksa garis lipat @msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. @@ -8856,6 +8886,7 @@ breakText Glyphs Glif @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` untuk dialog file skrip harus salah satu dari: once, always, deny, stop @msg choose a file or folder first, or deny pilih file atau folder terlebih dahulu, atau tolak @msg the script file permissions could not be saved: {e} izin file skrip tidak dapat disimpan: {e} +@msg the script file permissions could not be read: {e} izin file skrip tidak dapat dibaca: {e} @msg this script's file access can be allowed only once akses file skrip ini hanya dapat diizinkan sekali @msg Only the person at the keyboard can allow a script's file access Hanya orang yang berada di depan keyboard yang dapat mengizinkan akses file skrip @msg A script is given at most 2,048 files: the files picked after them were left out Skrip diberi paling banyak 2.048 file: file yang dipilih sesudahnya dihilangkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d00eb9be50..79c9192735 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4980,6 +4980,14 @@ axis Both Entrambi The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. Allow Once Consenti una volta Always Allow This Script Consenti sempre questo script + No script has kept file access. Nessuno script ha conservato un accesso ai file. + Read file Lettura file + Read and write file Lettura e scrittura file + Read and write folder Lettura e scrittura cartella + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca rimuove l'accesso conservato per ogni versione dello script. L'accesso a una cartella comprende tutto il suo contenuto. +@msg Script file access revoked Accesso dello script ai file revocato +@msg The script file access was already revoked L'accesso dello script ai file era già stato revocato Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso @@ -5145,6 +5153,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop @msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega @msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg the script file permissions could not be read: {e} impossibile leggere i permessi sui file degli script: {e} @msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta @msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script @msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi @@ -7203,6 +7212,21 @@ axis Y Axis Asse Y @msg time budget budget di tempo @msg memory budget (the selection is too large to hand over) budget di memoria (la selezione è troppo grande per essere passata) @msg output size ({what} is {len} bytes, limit {max}) dimensione dell’output ({what} è di {len} byte, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} riga {line}, colonna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budget di memoria +@msg call depth profondità delle chiamate +@msg run(input, params) returned no output object run(input, params) non ha restituito alcun oggetto di output +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" richiede `script`: il nome del file .js del plug-in, accanto al manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` deve essere il nome di un file .js nella cartella del manifest: 1-128 byte, nessuna cartella, nessun `:`, senza iniziare con `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` è il testo dello script, indicato solo nel JSON che riceve il dataBase64 di plugin.install: un file .vcplugin indica il proprio script in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" il manifest di un plug-in JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" è per un filtro di oggetti (`kind` "filter"), non per `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` un plug-in JavaScript non può elencare il permesso `{name}`: dei permessi dell’host può elencare `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in il manifest di un modulo WebAssembly omette `runtime`: "js" è per un plug-in JavaScript +@msg a JavaScript plug-in makes no command calls un plug-in JavaScript non chiama comandi +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) accetta due numeri +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) accetta un livello, 0 (errore), 1 (avviso), 2 (informazione) o 3 (debug), e una stringa @msg the plug-in's grant can't be removed from the plug-in store il permesso del plug-in non può essere rimosso dall’archivio dei plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it l’autorizzazione `{shown}` è riservata a un’API dei plug-in successiva; questo host non la concede @msg unknown permission `{shown}` autorizzazione sconosciuta `{shown}` @@ -10508,6 +10532,11 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Fold Angle Angolo di piega + Set Fold Angle… Imposta angolo di piega… + Set Fold Angle Imposta angolo di piega + Reset Fold Angle Reimposta angolo di piega +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleziona una linea di cordonatura, di taglio parziale o di perforazione che non sia bloccata né nascosta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra una scheda con ciò che fanno uno strumento della barra e i suoi tasti al posto della descrizione; richiede Mostra descrizioni comandi. Selects whole objects and groups to move, resize or rotate them. Seleziona oggetti e gruppi interi per spostarli, ridimensionarli o ruotarli. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8dba701981..b6aba6abbf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5806,6 +5806,14 @@ variable-list-end {0}, {1} {0}、{1} The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 Allow Once 今回のみ許可 Always Allow This Script このスクリプトを常に許可 + No script has kept file access. ファイルアクセスを保持しているスクリプトはありません。 + Read file ファイルの読み取り + Read and write file ファイルの読み取りと書き込み + Read and write folder フォルダーの読み取りと書き込み + Revoke 許可を取り消す + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「許可を取り消す」は、スクリプトのすべてのバージョンに保持されたアクセスを削除します。フォルダーへのアクセスには、その中のすべてが含まれます。 +@msg Script file access revoked スクリプトのファイルアクセスを取り消しました +@msg The script file access was already revoked スクリプトのファイルアクセスはすでに取り消されています Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない @@ -5980,6 +5988,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください @msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください @msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg the script file permissions could not be read: {e} スクリプトのファイル許可を読み込めませんでした: {e} @msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます @msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです @msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました @@ -7278,6 +7287,21 @@ axis Y Axis Y 軸 @msg time budget 時間予算 @msg memory budget (the selection is too large to hand over) メモリ予算 (選択範囲が大きすぎて渡せません) @msg output size ({what} is {len} bytes, limit {max}) 出力サイズ ({what} は {len} バイト、上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}、{script} {line} 行 {column} 列) +@msg {reason} ({id}, {script}) {reason} ({id}、{script}) +@msg memory budget メモリ予算 +@msg call depth 呼び出しの深さ +@msg run(input, params) returned no output object run(input, params) が出力オブジェクトを返しませんでした +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" には `script` が必要です: マニフェストと同じ場所にあるプラグインの .js ファイルの名前 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` はマニフェストのフォルダーにある .js ファイルの名前にしてください: 1-128 バイト、フォルダーなし、`:` なし、`.` で始まらないこと +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` はスクリプトのテキストで、plugin.install の dataBase64 が受け取る JSON でだけ指定します: .vcplugin ファイルはスクリプトを `script` で指定します +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript プラグインのマニフェストは `runtime` "js" を指定します +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" はオブジェクトフィルター (`kind` "filter") 用で、`kind` "{kind}" 用ではありません +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript プラグインは権限 `{name}` を指定できません: ホストの権限のうち指定できるのは `progress` です +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly モジュールのマニフェストでは `runtime` を省略します: "js" は JavaScript プラグイン用です +@msg a JavaScript plug-in makes no command calls JavaScript プラグインはコマンドを呼び出しません +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) には数値を 2 つ指定します +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) にはレベル 0 (エラー)、1 (警告)、2 (情報)、3 (デバッグ) のいずれかと文字列を指定します @msg the plug-in's grant can't be removed from the plug-in store プラグインの許可をプラグインストアから削除できません @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 権限 `{shown}` は今後のプラグイン API 用に予約されています。このホストはこの権限を付与しません @msg unknown permission `{shown}` 不明な権限 `{shown}` @@ -10570,6 +10594,11 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Fold Angle 折り角度 + Set Fold Angle… 折り角度を設定… + Set Fold Angle 折り角度を設定 + Reset Fold Angle 折り角度をリセット +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ロックも非表示もされていない筋入れ線、半抜き線またはミシン目線を選択してください # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ツールバーのツールとそのキーの働きを、ヒントの代わりにカードで表示。ツールヒントを表示がオンのときに使用 Selects whole objects and groups to move, resize or rotate them. オブジェクトやグループ全体を選択して、移動、サイズ変更、回転を行います。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0a29222b28..4b36bf5fd8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8403,6 +8403,8 @@ mark-style Japanese იაპონური Variation ვარიაცია VectorCraft Default VectorCraft-ის ნაგულისხმევი VectorCraft Generic CMYK (SWOP-like) VectorCraft-ის ზოგადი CMYK (SWOP-ის მსგავსი) + VectorCraft Coated CMYK (FOGRA51) VectorCraft-ის ცარციანი ქაღალდის CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft-ის უცარცო ქაღალდის CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft-ის ფერის ნიმუშები (.vcswatches) Vertical Area Type ვერტიკალური არის ტექსტი Vertical Type ვერტიკალური ტექსტი @@ -8484,6 +8486,14 @@ imageTrace Outline კონტური The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. Allow Once ერთხელ დაშვება Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + No script has kept file access. არცერთ სკრიპტს არ აქვს შენახული წვდომა ფაილებზე. + Read file ფაილის წაკითხვა + Read and write file ფაილის წაკითხვა და ჩაწერა + Read and write folder საქაღალდის წაკითხვა და ჩაწერა + Revoke ნებართვის გაუქმება + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. ნებართვის გაუქმება შლის სკრიპტის ყველა ვერსიისთვის შენახულ წვდომას. საქაღალდეზე წვდომა მოიცავს მასში არსებულ ყველაფერს. +@msg Script file access revoked სკრიპტის წვდომა ფაილებზე გაუქმდა +@msg The script file access was already revoked სკრიპტის წვდომა ფაილებზე უკვე გაუქმებული იყო Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება @@ -8650,6 +8660,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop @msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით @msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg the script file permissions could not be read: {e} სკრიპტების ფაილების ნებართვების წაკითხვა ვერ მოხერხდა: {e} @msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას @msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს @msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია @@ -9686,6 +9697,21 @@ axis Y Axis Y ღერძი @msg time budget დროის ბიუჯეტი @msg memory budget (the selection is too large to hand over) მეხსიერების ბიუჯეტი (მონიშნული ზედმეტად დიდია გადასაცემად) @msg output size ({what} is {len} bytes, limit {max}) გამოტანის ზომა ({what}: {len} ბაიტი, ლიმიტი {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, სტრიქონი {line}, სვეტი {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget მეხსიერების ბიუჯეტი +@msg call depth გამოძახების სიღრმე +@msg run(input, params) returned no output object run(input, params)-მა გამოტანის ობიექტი არ დააბრუნა +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" საჭიროებს `script`-ს: პლაგინის .js ფაილის სახელს მანიფესტის გვერდით +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` უნდა იყოს მანიფესტის საქაღალდეში მყოფი .js ფაილის სახელი: 1-128 ბაიტი, საქაღალდის გარეშე, `:` სიმბოლოს გარეშე, `.` სიმბოლოთი არ უნდა იწყებოდეს +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` სკრიპტის ტექსტია და მიეთითება მხოლოდ JSON-ში, რომელსაც plugin.install-ის dataBase64 იღებს: .vcplugin ფაილი თავის სკრიპტს `script` გასაღებში ასახელებს +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript პლაგინის მანიფესტი მიუთითებს `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" ობიექტების ფილტრისთვისაა (`kind` "filter"), არა `kind` "{kind}" მნიშვნელობისთვის +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript პლაგინს არ შეუძლია ნებართვის `{name}` ჩამოთვლა: ჰოსტის ნებართვებიდან მას შეუძლია ჩამოთვალოს `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly მოდულის მანიფესტი გამოტოვებს `runtime` გასაღებს: "js" JavaScript პლაგინისთვისაა +@msg a JavaScript plug-in makes no command calls JavaScript პლაგინი ბრძანებებს არ იძახებს +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) იღებს ორ რიცხვს +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) იღებს დონეს, 0 (შეცდომა), 1 (გაფრთხილება), 2 (ინფორმაცია) ან 3 (გამართვა), და სტრიქონს @msg the plug-in's grant can't be removed from the plug-in store პლაგინის ნებართვის წაშლა პლაგინების საცავიდან შეუძლებელია @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it ნებართვა `{shown}` დაჯავშნილია პლაგინების მომავალი API-სთვის; ეს ჰოსტი მას არ გასცემს @msg unknown permission `{shown}` უცნობი ნებართვა `{shown}` @@ -11149,6 +11175,11 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მარკირებისთვის. Remove Fold Line Role ხაზის ტიპის მოხსნა + Fold Angle მოკეცვის კუთხე + Set Fold Angle… მოკეცვის კუთხის დაყენება… + Set Fold Angle მოკეცვის კუთხის დაყენება + Reset Fold Angle მოკეცვის კუთხის ჩამოყრა +@msg select a crease, partial cut or perforation line that is neither locked nor hidden მონიშნეთ ბიგის, ნაწილობრივი ჭრის ან პერფორაციის ხაზი, რომელიც არც ჩაკეტილია და არც დამალული Check შემოწმება Check Fold Lines მოკეცვის ხაზების შემოწმება @msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 78dc8d7b97..6f796453a7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5735,6 +5735,14 @@ variable-list-end {0}, {1} {0} 및 {1} The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. Allow Once 한 번 허용 Always Allow This Script 이 스크립트 항상 허용 + No script has kept file access. 파일 접근을 유지한 스크립트가 없습니다. + Read file 파일 읽기 + Read and write file 파일 읽기 및 쓰기 + Read and write folder 폴더 읽기 및 쓰기 + Revoke 권한 취소 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 권한 취소는 스크립트의 모든 버전에 유지된 접근을 제거합니다. 폴더 접근에는 폴더 안의 모든 항목이 포함됩니다. +@msg Script file access revoked 스크립트 파일 접근 권한을 취소했습니다 +@msg The script file access was already revoked 스크립트 파일 접근 권한이 이미 취소되었습니다 Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 @@ -5909,6 +5917,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 @msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 @msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg the script file permissions could not be read: {e} 스크립트 파일 권한을 읽을 수 없습니다: {e} @msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 @msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 @msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 @@ -7175,6 +7184,21 @@ axis Y Axis Y축 @msg time budget 시간 예산 @msg memory budget (the selection is too large to hand over) 메모리 예산(선택 항목이 너무 커서 넘길 수 없음) @msg output size ({what} is {len} bytes, limit {max}) 출력 크기({what}: {len}바이트, 제한 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id}, {script} {line}행 {column}열) +@msg {reason} ({id}, {script}) {reason}({id}, {script}) +@msg memory budget 메모리 예산 +@msg call depth 호출 깊이 +@msg run(input, params) returned no output object run(input, params)이 출력 개체를 반환하지 않았습니다 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js"에는 `script`가 필요합니다: 매니페스트 옆에 있는 플러그인 .js 파일의 이름 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script`는 매니페스트 폴더에 있는 .js 파일의 이름이어야 합니다: 1-128바이트, 폴더 없음, `:` 없음, `.`으로 시작하지 않음 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source`는 스크립트의 텍스트이며 plugin.install의 dataBase64가 받는 JSON에서만 지정합니다: .vcplugin 파일은 스크립트를 `script`에 지정합니다 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 플러그인의 매니페스트는 `runtime` "js"를 지정합니다 +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js"는 개체 필터(`kind` "filter")용이며 `kind` "{kind}"용이 아닙니다 +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 플러그인은 권한 `{name}`을(를) 나열할 수 없습니다: 호스트 권한 중에서 `progress`를 나열할 수 있습니다 +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 모듈의 매니페스트는 `runtime`을 생략합니다: "js"는 JavaScript 플러그인용입니다 +@msg a JavaScript plug-in makes no command calls JavaScript 플러그인은 명령을 호출하지 않습니다 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total)는 숫자 두 개를 받습니다 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text)는 수준 0(오류), 1(경고), 2(정보), 3(디버그) 중 하나와 문자열을 받습니다 @msg the plug-in's grant can't be removed from the plug-in store 플러그인 저장소에서 플러그인의 권한을 제거할 수 없습니다 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` 권한은 이후 플러그인 API용으로 예약되어 있습니다. 이 호스트는 이 권한을 부여하지 않습니다 @msg unknown permission `{shown}` 알 수 없는 권한 `{shown}` @@ -10471,6 +10495,11 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Fold Angle 접는 각도 + Set Fold Angle… 접는 각도 설정… + Set Fold Angle 접는 각도 설정 + Reset Fold Angle 접는 각도 재설정 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 잠기거나 숨겨지지 않은 오시선, 하프 컷 선 또는 미싱선을 선택하세요 # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. 도구 막대의 도구와 그 키가 하는 일을 도움말 대신 카드로 표시합니다. 도구 설명 표시가 켜져 있어야 합니다. Selects whole objects and groups to move, resize or rotate them. 개체와 그룹 전체를 선택하여 이동하거나 크기를 조정하거나 회전합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bbe1681764..dadb532aa8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -102,6 +102,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop @msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger @msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg the script file permissions could not be read: {e} de toestemmingen voor scriptbestanden konden niet worden gelezen: {e} @msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan @msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan @msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten @@ -606,6 +607,21 @@ liquify-list-end {0}, {1} {0} en {1} @msg time budget tijdbudget @msg memory budget (the selection is too large to hand over) geheugenbudget (de selectie is te groot om door te geven) @msg output size ({what} is {len} bytes, limit {max}) uitvoergrootte ({what} is {len} bytes, limiet {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} regel {line}, kolom {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget geheugenbudget +@msg call depth aanroepdiepte +@msg run(input, params) returned no output object run(input, params) heeft geen uitvoerobject teruggegeven +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" heeft `script` nodig: de naam van het .js-bestand van de plug-in, naast het manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` moet de naam zijn van een .js-bestand in de map van het manifest: 1-128 bytes, geen map, geen `:`, niet beginnend met `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` is de tekst van het script en staat alleen in de JSON die dataBase64 van plugin.install aanneemt: een .vcplugin-bestand noemt zijn script in `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" het manifest van een JavaScript-plug-in geeft `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" is voor een objectfilter (`kind` "filter"), niet voor `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` een JavaScript-plug-in kan de toestemming `{name}` niet vermelden: van de toestemmingen van de host mag hij `progress` vermelden +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in het manifest van een WebAssembly-module laat `runtime` weg: "js" is voor een JavaScript-plug-in +@msg a JavaScript plug-in makes no command calls een JavaScript-plug-in roept geen opdrachten aan +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) neemt twee getallen +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) neemt een niveau, 0 (fout), 1 (waarschuwing), 2 (informatie) of 3 (foutopsporing), en een tekenreeks @msg the plug-in's grant can't be removed from the plug-in store de toekenning van de plug-in kan niet uit de plug-inopslag worden verwijderd @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it machtiging `{shown}` is gereserveerd voor een latere plug-in-API; deze host kent haar niet toe @msg unknown permission `{shown}` onbekende machtiging `{shown}` @@ -1302,6 +1318,8 @@ liquify-list-end {0}, {1} {0} en {1} RGB RGB sRGB IEC61966-2.1 sRGB IEC61966-2.1 VectorCraft Generic CMYK (SWOP-like) Generieke VectorCraft-CMYK (SWOP-achtig) + VectorCraft Coated CMYK (FOGRA51) Gestreken VectorCraft-CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) Ongestreken VectorCraft-CMYK (FOGRA52) Legacy Macintosh RGB (Gamma 1.8) Verouderde Macintosh-RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internetstandaard-RGB (sRGB) Monitor RGB Monitor-RGB @@ -5606,6 +5624,14 @@ imageTrace Outline Contour The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. Allow Once Eenmaal toestaan Always Allow This Script Dit script altijd toestaan + No script has kept file access. Geen enkel script heeft bewaarde bestandstoegang. + Read file Bestand lezen + Read and write file Bestand lezen en schrijven + Read and write folder Map lezen en schrijven + Revoke Intrekken + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Intrekken verwijdert de toegang die voor elke versie van het script is bewaard. Toegang tot een map omvat alles erin. +@msg Script file access revoked Bestandstoegang van script ingetrokken +@msg The script file access was already revoked De bestandstoegang van het script was al ingetrokken Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen @@ -10870,6 +10896,11 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Fold Angle Vouwhoek + Set Fold Angle… Vouwhoek instellen… + Set Fold Angle Vouwhoek instellen + Reset Fold Angle Vouwhoek herstellen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecteer een rillijn, halve snijlijn of perforatielijn die niet vergrendeld of verborgen is # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Toont in plaats van de tooltip een kaart met wat een gereedschap in de werkbalk en zijn toetsen doen; vereist Tooltips tonen. Selects whole objects and groups to move, resize or rotate them. Selecteert hele objecten en groepen om ze te verplaatsen, te schalen of te draaien. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be22f98247..f564aa51fa 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5082,6 +5082,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. Allow Once Zezwól raz Always Allow This Script Zawsze zezwalaj temu skryptowi + No script has kept file access. Żaden skrypt nie ma zachowanego dostępu do plików. + Read file Odczyt pliku + Read and write file Odczyt i zapis pliku + Read and write folder Odczyt i zapis folderu + Revoke Odwołaj + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odwołaj usuwa dostęp zachowany dla każdej wersji skryptu. Dostęp do folderu obejmuje całą jego zawartość. +@msg Script file access revoked Odwołano dostęp skryptu do plików +@msg The script file access was already revoked Dostęp skryptu do plików został już odwołany Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia @@ -5247,6 +5255,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop @msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów @msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg the script file permissions could not be read: {e} nie można odczytać uprawnień skryptów do plików: {e} @msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz @msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze @msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte @@ -7436,6 +7445,21 @@ axis Y Axis Oś Y @msg time budget budżet czasu @msg memory budget (the selection is too large to hand over) budżet pamięci (zaznaczenie jest zbyt duże, aby je przekazać) @msg output size ({what} is {len} bytes, limit {max}) rozmiar wyjścia ({what} ma {len} bajtów, limit {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} wiersz {line}, kolumna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget budżet pamięci +@msg call depth głębokość wywołań +@msg run(input, params) returned no output object run(input, params) nie zwróciła obiektu wyjściowego +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" wymaga `script`: nazwy pliku .js wtyczki obok manifestu +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` musi być nazwą pliku .js w folderze manifestu: 1-128 bajtów, bez folderu, bez `:`, nie może zaczynać się od `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` to tekst skryptu, podawany tylko w JSON, który przyjmuje dataBase64 polecenia plugin.install: plik .vcplugin podaje swój skrypt w `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest wtyczki JavaScript podaje `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" jest dla filtra obiektów (`kind` "filter"), nie dla `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` wtyczka JavaScript nie może wymienić uprawnienia `{name}`: spośród uprawnień hosta może wymienić `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest modułu WebAssembly pomija `runtime`: "js" jest dla wtyczki JavaScript +@msg a JavaScript plug-in makes no command calls wtyczka JavaScript nie wywołuje poleceń +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) przyjmuje dwie liczby +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) przyjmuje poziom, 0 (błąd), 1 (ostrzeżenie), 2 (informacja) lub 3 (debugowanie), oraz ciąg znaków @msg the plug-in's grant can't be removed from the plug-in store nie można usunąć uprawnienia wtyczki z magazynu wtyczek @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it uprawnienie `{shown}` jest zarezerwowane dla późniejszego API wtyczek; ten host go nie przyznaje @msg unknown permission `{shown}` nieznane uprawnienie `{shown}` @@ -10697,6 +10721,11 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Fold Angle Kąt zgięcia + Set Fold Angle… Ustaw kąt zgięcia… + Set Fold Angle Ustaw kąt zgięcia + Reset Fold Angle Resetuj kąt zgięcia +@msg select a crease, partial cut or perforation line that is neither locked nor hidden zaznacz linię bigowania, nacięcia lub perforacji, która nie jest zablokowana ani ukryta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zamiast podpowiedzi pokazuje kartę z tym, co robią narzędzie z paska i jego klawisze; wymaga opcji Pokaż podpowiedzi. Selects whole objects and groups to move, resize or rotate them. Zaznacza całe obiekty i grupy, aby je przesuwać, skalować lub obracać. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2be19bf7e..c74f41a894 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6127,6 +6127,14 @@ variable-list-end {0}, {1} {0} e {1} The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. Allow Once Permitir uma vez Always Allow This Script Sempre permitir este script + No script has kept file access. Nenhum script manteve acesso a arquivos. + Read file Ler arquivo + Read and write file Ler e gravar arquivo + Read and write folder Ler e gravar pasta + Revoke Revogar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revogar remove o acesso mantido para cada versão do script. O acesso a uma pasta abrange tudo o que ela contém. +@msg Script file access revoked Acesso do script a arquivos revogado +@msg The script file access was already revoked O acesso do script a arquivos já estava revogado Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente @@ -6292,6 +6300,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop @msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue @msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg the script file permissions could not be read: {e} não foi possível ler as permissões de arquivos dos scripts: {e} @msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez @msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script @msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora @@ -6773,6 +6782,8 @@ mark-style Japanese Japonesas Variation Variação VectorCraft Default Padrão do VectorCraft VectorCraft Generic CMYK (SWOP-like) CMYK Genérico do VectorCraft (tipo SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK Revestido do VectorCraft (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK Não Revestido do VectorCraft (FOGRA52) VectorCraft Swatches (.vcswatches) Amostras do VectorCraft (.vcswatches) Vertical Area Type Texto de Área Vertical Vertical Type Texto Vertical @@ -7480,6 +7491,21 @@ axis Y Axis Eixo Y @msg time budget orçamento de tempo @msg memory budget (the selection is too large to hand over) orçamento de memória (a seleção é grande demais para ser entregue) @msg output size ({what} is {len} bytes, limit {max}) tamanho da saída ({what} tem {len} bytes, limite {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} linha {line}, coluna {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget orçamento de memória +@msg call depth profundidade de chamadas +@msg run(input, params) returned no output object run(input, params) não retornou nenhum objeto de saída +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" precisa de `script`: o nome do arquivo .js do plug-in, ao lado do manifesto +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` deve ser o nome de um arquivo .js na pasta do manifesto: 1-128 bytes, sem pasta, sem `:`, sem começar com `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` é o texto do script, dado só no JSON que o dataBase64 de plugin.install recebe: um arquivo .vcplugin indica seu script em `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" o manifesto de um plug-in JavaScript indica `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" é para um filtro de objetos (`kind` "filter"), não para `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` um plug-in JavaScript não pode listar a permissão `{name}`: das permissões do host, ele pode listar `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in o manifesto de um módulo WebAssembly omite `runtime`: "js" é para um plug-in JavaScript +@msg a JavaScript plug-in makes no command calls um plug-in JavaScript não chama comandos +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) recebe dois números +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) recebe um nível, 0 (erro), 1 (aviso), 2 (informação) ou 3 (depuração), e uma string @msg the plug-in's grant can't be removed from the plug-in store a permissão do plug-in não pode ser removida do armazenamento de plug-ins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a permissão `{shown}` está reservada para uma API de plug-in futura; este host não a concede @msg unknown permission `{shown}` permissão desconhecida `{shown}` @@ -10904,6 +10930,11 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Fold Angle Ângulo de Dobra + Set Fold Angle… Definir Ângulo de Dobra… + Set Fold Angle Definir Ângulo de Dobra + Reset Fold Angle Redefinir Ângulo de Dobra +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecione uma linha de vinco, de meio-corte ou de perfuração que não esteja bloqueada nem oculta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra um cartão com o que uma ferramenta da barra e suas teclas fazem, no lugar da dica; requer Mostrar Dicas de Ferramenta. Selects whole objects and groups to move, resize or rotate them. Seleciona objetos e grupos inteiros para movê-los, redimensioná-los ou girá-los. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e722b4e782..eeeda08d85 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4956,6 +4956,14 @@ axis Both Оба The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. Allow Once Разрешить один раз Always Allow This Script Всегда разрешать этот скрипт + No script has kept file access. Ни у одного скрипта нет сохранённого доступа к файлам. + Read file Чтение файла + Read and write file Чтение и запись файла + Read and write folder Чтение и запись папки + Revoke Отозвать + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Отозвать» удаляет доступ, сохранённый для каждой версии скрипта. Доступ к папке распространяется на всё её содержимое. +@msg Script file access revoked Доступ скрипта к файлам отозван +@msg The script file access was already revoked Доступ скрипта к файлам уже был отозван Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение @@ -5140,6 +5148,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop @msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите @msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg the script file permissions could not be read: {e} не удалось прочитать разрешения скриптов на файлы: {e} @msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз @msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены @@ -7203,6 +7212,21 @@ axis Y Axis Ось Y @msg time budget бюджет времени @msg memory budget (the selection is too large to hand over) бюджет памяти (выделение слишком велико для передачи) @msg output size ({what} is {len} bytes, limit {max}) размер вывода ({what}: {len} байт, предел {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, строка {line}, столбец {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget бюджет памяти +@msg call depth глубина вызовов +@msg run(input, params) returned no output object run(input, params) не вернула объект вывода +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest для `runtime` "js" нужен `script`: имя файла .js модуля рядом с манифестом +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` должен быть именем файла .js в папке манифеста: 1-128 байт, без папки, без `:`, не начинаясь с `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` содержит текст скрипта и задаётся только в JSON, который принимает dataBase64 команды plugin.install: файл .vcplugin называет свой скрипт в `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" манифест модуля JavaScript задаёт `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" предназначен для фильтра объектов (`kind` "filter"), а не для `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` модуль JavaScript не может перечислять разрешение `{name}`: из разрешений хоста он может перечислить `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in манифест модуля WebAssembly не указывает `runtime`: "js" предназначен для модуля JavaScript +@msg a JavaScript plug-in makes no command calls модуль JavaScript не вызывает команды +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) принимает два числа +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) принимает уровень, 0 (ошибка), 1 (предупреждение), 2 (информация) или 3 (отладка), и строку @msg the plug-in's grant can't be removed from the plug-in store разрешение модуля нельзя удалить из хранилища модулей @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it разрешение `{shown}` зарезервировано для будущего API модулей; этот хост его не выдаёт @msg unknown permission `{shown}` неизвестное разрешение `{shown}` @@ -8005,6 +8029,8 @@ arrowhead Target Мишень VectorCraft Default VectorCraft по умолчанию VectorCraft Defaults Стандартные VectorCraft VectorCraft Generic CMYK (SWOP-like) Общий CMYK VectorCraft (как SWOP) + VectorCraft Coated CMYK (FOGRA51) CMYK VectorCraft для мелованной бумаги (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) CMYK VectorCraft для немелованной бумаги (FOGRA52) VectorCraft Swatches (.vcswatches) Образцы VectorCraft (.vcswatches) Vertical Align Вертикальное выравнивание Vertical Area Type Вертикальный текст в области @@ -10918,6 +10944,11 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Fold Angle Угол сгиба + Set Fold Angle… Задать угол сгиба… + Set Fold Angle Задать угол сгиба + Reset Fold Angle Сбросить угол сгиба +@msg select a crease, partial cut or perforation line that is neither locked nor hidden выделите линию биговки, надреза или перфорации, которая не закреплена и не скрыта Check Проверить Check Fold Lines Проверить линии сгиба @msg No cut lines are in the selection. В выделении нет линий реза. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2c9b16b092..9c5ffcddb8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4815,6 +4815,14 @@ axis Both Båda The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. Allow Once Tillåt en gång Always Allow This Script Tillåt alltid det här skriptet + No script has kept file access. Inget skript har sparad filåtkomst. + Read file Läs fil + Read and write file Läs och skriv fil + Read and write folder Läs och skriv mapp + Revoke Återkalla + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Återkalla tar bort åtkomsten som sparats för varje version av skriptet. Åtkomst till en mapp omfattar allt i den. +@msg Script file access revoked Skriptets filåtkomst har återkallats +@msg The script file access was already revoked Skriptets filåtkomst var redan återkallad Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen @@ -5013,6 +5021,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop @msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka @msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg the script file permissions could not be read: {e} skriptens filbehörigheter kunde inte läsas: {e} @msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång @msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst @msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades @@ -6817,6 +6826,8 @@ arrowhead Feather Fjäder VectorCraft Default VectorCraft-standard VectorCraft Defaults VectorCraft-standardvärden VectorCraft Generic CMYK (SWOP-like) VectorCraft allmän CMYK (SWOP-liknande) + VectorCraft Coated CMYK (FOGRA51) VectorCraft bestruken CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft obestruken CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft-färgrutor (.vcswatches) Vertical Align Vertikal justering Vertical Area Type Vertikal områdestext @@ -9756,6 +9767,21 @@ digits Hindi Hindi @msg outlineText {v}: true or false outlineText {v}: true eller false @msg output intent profile: {e} profil för utgångsavsikt: {e} @msg output size ({what} is {len} bytes, limit {max}) utdatastorlek ({what} är {len} byte, gräns {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} rad {line}, kolumn {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget minnesbudget +@msg call depth anropsdjup +@msg run(input, params) returned no output object run(input, params) returnerade inget utdataobjekt +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" kräver `script`: namnet på pluginets .js-fil bredvid manifestet +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` måste vara namnet på en .js-fil i manifestets mapp: 1-128 byte, ingen mapp, inget `:`, får inte börja med `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` är skriptets text och anges bara i den JSON som dataBase64 i plugin.install tar: en .vcplugin-fil namnger sitt skript i `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifestet för ett JavaScript-plugin anger `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" är för ett objektfilter (`kind` "filter"), inte `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` ett JavaScript-plugin kan inte ange behörigheten `{name}`: av värdens behörigheter får det ange `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifestet för en WebAssembly-modul utelämnar `runtime`: "js" är för ett JavaScript-plugin +@msg a JavaScript plug-in makes no command calls ett JavaScript-plugin anropar inga kommandon +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) tar två tal +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) tar en nivå, 0 (fel), 1 (varning), 2 (information) eller 3 (felsökning), och en sträng @msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1}-filer är CMYK, och ”{name}” är en RGB-profil @msg output.destination: {e} output.destination: {e} @msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: ingen RGB- eller CMYK-profil heter ”{name}” @@ -10957,6 +10983,11 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Fold Angle Falsvinkel + Set Fold Angle… Ange falsvinkel… + Set Fold Angle Ange falsvinkel + Reset Fold Angle Återställ falsvinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markera en biglinje, halvskärlinje eller perforeringslinje som varken är låst eller dold Check Kontrollera Check Fold Lines Kontrollera falslinjer @msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 15e0be1049..a7fb6cafba 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -829,19 +829,18 @@ fn menu_item_effect<'a>(id: &str, p: &'a serde_json::Value) -> Option<&'a str> { p.get("effect").and_then(serde_json::Value::as_str).filter(|_| matches!(id, "effect.apply" | "effect.dialog")) } -/// The label a menu item shows in `lang`, as the menus resolve it: an Effect menu item by its -/// effect's `@id` row when the catalog has one, any other command by its id's row or its English -/// label, and a submenu, an unbuilt item or a placeholder by its English label. -fn shown_menu_label(lang: Lang, item: &crate::menus::Node) -> Option<&str> { +/// The label a menu item shows in `lang`, as the menus resolve it: a built-in Effect menu item by +/// its effect's name ([`crate::menus::effect_item_label`]), any other command by its id's row or +/// its English label, and a submenu, an unbuilt item or a placeholder by its English label. +fn shown_menu_label(lang: Lang, item: &crate::menus::Node) -> Option { use crate::menus::Node; match item { - Node::Item(it) if crate::menus::unbound(&it.command.id) => Some(tr(lang, &it.label)), + Node::Item(it) if crate::menus::unbound(&it.command.id) => Some(tr(lang, &it.label).to_string()), Node::Item(it) => { let (id, p) = (it.command.id.as_str(), &it.command.params); - let by_effect = menu_item_effect(id, p).map(|e| tr_id(lang, e, "")).filter(|s| !s.is_empty()); - Some(by_effect.unwrap_or_else(|| tr_id(lang, id, &it.label))) + Some(crate::menus::effect_item_label(id, p, lang).unwrap_or_else(|| tr_id(lang, id, &it.label).to_string())) } - Node::Submenu { label, .. } => Some(tr(lang, label)), + Node::Submenu { label, .. } => Some(tr(lang, label).to_string()), _ => None, } } @@ -853,7 +852,7 @@ fn shown_menu_label(lang: Lang, item: &crate::menus::Node) -> Option<&str> { fn menu_items_side_by_side_have_different_labels() { use crate::menus::Node; fn walk(lang: Lang, path: &str, items: &[Node], out: &mut Vec) { - let mut seen: std::collections::BTreeMap<&str, (&str, &str)> = std::collections::BTreeMap::new(); + let mut seen: std::collections::BTreeMap = std::collections::BTreeMap::new(); for item in items { let Some(shown) = shown_menu_label(lang, item) else { continue }; let (english, what) = match item { @@ -862,7 +861,7 @@ fn menu_items_side_by_side_have_different_labels() { Node::Submenu { label, .. } => (label.as_str(), "submenu or unbuilt item"), _ => continue, }; - match seen.get(shown) { + match seen.get(&shown) { Some(&(other, other_what)) if other != english => { out.push(format!("{}: {path}: {other:?} ({other_what}) and {english:?} ({what}) both show {shown:?}", lang.code())); } @@ -916,7 +915,7 @@ fn menu_items_never_show_an_id() { let (l, id) = (&it.label, it.command.id.as_str()); let key = menu_item_effect(id, &it.command.params).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); - if label_shows_an_id(shown, key) && !label_shows_an_id(l, key) { + if label_shows_an_id(&shown, key) && !label_shows_an_id(l, key) { out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.code())); } } @@ -1009,14 +1008,15 @@ fn untranslated_report() { assert!(strings.len() > 500, "menu scan found only {} strings", strings.len()); let literals = tl_literals(); assert!(literals.len() > 300, "scan found only {} tl! literals", literals.len()); - // Undo step names: the recorded names, every effect's name without its ellipsis, and the - // Liquify tools' step names (`{} Tool`). A name's row is its plain row or the row of the same - // name with an ellipsis (`panels::history::step_name`); a template made with - // `Session::edit_named` needs a plain row, which `panels::history::entry_name` fills. + // Undo step names: the recorded names and the Liquify tools' step names (`{} Tool`). A name's + // row is its plain row or the row of the same name with an ellipsis + // (`panels::history::step_name`); a template made with `Session::edit_named` needs a plain + // row, which `panels::history::entry_name` fills. A step that applies an effect is named as + // the Effect menu names it (`i18n::has_effect_name`), listed under "effect names". let scan = undo_scan(); let mut undo = scan.labels; assert!(undo.len() > 300, "scan found only {} undo labels", undo.len()); - undo.extend(vectorcraft_effects::effect_catalog().iter().map(|e| e.label.trim_end_matches('…').to_string())); + let effect_ids: Vec<&'static str> = vectorcraft_effects::effect_catalog().iter().map(|e| e.id).collect(); let liquify = ["warp", "twirl", "pucker", "bloat", "scallop", "crystallize", "wrinkle"]; undo.extend(liquify.iter().filter_map(|k| vectorcraft_tools::distort::liquify::LiquifyKind::parse(k)).map(|k| format!("{} Tool", k.label()))); assert_eq!(scan.formatted.iter().collect::>(), ["{} Tool"], "step names built with format! (make them with Session::edit_named)"); @@ -1040,6 +1040,11 @@ fn untranslated_report() { add(code, "menu strings", strings.iter().filter(|s| !kept(s) && !has(lang, s)).cloned().collect::>()); add(code, "tl! strings", literals.iter().filter(|s| !has(lang, s)).cloned().collect::>()); add(code, "undo labels", undo.iter().filter(|s| crate::panels::history::step_name(lang, s).is_none()).cloned().collect::>()); + add( + code, + "effect names", + effect_ids.iter().filter(|id| !crate::i18n::has_effect_name(lang, id)).map(|id| id.to_string()).collect::>(), + ); add(code, "undo label templates", scan.templates.iter().filter(|t| !has(lang, t)).cloned().collect::>()); let render_site = RENDER_SITE_ROWS.iter().filter(|(ctx, src)| catalog.get(lang, ctx, src).is_none()).map(|(ctx, src)| format!("{ctx}: {src}")); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 81accf43c5..263f230843 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4661,6 +4661,14 @@ axis Both Her İkisi The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. Allow Once Bir Kez İzin Ver Always Allow This Script Bu Betiğe Her Zaman İzin Ver + No script has kept file access. Hiçbir betiğin kayıtlı dosya erişimi yok. + Read file Dosya Okuma + Read and write file Dosya Okuma ve Yazma + Read and write folder Klasör Okuma ve Yazma + Revoke İzni Kaldır + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. İzni Kaldır, betiğin her sürümü için kayıtlı erişimi kaldırır. Bir klasöre erişim, içindeki her şeyi kapsar. +@msg Script file access revoked Betiğin dosya erişimi kaldırıldı +@msg The script file access was already revoked Betiğin dosya erişimi zaten kaldırılmıştı Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme @@ -4843,6 +4851,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop @msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin @msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg the script file permissions could not be read: {e} betiklerin dosya izinleri okunamadı: {e} @msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir @msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir @msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı @@ -6662,6 +6671,8 @@ arrowhead Feather Tüy VectorCraft Default VectorCraft Varsayılanı VectorCraft Defaults VectorCraft Varsayılanları VectorCraft Generic CMYK (SWOP-like) VectorCraft Genel CMYK (SWOP benzeri) + VectorCraft Coated CMYK (FOGRA51) VectorCraft Kaplamalı CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft Kaplamasız CMYK (FOGRA52) VectorCraft Swatches (.vcswatches) VectorCraft Renk Örnekleri (.vcswatches) Vertical Align Dikey Hizalama Vertical Area Type Dikey Alan Türü @@ -7653,6 +7664,21 @@ axis Y Axis Y ekseni @msg time budget zaman bütçesi @msg memory budget (the selection is too large to hand over) bellek bütçesi (seçim aktarılamayacak kadar büyük) @msg output size ({what} is {len} bytes, limit {max}) çıktı boyutu ({what}: {len} bayt, sınır {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} satır {line}, sütun {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget bellek bütçesi +@msg call depth çağrı derinliği +@msg run(input, params) returned no output object run(input, params) bir çıktı nesnesi döndürmedi +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" için `script` gerekir: eklentinin bildirimin yanındaki .js dosyasının adı +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script`, bildirimin klasöründeki bir .js dosyasının adı olmalıdır: 1-128 bayt, klasör yok, `:` yok, `.` ile başlamaz +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` betiğin metnidir ve yalnızca plugin.install komutunun dataBase64 parametresinin aldığı JSON içinde verilir: bir .vcplugin dosyası betiğini `script` içinde adlandırır +@msg a JavaScript plug-in's manifest gives `runtime` "js" bir JavaScript eklentisinin bildirimi `runtime` "js" verir +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" bir nesne filtresi içindir (`kind` "filter"), `kind` "{kind}" için değil +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` bir JavaScript eklentisi `{name}` iznini listeleyemez: ana makinenin izinlerinden `progress` iznini listeleyebilir +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in bir WebAssembly modülünün bildirimi `runtime` anahtarını atlar: "js" bir JavaScript eklentisi içindir +@msg a JavaScript plug-in makes no command calls bir JavaScript eklentisi komut çağırmaz +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) iki sayı alır +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) bir düzey, 0 (hata), 1 (uyarı), 2 (bilgi) veya 3 (hata ayıklama), ve bir dize alır @msg the plug-in's grant can't be removed from the plug-in store eklentinin izni eklenti deposundan kaldırılamıyor @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` izni sonraki bir eklenti API’si için ayrılmıştır; bu ana bilgisayar bu izni vermez @msg unknown permission `{shown}` bilinmeyen izin `{shown}` @@ -10789,6 +10815,11 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Fold Angle Katlama Açısı + Set Fold Angle… Katlama Açısını Ayarla… + Set Fold Angle Katlama Açısını Ayarla + Reset Fold Angle Katlama Açısını Sıfırla +@msg select a crease, partial cut or perforation line that is neither locked nor hidden kilitli ya da gizli olmayan bir pilyaj, yarım kesim veya perforaj çizgisi seçin # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Araç çubuğundaki bir aracın ve tuşlarının ne yaptığını ipucu yerine bir kartta gösterir; Araç İpuçlarını Göster gerekir. Selects whole objects and groups to move, resize or rotate them. Taşımak, yeniden boyutlandırmak veya döndürmek için nesnelerin ve grupların tamamını seçer. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e1700dbb94..65ba53d65d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4964,6 +4964,14 @@ axis Both Обидві The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. Allow Once Дозволити один раз Always Allow This Script Завжди дозволяти цей скрипт + No script has kept file access. Жоден скрипт не має збереженого доступу до файлів. + Read file Читання файлу + Read and write file Читання й запис файлу + Read and write folder Читання й запис папки + Revoke Відкликати + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Відкликати» прибирає доступ, збережений для кожної версії скрипту. Доступ до папки охоплює весь її вміст. +@msg Script file access revoked Доступ скрипту до файлів відкликано +@msg The script file access was already revoked Доступ скрипту до файлів уже було відкликано Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження @@ -5129,6 +5137,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop @msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте @msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg the script file permissions could not be read: {e} не вдалося прочитати дозволи скриптів на файли: {e} @msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз @msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено @@ -7185,6 +7194,21 @@ axis Y Axis Вісь Y @msg time budget бюджет часу @msg memory budget (the selection is too large to hand over) бюджет пам’яті (виділення завелике для передавання) @msg output size ({what} is {len} bytes, limit {max}) розмір виводу ({what}: {len} байтів, межа {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script}, рядок {line}, стовпець {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget бюджет пам’яті +@msg call depth глибина викликів +@msg run(input, params) returned no output object run(input, params) не повернула об’єкт виводу +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest для `runtime` "js" потрібен `script`: ім’я файлу .js модуля поруч із маніфестом +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` має бути ім’ям файлу .js у теці маніфесту: 1-128 байтів, без теки, без `:`, не починаючись із `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` містить текст скрипту й задається лише в JSON, який приймає dataBase64 команди plugin.install: файл .vcplugin називає свій скрипт у `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" маніфест модуля JavaScript задає `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" призначено для фільтра об’єктів (`kind` "filter"), а не для `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` модуль JavaScript не може перелічувати дозвіл `{name}`: із дозволів хоста він може перелічити `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in маніфест модуля WebAssembly не вказує `runtime`: "js" призначено для модуля JavaScript +@msg a JavaScript plug-in makes no command calls модуль JavaScript не викликає команд +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) приймає два числа +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) приймає рівень, 0 (помилка), 1 (попередження), 2 (інформація) або 3 (налагодження), і рядок @msg the plug-in's grant can't be removed from the plug-in store дозвіл модуля не вдається вилучити зі сховища модулів @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it дозвіл `{shown}` зарезервовано для пізнішого API модулів; цей хост його не надає @msg unknown permission `{shown}` невідомий дозвіл `{shown}` @@ -10484,6 +10508,11 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Fold Angle Кут згину + Set Fold Angle… Задати кут згину… + Set Fold Angle Задати кут згину + Reset Fold Angle Скинути кут згину +@msg select a crease, partial cut or perforation line that is neither locked nor hidden виділіть лінію біговки, надрізу або перфорації, яка не закріплена й не прихована # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Замість підказки показує картку з тим, що роблять інструмент панелі та його клавіші; потрібно Показувати підказки. Selects whole objects and groups to move, resize or rotate them. Виділяє об’єкти й групи цілком, щоб переміщувати, масштабувати або обертати їх. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 278a8c10e9..965740d026 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5442,6 +5442,14 @@ theme Appearance Giao diện The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. Allow Once Cho phép một lần Always Allow This Script Luôn cho phép tập lệnh này + No script has kept file access. Không có tập lệnh nào được giữ quyền truy cập tệp. + Read file Đọc tệp + Read and write file Đọc và ghi tệp + Read and write folder Đọc và ghi thư mục + Revoke Thu hồi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Thu hồi gỡ quyền truy cập đã giữ cho mọi phiên bản của tập lệnh. Quyền truy cập một thư mục bao gồm mọi thứ bên trong. +@msg Script file access revoked Đã thu hồi quyền truy cập tệp của tập lệnh +@msg The script file access was already revoked Quyền truy cập tệp của tập lệnh đã được thu hồi trước đó Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này @@ -5639,6 +5647,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop @msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối @msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg the script file permissions could not be read: {e} không thể đọc quyền truy cập tệp của các tập lệnh: {e} @msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần @msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp @msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua @@ -7232,6 +7241,21 @@ axis Y Axis Trục Y @msg time budget ngân sách thời gian @msg memory budget (the selection is too large to hand over) ngân sách bộ nhớ (vùng chọn quá lớn để chuyển giao) @msg output size ({what} is {len} bytes, limit {max}) kích thước đầu ra ({what} là {len} byte, giới hạn {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason} ({id}, {script} dòng {line}, cột {column}) +@msg {reason} ({id}, {script}) {reason} ({id}, {script}) +@msg memory budget ngân sách bộ nhớ +@msg call depth độ sâu lời gọi +@msg run(input, params) returned no output object run(input, params) không trả về đối tượng đầu ra nào +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" cần `script`: tên tệp .js của plug-in, nằm cạnh manifest +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` phải là tên một tệp .js trong thư mục của manifest: 1-128 byte, không có thư mục, không có `:`, không bắt đầu bằng `.` +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` là văn bản của tập lệnh, chỉ được cung cấp trong JSON mà dataBase64 của plugin.install nhận: tệp .vcplugin nêu tên tập lệnh của nó trong `script` +@msg a JavaScript plug-in's manifest gives `runtime` "js" manifest của plug-in JavaScript cho `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" dành cho bộ lọc đối tượng (`kind` "filter"), không phải `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` plug-in JavaScript không thể liệt kê quyền `{name}`: trong các quyền của máy chủ, nó có thể liệt kê `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in manifest của mô-đun WebAssembly bỏ qua `runtime`: "js" dành cho plug-in JavaScript +@msg a JavaScript plug-in makes no command calls plug-in JavaScript không gọi lệnh +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) nhận hai số +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) nhận một mức, 0 (lỗi), 1 (cảnh báo), 2 (thông tin) hoặc 3 (gỡ lỗi), và một chuỗi @msg the plug-in's grant can't be removed from the plug-in store không thể xóa quyền của plug-in khỏi kho plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it quyền `{shown}` được dành cho một API plug-in sau này; máy chủ này không cấp quyền đó @msg unknown permission `{shown}` quyền không xác định `{shown}` @@ -8604,6 +8628,11 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Fold Angle Góc gấp + Set Fold Angle… Đặt góc gấp… + Set Fold Angle Đặt góc gấp + Reset Fold Angle Đặt lại góc gấp +@msg select a crease, partial cut or perforation line that is neither locked nor hidden hãy chọn một đường cấn, đường cắt một phần hoặc đường đục lỗ không bị khóa và không bị ẩn Check Kiểm tra Check Fold Lines Kiểm tra đường gấp @msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ae265a4fc7..7949198691 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5471,6 +5471,14 @@ imageTrace Outline 轮廓 The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 Allow Once 允许一次 Always Allow This Script 始终允许此脚本 + No script has kept file access. 没有脚本保留了文件访问权限。 + Read file 读取文件 + Read and write file 读取和写入文件 + Read and write folder 读取和写入文件夹 + Revoke 收回权限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. “收回权限”会移除为脚本每个版本保留的访问权限。文件夹的访问权限包括其中的所有内容。 +@msg Script file access revoked 已收回脚本的文件访问权限 +@msg The script file access was already revoked 脚本的文件访问权限已被收回 Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 @@ -5636,6 +5644,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop @msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 @msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg the script file permissions could not be read: {e} 无法读取脚本的文件权限:{e} @msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 @msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 @msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 @@ -6212,6 +6221,8 @@ liquify-list-end {0}, {1} {0}和{1} Photo Low Fidelity 低保真照片 Restricted Colors 受限颜色 VectorCraft Generic CMYK (SWOP-like) VectorCraft 通用 CMYK (类 SWOP) + VectorCraft Coated CMYK (FOGRA51) VectorCraft 涂布纸 CMYK (FOGRA51) + VectorCraft Uncoated CMYK (FOGRA52) VectorCraft 非涂布纸 CMYK (FOGRA52) sRGB IEC61966-2.1 sRGB IEC61966-2.1 Working RGB 工作 RGB Dot Gain 15% 网点扩大 15% @@ -7413,6 +7424,21 @@ axis Y Axis Y 轴 @msg time budget 时间预算 @msg memory budget (the selection is too large to hand over) 内存预算(所选内容太大,无法传递) @msg output size ({what} is {len} bytes, limit {max}) 输出大小({what} 为 {len} 字节,上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id},{script} 第 {line} 行,第 {column} 列) +@msg {reason} ({id}, {script}) {reason}({id},{script}) +@msg memory budget 内存预算 +@msg call depth 调用深度 +@msg run(input, params) returned no output object run(input, params) 未返回输出对象 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" 需要 `script`:清单旁边增效工具 .js 文件的名称 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` 必须是清单所在文件夹中 .js 文件的名称:1-128 字节,不含文件夹,不含 `:`,不以 `.` 开头 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` 是脚本的文本,只在 plugin.install 的 dataBase64 接受的 JSON 中给出:.vcplugin 文件在 `script` 中指定其脚本 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 增效工具的清单指定 `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" 用于对象滤镜(`kind` "filter"),而不是 `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 增效工具不能列出权限 `{name}`:在主机的权限中,它可以列出 `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 模块的清单省略 `runtime`:"js" 用于 JavaScript 增效工具 +@msg a JavaScript plug-in makes no command calls JavaScript 增效工具不调用命令 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) 接受两个数字 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) 接受一个级别(0(错误)、1(警告)、2(信息)或 3(调试))和一个字符串 @msg the plug-in's grant can't be removed from the plug-in store 无法从增效工具存储中移除该增效工具的授权 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 权限 `{shown}` 保留给以后的增效工具 API;此主机不授予该权限 @msg unknown permission `{shown}` 未知权限 `{shown}` @@ -10707,6 +10733,11 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Fold Angle 折叠角度 + Set Fold Angle… 设置折叠角度… + Set Fold Angle 设置折叠角度 + Reset Fold Angle 重置折叠角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 请选择未锁定且未隐藏的压痕线、半切线或打孔线 Check 检查 Check Fold Lines 检查折线 @msg No cut lines are in the selection. 所选内容中没有切割线。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7d83822f05..bdd34272f2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2806,6 +2806,14 @@ file-filter Templates 範本 The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 Allow Once 允許一次 Always Allow This Script 一律允許此指令碼 + No script has kept file access. 沒有指令碼保留檔案存取權。 + Read file 讀取檔案 + Read and write file 讀取和寫入檔案 + Read and write folder 讀取和寫入資料夾 + Revoke 收回權限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「收回權限」會移除為指令碼每個版本保留的存取權。資料夾的存取權包含其中的所有內容。 +@msg Script file access revoked 已收回指令碼的檔案存取權 +@msg The script file access was already revoked 指令碼的檔案存取權已被收回 Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 @@ -2980,6 +2988,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop @msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 @msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg the script file permissions could not be read: {e} 無法讀取指令碼的檔案權限:{e} @msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 @msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 @msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 @@ -7234,6 +7243,21 @@ axis Y Axis Y 軸 @msg time budget 時間預算 @msg memory budget (the selection is too large to hand over) 記憶體預算(所選內容太大,無法傳遞) @msg output size ({what} is {len} bytes, limit {max}) 輸出大小({what} 為 {len} 位元組,上限 {max}) +@msg {reason} ({id}, {script} line {line}, column {column}) {reason}({id},{script} 第 {line} 行,第 {column} 欄) +@msg {reason} ({id}, {script}) {reason}({id},{script}) +@msg memory budget 記憶體預算 +@msg call depth 呼叫深度 +@msg run(input, params) returned no output object run(input, params) 未傳回輸出物件 +@msg `runtime` "js" needs `script`: the name of the plug-in's .js file, next to the manifest `runtime` "js" 需要 `script`:資訊清單旁增效模組 .js 檔案的名稱 +@msg `script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.` `script` 必須是資訊清單所在資料夾中 .js 檔案的名稱:1-128 位元組,不含資料夾,不含 `:`,不以 `.` 開頭 +@msg `source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script` `source` 是指令碼的文字,只在 plugin.install 的 dataBase64 接受的 JSON 中提供:.vcplugin 檔案在 `script` 中指定其指令碼 +@msg a JavaScript plug-in's manifest gives `runtime` "js" JavaScript 增效模組的資訊清單指定 `runtime` "js" +@msg `runtime` "js" is for an object filter (`kind` "filter"), not `kind` "{kind}" `runtime` "js" 用於物件濾鏡(`kind` "filter"),而不是 `kind` "{kind}" +@msg a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress` JavaScript 增效模組不能列出權限 `{name}`:在主機的權限中,它可以列出 `progress` +@msg a WebAssembly module's manifest leaves `runtime` out: "js" is for a JavaScript plug-in WebAssembly 模組的資訊清單不填寫 `runtime`:"js" 用於 JavaScript 增效模組 +@msg a JavaScript plug-in makes no command calls JavaScript 增效模組不呼叫命令 +@msg vc.progress(done, total) takes two numbers vc.progress(done, total) 接受兩個數字 +@msg vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string vc.log(level, text) 接受一個層級(0(錯誤)、1(警告)、2(資訊)或 3(偵錯))和一個字串 @msg the plug-in's grant can't be removed from the plug-in store 無法從增效模組存放區移除該增效模組的授權 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 權限 `{shown}` 保留給日後的增效模組 API;此主機不授予該權限 @msg unknown permission `{shown}` 未知權限 `{shown}` @@ -10523,6 +10547,11 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Fold Angle 摺疊角度 + Set Fold Angle… 設定摺疊角度… + Set Fold Angle 設定摺疊角度 + Reset Fold Angle 重設摺疊角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 請選取未鎖定且未隱藏的壓痕線、半切線或打孔線 Check 檢查 Check Fold Lines 檢查摺線 @msg No cut lines are in the selection. 選取範圍中沒有切割線。 diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 04771e26ff..75d9bd9b65 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -26,9 +26,15 @@ pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opti /// [`open_bytes`], a document opening with `document.open`'s params `p`. fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { let opens = opens_as(name); - // A WebAssembly plug-in is installed. + // A plug-in is installed: a JavaScript plug-in's manifest by its path, which the script it + // names is read beside. Without a path the manifest's bytes alone are refused, since they hold + // no script (`vectorcraft_plugins::js::SOURCE_RULE`). if opens == Some(OpensAs::Plugin) { - let module = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": path.as_deref().unwrap_or(name)}); + let js = vectorcraft_plugins::registry::is_js_package(std::path::Path::new(name)); + let module = match path.as_deref() { + Some(path) if js => json!({ "path": path }), + _ => json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": path.as_deref().unwrap_or(name)}), + }; return install_module(app, module).map(|_| Value::Null); } if opens == Some(OpensAs::ShortcutSet) { @@ -609,6 +615,12 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } + // A JavaScript plug-in's manifest is read by `plugin.install {path}`, with the script it names. + if opens_as(path) == Some(OpensAs::Plugin) && vectorcraft_plugins::registry::is_js_package(std::path::Path::new(path)) { + install_module(app, json!({ "path": path }))?; + note_recent(app, path); + return Ok(Value::Null); + } // A file only an importer plug-in reads is not read past the importer's input limit. check_import_size(path, false)?; let bytes = read(app, path)?; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6078ca0c07..a9b143e397 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -72,6 +72,7 @@ pub mod prefs_dialog; pub mod print; pub mod recovery; pub mod render_worker; +pub mod retype_runs; pub mod screen_color; pub mod script_runs; pub mod scripts_menu; @@ -249,6 +250,8 @@ pub struct VectorcraftApp { pub placing: placing::Placing, /// Image Traces running off the UI thread ([`trace_runs`]). pub trace_runs: trace_runs::TraceRuns, + /// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]). + pub retype_runs: retype_runs::RetypeRuns, /// Data Recovery's timer and startup question ([`recovery`]). pub recovery: recovery::Timer, /// The Close, Close All or Quit in progress, which asks about each unsaved document in turn. @@ -270,6 +273,8 @@ pub struct VectorcraftApp { pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, + /// The document whose settings the open Document Setup dialog edits. + pub(crate) document_setup_source: Option, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one /// step however many values it sets. pub(crate) edit_scopes: HashMap, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5291000751..6355eca440 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -81,6 +81,8 @@ use entries::flatten; pub use entries::{InsertableItem, MenuEntry, context_entries, insertable, insertable_items, menu_entries, plays_in_app, shown_label}; pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; +#[cfg(test)] +pub(crate) use labels::effect_item_label; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; pub(crate) use labels::{holds_plugin_commands, item_shortcut_in, lists_plugin}; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 212cffd703..ef801cd4b7 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -55,7 +55,15 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { c("Select All", "select.all"), ]); } else { - v.extend([c("Cut", "edit.cut"), c("Copy", "edit.copy"), c("Paste", "edit.paste"), Sep]); + v.extend([c("Cut", "edit.cut"), c("Copy", "edit.copy"), c("Paste", "edit.paste")]); + // With the Quick Pen, Delete removes the selected anchor points, or the selected objects + // (`edit.clear`), as the public + // [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) + // page describes for removing a path. + if app.session.tool_id() == vectorcraft_tools::quickpen::ID { + v.push(c("Delete", "edit.clear")); + } + v.push(Sep); // With one group or compound path selected the menu has Isolate Selected Group, and with // one path selected (a member of a group or a compound path too) it has Isolate Selected // Path, as the help page diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 09513fb538..69722bd1ae 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -9,7 +9,7 @@ use super::{Node, Serialize, Value, VectorcraftApp, unbound}; /// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a /// spelling suggestion, or [`display_label`]. pub fn shown_label(app: &VectorcraftApp, id: &str, p: &Value, label: &str) -> String { - effect_item_label(id, p) + effect_item_label(id, p, crate::i18n::current()) .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) .or_else(|| spelling_item_label(id, p)) .unwrap_or_else(|| display_label(app, id, label)) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 1c36614574..ec9f3a68ff 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -55,6 +55,8 @@ pub(super) fn open_menu_dialog(app: &mut VectorcraftApp, id: &str) -> Option crate::dialogs::rearrange_artboards::open(app), crate::dialogs::rename_artboards::CMD => crate::dialogs::rename_artboards::open(app), crate::dialogs::smart_punctuation::COMMAND => crate::dialogs::smart_punctuation::open(app), + // Set Fold Angle… opens on the angle the selected fold lines fold at, and says why while it can change none. + crate::addons::packaging::SET_FOLD_ANGLE => crate::addons::packaging::open_dialog(app), _ => return None, }) } @@ -136,6 +138,21 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } return; } + // Retype and Find Matching Fonts read the installed fonts off the UI thread, with their + // progress; Find more font matches lists what the last search found at once, and before any + // search it is a new one. + let new_search = match p.get("more") { + None | Some(serde_json::Value::Null | serde_json::Value::Bool(false)) => true, + Some(serde_json::Value::Bool(true)) => !app.ui.retype.searched, + Some(_) => false, + }; + if id == "type.retype" || (id == "retype.find" && new_search) { + let r = if id == "type.retype" { crate::retype_runs::start(app, id, p, false) } else { crate::panels::retype::find_in_background(app, &p) }; + if let Err(e) = r { + app.status(e); + } + return; + } if let Some(r) = crate::panels::artboards::run_menu_item(app, id, &p) { if let Err(e) = r { app.status(e); diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 3957d294b6..65cc2eb334 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -207,8 +207,8 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { "window.toolbarAdvanced" => crate::i18n::tr(lang, label).to_string(), "effect.last" => match &app.last_effect { Some((e, _)) => { - let name = vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str()); - fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) + let name = crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone()); + fmt(tl!("Last Effect: {name}"), &[("name", &name)]) } None => crate::i18n::tr_id(lang, id, label).to_string(), }, @@ -232,17 +232,19 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } } -/// The label of an Effect menu item in the UI language, by the effect's own id. Every effect item -/// runs `effect.apply` or `effect.dialog`, so the command id can't tell them apart; an `@id` row -/// for the effect id (for example `pathfinder.add`) wins over the plain row of the English label. -/// `None` when the catalog has no such row, and the plain translation applies. -pub(super) fn effect_item_label(id: &str, p: &Value) -> Option { +/// The label of an Effect menu item in `lang`, by the effect's own id +/// ([`crate::i18n::effect_menu_label`]). Every effect item runs `effect.apply` or `effect.dialog`, +/// so the command id can't tell them apart. `None` for any other item, and for a plug-in effect, +/// whose item shows the plug-in's own text. +pub(crate) fn effect_item_label(id: &str, p: &Value, lang: crate::i18n::Lang) -> Option { if !matches!(id, "effect.apply" | "effect.dialog") { return None; } let effect = p.get("effect")?.as_str()?; - let shown = crate::i18n::tr_id(crate::i18n::current(), effect, ""); - (!shown.is_empty()).then(|| shown.to_string()) + if vectorcraft_plugins::effect::plugin_id(effect).is_some() { + return None; + } + crate::i18n::effect_menu_label(lang, effect) } /// The label of an item of the canvas context menu's Unlock submenu (`layer.setProps` with one id diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 2a4700a6b8..5ea7d6b6f4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1219,6 +1219,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::plugin_runs::hide_all(app)), "imageTrace.cancelRuns" => Ok(crate::trace_runs::cancel_all(app)), "imageTrace.hideRuns" => Ok(crate::trace_runs::hide_all(app)), + "retype.cancelSearch" => Ok(crate::retype_runs::cancel(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), "ui.runScript" => crate::dialogs::script_run::command(app, p), crate::scripts_menu::COMMAND => crate::scripts_menu::run(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index bce31f0fd0..ad77caab42 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -310,6 +310,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "plugin.hideRuns" => crate::plugin_runs::any_shown(app), "imageTrace.cancelRuns" => crate::trace_runs::any_running(app), "imageTrace.hideRuns" => crate::trace_runs::any_shown(app), + "retype.cancelSearch" => crate::retype_runs::any_running(app), "file.place" | "file.export.svg" | "file.export.png" diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 2433cc0e25..8584d5133e 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -480,25 +480,28 @@ fn last_effect_dialog_and_view_toggles() { } } -/// Edit › Undo and Edit › Redo name the step in the UI language as the History panel lists it -/// (`panels::history::step_name`), including a step named after an effect whose catalog holds -/// only the effect's menu row with an ellipsis, as Japanese does for Feather. +/// Edit › Undo and Edit › Redo name the step in the UI language as the History panel lists it: a +/// step that applied an effect by the effect's name as the Effect menu shows it +/// (`i18n::effect_name`), even where the plain row of its English label holds another word, as +/// French does for Feather, and any other step by `panels::history::step_name` of its label. #[test] fn undo_and_redo_name_the_step_as_the_history_panel_does() { - let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); - crate::i18n::set_current(ja); + let fr = crate::i18n::Lang::from_code("fr").expect("fr registered"); + crate::i18n::set_current(fr); let mut app = app_with_a_rectangle(); app.run("effect.apply", json!({"effect": "stylize.feather"})).unwrap(); assert_eq!(app.session.active().unwrap().history.undo.last().map(|h| h.label.as_str()), Some("Feather")); let shown = |app: &mut VectorcraftApp, id: &'static str| shown_label(app, id).unwrap_or_else(|| panic!("{id} is not a menu item")); - let step = |template: &str, name: &str| { - let name = crate::panels::history::step_name(ja, name).unwrap_or_else(|| name.to_string()); - crate::i18n::fmt(crate::i18n::tr(ja, template), &[("name", &name)]) - }; - assert_eq!(shown(&mut app, "edit.undo"), step("Undo {name}", "Feather")); + let step = |lang, template: &str, name: &str| crate::i18n::fmt(crate::i18n::tr(lang, template), &[("name", name)]); + let feather = crate::i18n::effect_name(fr, "stylize.feather").expect("the Effect menu names Feather"); + assert_eq!(shown(&mut app, "edit.undo"), step(fr, "Undo {name}", &feather)); app.run("edit.undo", json!({})).unwrap(); - assert_eq!(shown(&mut app, "edit.redo"), step("Redo {name}", "Feather")); - assert_eq!(shown(&mut app, "edit.undo"), step("Undo {name}", "Rectangle"), "a step with a plain row"); + assert_eq!(shown(&mut app, "edit.redo"), step(fr, "Redo {name}", &feather)); + // Japanese names a rectangle in other words than English. + let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); + crate::i18n::set_current(ja); + let rectangle = crate::panels::history::step_name(ja, "Rectangle").unwrap_or_else(|| "Rectangle".to_string()); + assert_eq!(shown(&mut app, "edit.undo"), step(ja, "Undo {name}", &rectangle), "a step with a plain row"); crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(shown(&mut app, "edit.redo"), "Redo Feather"); } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7dcbb1d05d..4da3dcdc16 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -772,7 +772,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -868,7 +868,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -1175,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1514,7 +1514,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1598,7 +1598,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} 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), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; 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 item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {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); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list 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, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} 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), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; 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 item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {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); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else 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, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -2031,17 +2031,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 2622c8f966..f45209ee65 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -53,6 +53,7 @@ pub fn long_operation_busy(app: &VectorcraftApp) -> bool { || !app.plugin_runs.running.is_empty() || !app.placing.pending.is_empty() || !app.trace_runs.running.is_empty() + || crate::retype_runs::any_running(app) } /// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 543c06998e..6516f7132c 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -242,6 +242,28 @@ fn an_explicit_float_command_updates_an_existing_native_windows_geometry() { } } +/// Swatches and Color as tabs of one native window, with its OS window drawn. +fn native_tab_group(h: &mut Harness) -> ViewportId { + let viewport = h.float("swatches"); + h.app.run("window.panel.float", json!({"panel": "color", "onto": "swatches"})).unwrap(); + h.frames(3); + assert_eq!(h.viewport("color"), viewport); + viewport +} + +#[test] +fn a_group_float_of_a_tab_group_resizes_its_native_window() { + let mut h = Harness::new(); + let viewport = native_tab_group(&mut h); + let id = floating_window(layout_of(&h.app.ui), "swatches").unwrap().id; + let before = h.host.borrow().windows[&viewport].rect; + h.app.run("window.panel.float", json!({"panel": "swatches", "group": true, "width": 400})).unwrap(); + h.frames(3); + assert_eq!(floating_window(layout_of(&h.app.ui), "swatches").unwrap().id, id); + assert_eq!(h.viewport("color"), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(before.min, vec2(400.0, before.height()))); +} + /// `window.toolbar.float` with x, y moves the OS window a toolbar made with New Toolbar already has. #[test] fn floating_a_toolbar_at_a_point_moves_its_native_window() { diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 83ebf46070..27cab1fe2c 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -41,6 +41,8 @@ pub enum PanelDrag { /// panel order. #[derive(Clone, Debug, PartialEq)] pub struct SwatchRows { + /// The document whose rows the drag started on. + pub document: u64, pub grabbed: String, pub names: Vec, /// The names are colour groups. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f7b3258959..fe36fca6df 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -63,11 +63,11 @@ use craft::keymap::CommandRef; use craft::theme::Srgba; use craft::theme::variant::Tone; use craft::ui::buttons::{IconButton, Link, PopupMark}; -use craft::ui::choice::SwatchSpacing; +use craft::ui::choice::{Radio, RadioGroup, SwatchSpacing}; use craft::ui::contract::{Bind, CommandSet as _, Entry, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::{Menu, PanelMenu, PanelRow}; use craft::ui::notices::{Notice, NoticeIcon, NoticeLayout}; use craft::ui::pickers::Select; @@ -103,10 +103,22 @@ pub(crate) fn corner_radius(app: &VectorcraftApp, n: &Node) -> Option { corner_style(app, n).0 } -/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. +/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. The +/// radius is a document length ([`corner_length`]). pub(crate) fn corner_style(app: &VectorcraftApp, n: &Node) -> (Option, Option) { let partial = app.session.active().and_then(|d| d.selection.partial(n.id)); - LiveCorners::of(n).map_or((None, None), |c| c.style(&c.picked(partial))) + let Some(c) = LiveCorners::of(n) else { return (None, None) }; + let corners = c.picked(partial); + let mut radii = corners.iter().map(|k| corner_length(&c, *k)); + let radius = radii.next().filter(|first| radii.all(|r| (r - first).abs() < 1e-9)); + (radius, c.style(&corners).1) +} + +/// The radius asked for at corner `k`, as a document length, even where it draws smaller. A +/// relative radius is stored as a fraction of the corner's largest; the fields and +/// `object.setLiveShape` take lengths. +pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 { + if c.radii_relative() { c.radius(k) * c.corner(k).map_or(0.0, |c| c.max_radius()) } else { c.radius(k) } } /// One entry per corner kind, labelled as the Corners dialog labels them. @@ -214,7 +226,7 @@ fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { for (k, label, corner) in rectangle_corners() { Field::new(label).show(ui, |ui, _| { Row::new().wrap(true).show(ui, |ui, _| { - radii.push((k, NumberField::length(label, Bind::given(Some(lc.radius(k))), lengths).show(ui).edit)); + radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit)); if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) { kinds.push((k, kind)); } @@ -274,6 +286,117 @@ pub(crate) fn command_icon(id: &str) -> Option<&'static str> { } } +/// The corners that the Corners link, its pop-up and the Corner Radius field beside it edit: +/// [`picked_corners`]. +pub(crate) struct PickedCorners { + /// `object.setLiveShape`'s `items`: `{id, corners}` for each path. + pub items: Vec, + /// The radius the corners share, as a document length; None when they differ. + pub radius: Option, + /// The kind the corners share; None when they differ. + pub kind: Option, + /// Whether their paths store relative radii; None when the paths differ. + pub relative: Option, +} + +/// The picked corners of the selection: for each selected path with Live Corners, the corners +/// holding a Direct-Selected anchor, or every corner of a path selected whole. A path whose +/// selected anchors hold no corner adds none. None when no path adds a corner. +pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option { + fn shared(values: &[T], same: impl Fn(T, T) -> bool) -> Option { + let (&first, rest) = values.split_first()?; + rest.iter().all(|v| same(*v, first)).then_some(first) + } + let st = app.session.active()?; + let (mut items, mut radii, mut kinds, mut relative) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for &id in &st.selection.objects { + let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) else { continue }; + let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); + if corners.is_empty() { + continue; + } + for &k in &corners { + radii.push(corner_length(&lc, k)); + kinds.push(lc.kind(k)); + } + relative.push(lc.radii_relative()); + items.push(json!({"id": id, "corners": corners})); + } + if items.is_empty() { + return None; + } + Some(PickedCorners { + items, + radius: shared(&radii, |a, b| (a - b).abs() < 1e-9), + kind: shared(&kinds, |a, b| a == b), + relative: shared(&relative, |a, b| a == b), + }) +} + +/// Run `object.setLiveShape` with `p` (a `kind`, `radius` or `relativeRadii`) on `picked`'s +/// corners: one undo step, or none when nothing changes. `App::run` reports a failure in the +/// status bar. +pub(crate) fn set_picked_corners(app: &mut VectorcraftApp, picked: &PickedCorners, mut p: Value) { + p["items"] = json!(picked.items); + app.run("object.setLiveShape", p).ok(); +} + +/// The Corners link of the Control bar and the Properties panel: a click on it opens or closes +/// [`corners_popup`] under it. +pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui) { + let link = option_link(tl!("Corners")).tooltip(tl!("Corner options")).show(ui).response; + Popover::new(tl!("Corner options"), Bind::kept()) + .overlay(|overlay| overlay.opened_by(&link, Trigger::Click)) + .show(ui, |ui, _| corners_popup(app, ui)); +} + +/// The Corners pop-up: the corner kind, the radius (blank while the picked corners differ) and +/// the rounding, Relative or Absolute (neither while their paths differ), of the picked corners +/// ([`picked_corners`]). Each change sets them on those corners alone, in one undo step. +fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(picked) = picked_corners(app) else { return }; + let lengths = general_lengths(app); + let (mut set, mut radius) = (None, None); + Stack::new().show(ui, |ui, _| { + Field::new(tl!("Corner")).show(ui, |ui, _| { + let group = RadioGroup::new(tl!("Corner"), Bind::given(picked.kind)).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for k in CornerKind::ALL { + Radio::new(Some(k)).label(crate::dialogs::corners::kind_label(k)).show(ui); + } + }); + }); + if let Some(Some(k)) = group.output.events.committed() { + set = Some(json!({"kind": k})); + } + }); + Field::new(tl!("Radius")).show(ui, |ui, _| { + radius = Some(NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit); + }); + let rounding = RadioGroup::new(tl!("Rounding"), Bind::given(picked.relative)).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Radio::new(Some(true)).label(tl!("Relative")).show(ui); + Radio::new(Some(false)).label(tl!("Absolute")).show(ui); + }); + }); + if let Some(Some(on)) = rounding.output.events.committed() { + set = Some(json!({"relativeRadii": on})); + } + }); + // Applied after the Stack, whose body runs twice (measure, then real), as the radios' `set`. + if let Some(radius) = radius { + apply_edits(app, &radius, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); + } + if let Some(p) = set { + set_picked_corners(app, &picked, p); + } +} + /// Number of selected objects. pub(crate) fn selection_len(app: &VectorcraftApp) -> usize { app.session.active().map(|d| d.selection.len()).unwrap_or(0) diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 71788cffb4..33d27e495f 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -352,11 +352,17 @@ pub fn effect_label(id: &str) -> String { .unwrap_or_else(|| id.rsplit('.').next().unwrap_or(id).to_string()) } -/// [`effect_label`] as shown: a built-in effect's in the UI language (an `@id` row for the -/// effect's id wins over the plain row of its English label), a plug-in's as it is. +/// Is `id` one of our own effects? A plug-in's effect name comes from the plug-in and is shown as +/// it is. +fn built_in_effect(id: &str) -> bool { + catalog().iter().any(|c| c.0 == id) +} + +/// [`effect_label`] as shown: a built-in effect's name in the UI language as the Effect menu +/// shows it ([`crate::i18n::effect_name`]), a plug-in's as it is. pub(crate) fn shown_effect_label(id: &str) -> String { - match catalog().iter().find(|c| c.0 == id) { - Some(c) => crate::i18n::t_id(id, &c.1).to_string(), + match built_in_effect(id).then(|| crate::i18n::effect_name(crate::i18n::current(), id)).flatten() { + Some(name) => name, None => effect_label(id), } } @@ -429,7 +435,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let order = rows.keys(); let sel = current_sel(app, node.as_deref()); let mut selection = node.as_deref().map_or_else(Selection::default, |n| list_selection(app, n, sel)); - let list_id = ui.scope_id().with("appearance-rows"); + let document = app.session.active().map(|st| st.uid); + let list_id = ui.scope_id().with(("appearance-rows", document)); let has = node.is_some(); // A dragged fill/stroke or effect row lights Duplicate and Delete up, also with nothing picked. let dragged = craft::ui::runtime::drag::active::>(ui.ctx()) @@ -490,6 +497,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let (Some(dropped), Some(n)) = (&out.dropped, node.as_deref()) && let Some(drag) = dropped.payload::>() + && drag.list == list_id { drop_on_footer(app, n, sel, &drag.keys, dropped.index == DUPLICATE); } @@ -1778,9 +1786,10 @@ fn effects_move( pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut groups: Vec<(String, Vec<(String, String)>)> = vec![]; let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect(); - // Built-in effects in the UI language; a plug-in's by the name it gives. - let built_in = catalog().iter().map(|(id, label, menu)| (id, tl!(label), menu)); - for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.as_str(), menu))) { + // Built-in effects named as the Effect menu names them; a plug-in's by the name it gives. + let lang = crate::i18n::current(); + let built_in = catalog().iter().map(|(id, label, menu)| (id, crate::i18n::effect_name(lang, id).unwrap_or_else(|| label.clone()), menu)); + for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.clone(), menu))) { let g = menu.get(1).cloned().unwrap_or_else(|| "Other".into()); match groups.iter_mut().find(|(n, _)| *n == g) { Some((_, v)) => v.push((id.clone(), label.to_string())), diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index bfd9867950..36df059b59 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -553,7 +553,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { footer = Some(bar); }); let zone = footed.show(ui, |ui, _| { - DropAction::::new(|p| matches!(p, PanelDrag::Art { .. })).sizing(Sizing::Fill).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |p| matches!(p, PanelDrag::Art { document, .. } if *document == uid)); + drop_art.sizing(Sizing::Fill).show(ui, |ui, _| { if st.doc.assets.is_empty() { Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) .title(tl!("No assets")) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 7c1ac5c226..6804b53c4d 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1620,8 +1620,9 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// line gap, 50%, Auto alignment), Insert Aki Left and Right 0, Tsume 0, the Default character direction, /// Kashidas on, the Default digits, Adjust Horizontal and Vertical Diacritic Position 0 and the Em Box /// font height reference, whether or not Show East Asian -/// Options, Show Indic Options and Show Font Height Options are on. Inside an undo group that is -/// already open, the reset is part of that group's step. +/// Options, Show Indic Options and Show Font Height Options are on. Area type with Dynamic Text +/// (Block) on keeps its frame's Line Gap. Inside an undo group that is already open, the reset is +/// part of that group's step. fn reset_panel(app: &mut VectorcraftApp) { // Typing in progress stays an undo step of its own. end_typing(app); @@ -1630,7 +1631,8 @@ fn reset_panel(app: &mut VectorcraftApp) { app.session.begin_named_undo_group(Some("Reset Panel".into())); } let d = CharStyle::default(); - style(app, json!({"tracking": 0, "leading": "auto"})); + // Dynamic Text's Line Gap is the frame's, so the reset leaves it as it is. + style(app, json!({"tracking": 0, "leading": "auto", "keepLineGap": true})); format( app, json!({ diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 73f1296ca9..6713eb3033 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -232,6 +232,92 @@ fn leading_follows_the_paragraphs_the_type_tool_selection_covers() { } } +/// Selected area type of two equal lines with Dynamic Text (Block) on and a Line Gap of 7 pt. +fn block_app() -> (VectorcraftApp, NodeId) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let id = + app.run("text.create", json!({"x": 20, "y": 20, "size": 12, "area": {"width": 300, "height": 2000}, "text": "Hello\nHello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("type.dynamicText", json!({"on": true, "lineGap": 7})).unwrap(); + let leading = shared_leading(&app).expect("both lines share a leading"); + assert!((leading - block_text(&app, NodeId(id)).runs[0].style.size - 7.0).abs() < 1e-9); + (app, NodeId(id)) +} + +fn block_text(app: &VectorcraftApp, id: NodeId) -> vectorcraft_doc::TextObject { + match &app.session.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + } +} + +fn pick_leading(panel: &mut crate::tests::panel_harness::Panel, entry: &str) { + panel.focus("Leading"); + panel.key(egui::Key::ArrowDown, egui::Modifiers::ALT); + panel.click_role(entry, craft::ui::contract::Role::LIST_BOX_OPTION); +} + +/// Area type with Dynamic Text (Block) on: a leading typed into the Leading field moves the +/// frame's Line Gap, so the field then shows the leading typed and the lines are spaced by it. +#[test] +fn leading_typed_with_block_on_moves_the_line_gap() { + use crate::tests::panel_harness::Panel; + let (app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + let mut panel = Panel::new(app, show); + panel.type_into("Leading", "200"); + let app = panel.app(); + let t = block_text(&app, id); + assert!((t.area.line_gap - (200.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); + assert!(shared_leading(&app).is_some_and(|l| (l - 200.0).abs() < 1e-6), "the field shows {:?}", shared_leading(&app)); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!((lay.lines[1].baseline - lay.lines[0].baseline - 200.0).abs() < 1e-6, "the lines are 200 pt apart"); +} + +/// The Properties panel's Leading field does the same on Block text. +#[test] +fn leading_typed_in_properties_with_block_on_moves_the_line_gap() { + use crate::tests::panel_harness::Panel; + let (app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + let mut panel = Panel::new(app, super::super::properties::show); + panel.type_into("Leading", "150"); + let t = block_text(&panel.app(), id); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// A pick from the Leading field's list on Block text: a preset, then Auto, each moves the Line Gap. +#[test] +fn leading_picked_from_the_list_with_block_on_moves_the_line_gap() { + use crate::tests::panel_harness::Panel; + let (app, id) = block_app(); + let size = block_text(&app, id).runs[0].style.size; + let preset = vectorcraft_doc::Unit::Points.format(72.0); + let mut panel = Panel::new(app, show); + pick_leading(&mut panel, &preset); + let gap = block_text(&panel.app(), id).area.line_gap; + assert!((gap - (72.0 - size)).abs() < 1e-6, "{preset}: line gap {gap} for size {size}"); + pick_leading(&mut panel, tl!("Auto")); + let gap = block_text(&panel.app(), id).area.line_gap; + assert!(gap > 0.0 && gap < size * 0.5, "Auto: line gap {gap} for size {size}"); +} + +/// Reset Panel resets the leading to Auto and leaves Block's Line Gap, which belongs to the frame. +#[test] +fn reset_panel_with_block_on_keeps_the_line_gap() { + let (mut app, id) = block_app(); + app.run("text.setFormat", json!({"baselineShift": 3})).unwrap(); + let reset = CommandRef::with_params("ui.character.reset", json!({})); + assert!(listed(&app).contains(&reset), "the panel menu lists Reset Panel"); + fire(&mut app, &reset); + let t = block_text(&app, id); + assert_eq!(t.area.line_gap, 7.0); + assert_eq!(t.runs[0].style.baseline_shift, 0.0, "the reset ran"); +} + #[test] fn scaled_range_fields_follow_the_type_tool_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 5cc220b272..1ba94f3d4c 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -985,11 +985,15 @@ fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: } /// What the HSB picked last belongs to: the document, the selected objects or text characters, -/// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color -/// the pick stored. The wheel shows that HSB only while all of them are unchanged. +/// the appearance item, the proxy, the gradient stop or freeform point, its paint, the color the +/// pick stored, and the document's undo step. The wheel shows that HSB only while all of them are +/// unchanged. #[derive(Clone, Debug, PartialEq)] struct Owner { doc: Option, + /// The document's [`History::step`](vectorcraft_engine::History::step): another edit, an Undo + /// or a Redo changes it, also when the same color comes back. + step: Option<(u64, u64)>, selection: Vec, /// The Type tool's selected characters, when it edits the paint. text_selection: Option<(NodeId, usize, usize)>, @@ -1013,6 +1017,7 @@ impl Owner { }; Self { doc: st.map(|d| d.uid), + step: st.map(|d| d.history.step()), selection: st.map(|d| d.selection.objects.clone()).unwrap_or_default(), text_selection: super::character::text_editing(app), appearance_item: app.session.appearance_item(), @@ -1045,6 +1050,15 @@ fn recall( kept } +/// Move the record in `slot` from owner `was` to owner `now`, when `was` holds it. +fn rekey(slot: &mut Option<(Owner, [f32; 3], T)>, was: &Owner, now: &Owner) { + if let Some((owner, ..)) = slot + && owner == was + { + *owner = now.clone(); + } +} + /// The HSB a color shows on the wheel: that of its display sRGB through `cms`. pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] { rgb_to_hsb(cms.display_rgb(c)) @@ -1505,13 +1519,13 @@ fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pi let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, tgt, c)); opacity_row(app, panel, ui, tgt, &shown, cx.cms); - // 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, ..)) = &mut panel.hsb - && *remembered == was - { - *remembered = Owner::of(app, tgt, c); + // An opacity edit adds an undo step, and on a gradient stop or point it also changes the + // gradient its owner holds. The HSB, HSL and OKLCH picked last stay with the edited paint. + if let (Some(c), Some(was)) = (color, owner) { + let now = Owner::of(app, tgt, c); + rekey(&mut panel.hsb, &was, &now); + rekey(&mut panel.hsl, &was, &now); + rekey(&mut panel.oklch, &was, &now); } } else { end_opacity_drag(app, panel); diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index b3e8833076..91683cc016 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use craft::behavior::IconId; use craft::keymap::CommandRef; use craft::theme::variant::Tone; -use craft::ui::contract::{Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Stack; use craft::ui::menu::PanelRow; @@ -132,19 +132,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let opts = app.ui.css_properties_panel.options.clone(); let all = !selected && app.ui.css_properties_panel.all; let Some(shown) = shown(app, &opts, all) else { return }; - Stack::new().fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { - let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); - if shown.rules > 0 { - SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); - } else if selected { - let hint = tl!("The selected objects have no CSS of their own (see below)."); - Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } else { - let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); - Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } - }); - let notes = (shown.more > 0) + let notes: Vec<_> = (shown.more > 0) .then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one.")) .into_iter() .chain((shown.skipped > 0).then(|| { @@ -154,23 +142,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { "{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.", ) })) - .chain(shown.warnings.iter().map(|w| sentence(w))); - for n in notes { - Text::new(n).role(TypeRole::Caption).shade(Shade::Muted).show(ui); - } + .chain(shown.warnings.iter().map(|w| sentence(w))) + .collect(); let has_css = shown.rules > 0; let scope = if all { "all" } else { "selection" }; // Generate at the start edge; Export at the end edge with Copy before it. - let footer = FooterBar::actions([ + let actions = [ FooterAction::new(IconId::new("sparkles"), tl!("Generate CSS: the whole document's CSS while nothing is selected")) .pressed(all) .enabled(!selected), FooterAction::new(IconId::new("save"), if all { tl!("Export All…") } else { tl!("Export Selected CSS…") }).enabled(has_css), FooterAction::new(IconId::new("copy"), if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") }).enabled(has_css), - ]) - .at_start(1) - .show_footer(ui); - match footer.picked { + ]; + let mut picked = None; + let notes_room = (ui.available_height() / 3.0).min(72.0); + Stack::new() + .fill() + .footer(|ui, _| { + if !notes.is_empty() { + Stack::new().label(tl!("Notes")).fill_width().scroll(Scroll::vertical()).room_height(notes_room).show(ui, |ui, _| { + for note in ¬es { + Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + } + }); + } + let footer = FooterBar::actions(actions.clone()).at_start(1).show_footer(ui); + if !ui.is_sizing_pass() { + picked = footer.picked; + } + }) + .show(ui, |ui, _| { + Stack::new().label(tl!("CSS Properties")).fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { + let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); + if shown.rules > 0 { + SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); + } else if selected { + let hint = tl!("The selected objects have no CSS of their own (see below)."); + Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } else { + let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); + Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } + }); + }); + match picked { Some(0) => { crate::menus::invoke(app, GENERATE, json!({})); } @@ -311,3 +326,39 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option return None, }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + #[test] + fn generated_css_notices_keep_the_actions_in_a_short_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({ "width": 100, "height": 100 })).unwrap(); + for card in 0..12 { + let id = app.run("shape.rectangle", json!({ "x": 0, "y": 0, "width": 20, "height": 20 })).unwrap()["id"].clone(); + app.run("layer.setProps", json!({ "id": id, "name": format!("Card-{card}") })).unwrap(); + } + app.run("shape.ellipse", json!({ "x": 30, "y": 0, "width": 20, "height": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + let options = CssOptions { unnamed: false, ..CssOptions::default() }; + let styles = shown(&mut app, &options, true).unwrap(); + assert_eq!((styles.rules, styles.skipped), (12, 1)); + app.ui.css_properties_panel = CssPropertiesPanel { options, all: true }; + + let mut panel = Panel::new(app, show); + let room = egui::vec2(220.0, 220.0); + panel.room(room).frame(); + panel.frame(); + for name in ["Copy All Styles", "Export All…"] { + let action = panel.rect(name); + assert!(action.bottom() <= room.y && action.right() <= room.x, "{name} overflows the panel at {action:?}"); + assert!(panel.enabled(name), "{name} is enabled when there is CSS"); + } + let notice = panel.rect("1 unnamed object left out: name it, or turn on Unnamed Objects in the panel menu."); + assert!(notice.top() >= 0.0 && notice.bottom() <= panel.rect("Copy All Styles").top(), "the notice fits above the actions: {notice:?}"); + assert!(notice.left() >= 0.0 && notice.right() <= room.x, "the notice wraps within the panel: {notice:?}"); + } +} diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 87eb9f9880..bc98af1c4d 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -59,6 +59,15 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { clicked } +/// Whether no artwork is selected. Artboards the Artboard tool has selected are not artwork: +/// `document.info` lists them under Document whatever this says. +fn no_artwork_selected(app: &VectorcraftApp) -> bool { + match app.session.active() { + Some(st) => st.selection.objects.is_empty(), + None => true, + } +} + /// `document.info` with its categories, fetched again only when the document, the scope or the /// artboards the Artboard tool has selected change. A frame that fetches nothing returns the stored /// result without copying it and stores nothing; a failed fetch leaves the stored result as it was. @@ -85,6 +94,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone(); let mut copy = None; Stack::new().show(ui, |ui, _| { + if sel_only && no_artwork_selected(app) { + Text::new(tl!("(No artwork selected)").to_string()).shade(Shade::Muted).show(ui); + } let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice); let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str()); for (n, s) in shown.enumerate() { @@ -919,4 +931,79 @@ mod tests { assert_eq!(in_lang("de", &json!({"type": "grid", "rows": 1, "cols": 3, "instances": 3})), "Rasterwiederholung, 1 Zeile × 3 Spalten"); assert_eq!(repeat_value(&json!({"type": "spiral", "instances": 2})), None); } + + /// Objects rows the panel paints with Selection Only `on`, the Objects category shown. + fn objects_panel(app: &mut VectorcraftApp, on: bool) -> String { + app.ui.doc_info.selection_only = on; + app.ui.doc_info.category = "objects".to_string(); + crate::tests_labels::painted_text(app, show) + } + + /// With Selection Only off, Objects counts every object in the document. + #[test] + fn test_doc_info_counts_entire_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 80, "y": 10, "width": 30, "height": 20})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 80, "text": "Hi"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let text = objects_panel(&mut app, false); + assert!(text.contains("Paths\n2\n") && text.contains("Text Objects\n1\n"), "{text}"); + assert!(!text.contains("(No artwork selected)"), "{text}"); + } + + /// Selection Only counts the selected object and what it holds, and an empty selection says so. + #[test] + fn test_doc_info_selection_only_toggles_and_filters_counts() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let path = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap()["id"].clone(); + let text_id = app.session.execute("text.create", &json!({"x": 10, "y": 80, "text": "Hi"})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [text_id]})).unwrap(); + let text = objects_panel(&mut app, true); + assert!(text.contains("Text Objects\n1\n") && !text.contains("Paths\n"), "the selected type only: {text}"); + app.session.execute("select.set", &json!({"ids": [path]})).unwrap(); + let path_only = objects_panel(&mut app, true); + assert!(path_only.contains("Paths\n1\n") && !path_only.contains("Text Objects\n"), "the selected path only: {path_only}"); + app.session.execute("select.none", &json!({})).unwrap(); + let empty = objects_panel(&mut app, true); + assert!(empty.contains("(No artwork selected)") && !empty.contains("Paths\n") && !empty.contains("Text Objects\n"), "{empty}"); + } + + /// With Selection Only on, an artboard the Artboard tool has selected still shows under + /// Document when no artwork is selected, and the empty-state message speaks of artwork only. + #[test] + fn test_doc_info_selection_only_keeps_selected_artboard() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([1])); + app.ui.doc_info.selection_only = true; + app.ui.doc_info.category = "document".to_string(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Back"), "the selected artboard: {text}"); + assert!(!text.contains("(No selection)"), "no generic empty state: {text}"); + assert!(text.contains("(No artwork selected)"), "{text}"); + } + + /// The panel menu's Selection Only item toggles `selection_only` and updates its checked state. + #[test] + fn test_doc_info_panel_menu_toggles_state() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let check = |app: &VectorcraftApp| { + let mut states = CommandStates::default(); + menu_states(app, &mut states); + states.get(&CommandRef::new("ui.docInfo.selectionOnly")).and_then(CommandState::is_checked) + }; + assert_eq!(check(&app), Some(false)); + run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap(); + assert_eq!(check(&app), Some(true)); + run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap(); + assert_eq!(check(&app), Some(false)); + } } diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index e2c724fe2f..c55c06b1c3 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -13,9 +13,9 @@ use std::sync::Arc; use craft::behavior::CanvasTransform; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Divider, Shade, Text}; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom}; use craft::ui::pickers::Select; @@ -200,30 +200,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } // The highlighted art takes the theme's error colour. let highlight = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.solid); + let compact = ui.available_width() < Env::of(ui).tokens.size.plot.width; let mut set = app.ui.flattener_preview.clone(); let mut refresh_now = false; - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { refresh_now = Button::new(tl!("Refresh")).tooltip(tl!("Preview the document as it is now")).show(ui).clicked(); let entries = Highlight::ALL.map(|h| Entry::new(h, h.label())); - Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries).show(ui); + let picker = Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { Text::new(tl!("Overprints:")).shade(Shade::Muted).show(ui); let entries = Overprints::ALL.map(|o| Entry::new(o, o.label())); - Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries).show(ui); + let picker = Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + let preset_id = ui.scope_id().with("flattener-preset-row"); + let mut preset = |ui: &mut Ui| { Text::new(tl!("Preset:")).shade(Shade::Muted).show(ui); let names = flatten::preset_names(app); - let mut fields = DialogFields::from_pairs([("preset", set.preset.clone())]); - flatten::preset_picker(ui, &mut fields, "preset", &names, custom(app)); - if let Some(name) = fields.text("preset") - && name != set.preset + let is_custom = custom(app); + let current = if is_custom { String::new() } else { set.preset.clone() }; + let mut fields = DialogFields::from_pairs([("preset", current.clone())]); + flatten::preset_picker(ui, &mut fields, "preset", &names, is_custom); + if !ui.is_sizing_pass() + && let Some(name) = fields.text("preset").filter(|name| *name != current) && let Some(p) = app.session.flattener_preset(name) { (set.preset, set.options) = (p.name, p.options); } - }); + }; + if compact { + Stack::new().id(preset_id).fill_width().show(ui, |ui, _| preset(ui)); + } else { + Row::new().id(preset_id).fill_width().wrap(true).show(ui, |ui, _| preset(ui)); + } if set.show_options { Divider::horizontal().show(ui); let params = flatten::option_params(&[], ""); @@ -285,11 +298,16 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, // At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit. let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height()); let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32); - let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) + let pane = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) .aspect(ASPECT) .click_centres(false) - .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")) - .show(ui); + .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")); + let out = if w < Env::of(ui).tokens.size.plot.width { + let (_, room) = ui.allocate_space(vec2(w, w / ASPECT)); + pane.show_at(ui, room) + } else { + pane.show(ui) + }; *view = match out.clicked { Some(at) => { let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 }; @@ -484,6 +502,65 @@ mod tests { assert_eq!(back.flattener_preview, app.ui.flattener_preview); } + #[test] + fn the_flattener_selectors_and_preview_fit_a_narrow_dock() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + let width = 100.0; + panel.room(vec2(width, 520.0)).frame(); + panel.frame(); + for name in ["Highlight", "Overprints", "Preset:"] { + let rect = panel.rect_role(name, Role::COMBO_BOX); + assert!(rect.left() >= 0.0 && rect.right() <= width, "{name} overflows the dock at {rect:?}"); + } + let pane = panel.rect("Flattener Preview"); + assert!(pane.left() >= 0.0 && pane.right() <= width, "preview overflows the dock at {pane:?}"); + } + + #[test] + fn the_flattener_selectors_keep_their_caption_rows_when_the_panel_is_wide() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + panel.room(vec2(440.0, 600.0)).frame(); + panel.frame(); + for (caption, role, picker) in + [("Refresh", Role::BUTTON, "Highlight"), ("Overprints:", Role::LABEL, "Overprints"), ("Preset:", Role::LABEL, "Preset:")] + { + let row = panel.rect_role(caption, role); + let field = panel.rect_role(picker, Role::COMBO_BOX); + assert!(field.left() >= row.right() && field.center().y >= row.top() && field.center().y <= row.bottom(), "{picker} is below {caption}"); + } + } + + #[test] + fn the_compact_flattener_applies_a_preset_and_refreshes_the_snapshot() { + use craft::ui::contract::Role; + + let mut app = app(); + command(&mut app, &json!({"preset": "high", "options": {"balance": 12}})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.room(vec2(100.0, 520.0)).frame(); + panel.frame(); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.app().ui.flattener_preview.options.balance, 12.0); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.click("High Resolution"); + let expected = FlattenOptions::preset("high").unwrap(); + assert_eq!(panel.app().ui.flattener_preview.options, expected); + panel.app().run("select.all", json!({})).unwrap(); + panel.app().run("transparency.set", json!({"opacity": 100})).unwrap(); + assert!(stale(&panel.app()), "the live document changed"); + panel.click("Refresh"); + assert!(!stale(&panel.app()), "Refresh takes a new snapshot"); + let well = panel.rect("Flattener Preview"); + panel.click_at(well.center()); + assert!(!panel.app().flattener_preview.view.fit, "the compact preview still zooms"); + } + /// The panel in a fixture, and the preview pane's bounds. fn shown_pane() -> (std::rc::Rc>, craft::ui::testing::Fixture, egui::Rect) { let app = std::rc::Rc::new(std::cell::RefCell::new(app())); diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index b2131ae600..fbe030d45a 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -51,7 +51,8 @@ use egui::{Pos2, Ui}; use serde_json::{Value, json}; use vectorcraft_color::gradient::{MAX_REPEATS, MIN_STOPS, insert_stop, move_stop, remove_stop, set_midpoint}; use vectorcraft_color::{Color, Freeform, FreeformMode, Gradient, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; -use vectorcraft_doc::{NodeId, StrokeGradientMode}; +use vectorcraft_doc::StrokeGradientMode; +use vectorcraft_engine::StopOwner; use vectorcraft_tools::params::stops_json; // PLAN: assumed hub-w2's `panels::{proxy(app, ui), part_hidden(app, key), set_part_hidden(app, key, on), live_run, Live}` (co.A2, op.A5). @@ -92,9 +93,10 @@ const MENU_DELETE_PRESET: &str = "ui.gradient.deletePreset"; /// The panel's view state that lives only while the app runs (`app.ui.gradient_panel`). #[derive(Clone, Debug, Default)] pub struct GradientUi { - /// The selected midpoint diamond and the object it was picked on: it stands while no stop is - /// selected and that object is still the first selected. - pub(crate) mid_selected: Option<(usize, Option)>, + /// The selected midpoint diamond and the gradient it was picked on: it stands while no stop is + /// selected and the active proxy still shows that gradient + /// ([`vectorcraft_engine::Session::gradient_owner`]). + pub(crate) mid_selected: Option<(usize, StopOwner)>, /// The stops of the gradient the slider's open gesture began from, from its `Begin` until its /// `Commit` or `Cancel`. Every preview restarts from the interaction's snapshot and /// `paint.editGradient` sorts the stops, so the gradient shown mid-gesture is the last preview @@ -282,11 +284,11 @@ fn gradient_swatches(app: &VectorcraftApp) -> Vec<(String, GradientPaint)> { .collect() } -/// The selected midpoint diamond: kept for the object it was picked on, and given up when a stop -/// is selected. +/// The selected midpoint diamond: kept for the gradient it was picked on, as a selected stop is +/// ([`vectorcraft_engine::Session::gradient_owner`]), and given up when a stop is selected. fn selected_mid(app: &VectorcraftApp, stops: usize) -> Option { let (i, owner) = app.ui.gradient_panel.mid_selected?; - (app.session.selected_stop().is_none() && i + 1 < stops && owner == first_id(app)).then_some(i) + (app.session.selected_stop().is_none() && i + 1 < stops && owner == app.session.gradient_owner()).then_some(i) } /// A stored fraction as the percent a field shows, without the `f32` noise (`0.3` is `30`, not `30.000001`). @@ -294,10 +296,6 @@ fn percent(v: f32) -> f64 { (f64::from(v) * 1e6).round() / 1e4 } -fn first_id(app: &VectorcraftApp) -> Option { - app.session.active().and_then(|d| d.selection.objects.first().copied()) -} - // ---------- UI ---------- pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -829,7 +827,7 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra if out.selected != selected && (events.is_empty() || events.committed().is_some()) { match out.selected { Some(StopRef::Midpoint(_, m)) => { - app.ui.gradient_panel.mid_selected = Some((m, first_id(app))); + app.ui.gradient_panel.mid_selected = Some((m, app.session.gradient_owner())); if app.session.selected_stop().is_some() { select_stop(app, None); } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index f4b57b8c8b..040031e59a 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -3,6 +3,7 @@ use std::rc::Rc; use craft::ui::testing::{Fixture, Target}; use egui::{Key, Modifiers, Pos2, pos2, vec2}; +use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; use super::*; @@ -205,6 +206,56 @@ fn a_selected_diamond_shows_and_sets_its_midpoint_in_location() { assert_eq!(rig.number("Location"), Some(0.0), "the stop's location again"); } +/// A diamond picked on the selected object's gradient is not selected on another gradient the +/// panel shows with that object still selected: the Live Paint Bucket's, or the stroke's after the +/// proxy toggles. Going back to the object's fill selects it again. +#[test] +fn a_picked_diamond_stays_with_the_gradient_it_was_picked_on() { + let stops = json!([{"offset": 0, "color": "#ffffff", "midpoint": 0.3}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("paint.setStroke", json!({"gradient": {"kind": "radial"}})).unwrap(); + app.session.fill_active = true; + let mut rig = Rig::new(app); + rig.click("Midpoint 1"); + let mid = |rig: &Rig| selected_mid(&rig.app(), 2); + assert_eq!(mid(&rig), Some(0), "the diamond is picked"); + { + let mut app = rig.app(); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"kind": "radial"}})).unwrap(); + } + rig.fixture.settle(); + assert_eq!(mid(&rig), None, "the bucket's gradient"); + rig.app().select_tool("selection"); + rig.fixture.settle(); + assert_eq!(mid(&rig), Some(0), "the object's fill again"); + rig.app().session.fill_active = false; + rig.fixture.settle(); + assert_eq!(mid(&rig), None, "the object's stroke"); +} + +/// Dragging the document's tab along the strip keeps its selected stop and its picked diamond +/// selected: both stay with the document, not with the tab it was in. +#[test] +fn a_selected_stop_and_a_picked_diamond_stay_selected_when_the_document_tab_moves() { + let stops = json!([{"offset": 0, "color": "#ffffff", "midpoint": 0.3}, {"offset": 1, "color": "#000000"}]); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.run("document.move", json!({"to": 0})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1), "the stop stays selected in the moved tab"); + let mut rig = Rig::new(app); + rig.click("Midpoint 1"); + assert_eq!(selected_mid(&rig.app(), 2), Some(0), "the diamond is picked"); + rig.app().run("document.move", json!({"to": 1})).unwrap(); + rig.fixture.settle(); + assert_eq!(selected_mid(&rig.app(), 2), Some(0), "the diamond stays picked in the moved tab"); + assert_eq!(rig.number("Location"), Some(30.0), "Location still shows the midpoint"); +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored (the field's value times the mirror's sign). #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index a1f3dabb97..1d089378d3 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -56,6 +56,13 @@ use crate::panel_drag::PanelDrag; /// A style of the panel: its name, which is unique in a document. pub(crate) type StyleKey = String; +/// A document's graphic style dragged out to the canvas. +#[derive(Clone, Debug)] +pub(crate) struct StyleDrag { + pub(crate) document: u64, + pub(crate) name: StyleKey, +} + /// The panel's views (`ui.panelView {panel: "graphicStyles", view}`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -477,6 +484,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The browser's own state (an open rename field, the scroll position) is kept per document. let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); let list = PresetBrowser::::list_id(browser_id); + let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid).is_some(); // A style dragged from this panel's list. let ours = move |drag: &ListDrag| drag.list == list; let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); @@ -516,11 +524,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .selection(Bind::bound(&mut panel.selection)) .view_lock(view.preset_view()) .reorder(PresetReorder::items()) + .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, name: drag.grabbed.clone() })) .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) - .takes_drop(PresetDrop::new::(DropPlace::Between, |drag, _| dropped_object(drag).is_some())) - .takes_drop(PresetDrop::new::(DropPlace::Onto, |drag, _| dropped_object(drag).is_some())) + .takes_drop(PresetDrop::new::(DropPlace::Between, takes_object)) + .takes_drop(PresetDrop::new::(DropPlace::Onto, takes_object)) .takes_drop(PresetDrop::new::>( DropPlace::Onto, |drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)), @@ -599,11 +608,11 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent>) { } } -/// The object whose look a dropped payload carries: the first of the art dragged off the canvas, or the Appearance -/// panel's object. -fn dropped_object(drag: &PanelDrag) -> Option { +/// The object whose look a dropped payload carries: the first of the art dragged from this document, or the +/// Appearance panel's object. +fn dropped_object(drag: &PanelDrag, uid: u64) -> Option { match drag { - PanelDrag::Art { ids, .. } => ids.first().copied(), + PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(), PanelDrag::Appearance(id) => Some(*id), _ => None, } @@ -615,7 +624,7 @@ fn dropped(app: &mut VectorcraftApp, at: &DropAt, payload: &DropPayloa DropAt::Onto(name) => Some(name.as_str()), _ => None, }; - let object = payload.get::().and_then(dropped_object); + let object = app.session.active().and_then(|st| dropped_object(payload.get::()?, st.uid)); let style = payload.get::>().map(|drag| drag.grabbed.as_str()); drop_on(app, onto, object, style, alt); } @@ -1090,6 +1099,24 @@ mod tests { app.session.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect() } + #[test] + fn a_dragged_graphic_style_carries_the_source_document_to_the_canvas() { + use craft::ui::runtime::drag; + use craft::ui::testing::Fixture; + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Dragged Style"})).unwrap(); + let document = app.session.active().unwrap().uid; + let app = RefCell::new(app); + let mut fixture = Fixture::new(move |ui| show(&mut app.borrow_mut(), ui)); + fixture.room(egui::vec2(300.0, 600.0)).settle(); + let from = fixture.by_label("Dragged Style").unwrap().center(); + fixture.drag_hold_at(from, egui::vec2(0.0, 40.0)); + let carried = drag::active::(fixture.ctx()).expect("the Graphic Styles browser supplies the canvas payload"); + assert_eq!(carried.document, document); + assert_eq!(carried.name, "Dragged Style"); + } + fn doc(app: &VectorcraftApp) -> Document { (*app.session.active().unwrap().doc).clone() } @@ -1322,7 +1349,7 @@ mod tests { let n = names(&app); let document = app.session.active().unwrap().uid; for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] { - drop_on(&mut app, Some("Red"), dropped_object(&payload), None, true); + drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true); let d = doc(&app); assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green); assert_eq!(d.node(oval).unwrap().extras().graphic_style, d.graphic_style("Red").map(|g| g.id)); @@ -1339,6 +1366,54 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), steps); } + #[test] + fn graphic_styles_accepts_artwork_only_from_its_document() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 25, "y": 25, "width": 55, "height": 55})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let second = app.session.active().unwrap().selection.objects[0]; + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + let before = names(&app); + assert!(app.session.set_active(0)); + + let mut p = PanelHarness::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Drop Target").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphic Styles accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphic Styles withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(names(&p.app()), before, "the foreign drop creates no style from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Drop Target", egui::Modifiers::NONE); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a same-document drop still makes a style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index ddd4fd7887..7650b4d79c 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -37,10 +37,15 @@ pub fn step_name(lang: crate::i18n::Lang, label: &str) -> Option { /// A step's name in `lang`. A name made from a template (`Apply {name}`, /// [`vectorcraft_engine::HistoryEntry::named`]) takes the template's plain row with the name in its /// placeholder. A name VectorCraft gives is shown in `lang`, and any other name is shown as the -/// document holds it. It returns `None` when the catalog has no row for the template. Any other step -/// takes [`step_name`] of its label. +/// document holds it. It returns `None` when the catalog has no row for the template. A step that +/// applied or edited a built-in effect ([`vectorcraft_engine::HistoryEntry::effect`]) takes the +/// effect's name as the Effect menu shows it ([`crate::i18n::effect_name`]), `None` when the +/// catalog has no row for it. Any other step takes [`step_name`] of its label. pub fn entry_name(lang: crate::i18n::Lang, h: &vectorcraft_engine::HistoryEntry) -> Option { - use crate::i18n::{fmt, has, label_or_name, tr}; + use crate::i18n::{effect_name, fmt, has, has_effect_name, label_or_name, tr}; + if let Some(effect) = h.effect() { + return has_effect_name(lang, effect).then(|| effect_name(lang, effect)).flatten(); + } match h.named() { Some(n) => has(lang, n.template).then(|| fmt(tr(lang, n.template), &[("name", label_or_name(lang, &n.name, n.built_in))])), None => step_name(lang, &h.label), @@ -329,20 +334,97 @@ mod tests { assert_eq!(names(&app)[rows.len() - 6..rows.len() - 4], ["Apply Body", "Apply {name}"]); } - /// A step named after an effect whose catalog row has only the menu label with its ellipsis - /// takes that row's translation without the ellipsis; a name with no row has none. + /// A step that applies no effect, named like a menu item (Object › Path › Clean Up…), takes its + /// plain row, else the menu item's row without the ellipsis; a name with no row has none. #[test] - fn effect_steps_read_the_menu_row() { - let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); - for effect in ["Revolve", "Feather"] { - let menu_row = - crate::i18n::has(ja, &format!("{effect}…")).then(|| crate::i18n::tr(ja, &format!("{effect}…")).trim_end_matches('…').to_string()); - let plain_row = crate::i18n::has(ja, effect).then(|| crate::i18n::tr(ja, effect).to_string()); - assert_eq!(step_name(ja, effect), plain_row.or(menu_row), "{effect}"); + fn plain_steps_read_the_menu_row_and_unknown_steps_have_no_name() { + for lang in crate::i18n::Lang::all() { + let menu_row = crate::i18n::has(lang, "Clean Up…").then(|| crate::i18n::tr(lang, "Clean Up…").trim_end_matches('…').to_string()); + let plain_row = crate::i18n::has(lang, "Clean Up").then(|| crate::i18n::tr(lang, "Clean Up").to_string()); + assert_eq!(step_name(lang, "Clean Up"), plain_row.or(menu_row), "{}", lang.code()); } + let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); assert_eq!(step_name(ja, "No Such Step"), None); } + /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// names the step that applied it, and the Appearance panel its row, with the text of its + /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its + /// menu label with the ellipsis. + #[test] + fn effects_have_the_same_name_in_history_appearance_and_the_effect_menu() { + let mut app = app_with_two_rectangles(); + // The step each effect that applies to a rectangle with its defaults records. + let mut steps = Vec::new(); + for e in vectorcraft_effects::effect_catalog() { + if app.session.execute("effect.apply", &json!({ "effect": e.id })).is_ok() { + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(e.id), "{} names its step after the effect", e.id); + steps.push((e, h)); + app.session.execute("edit.undo", &json!({})).unwrap(); + } + } + assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); + let mut differ = Vec::new(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + for (e, h) in &steps { + let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; + let item = crate::menus::shown_label(&app, cmd, &json!({ "effect": e.id }), e.label); + let menu = item.trim_end_matches('…'); + let row = crate::i18n::tr_id(lang, e.id, e.label).trim_end_matches('…').to_string(); + let step = shown(h); + let shown_row = super::super::appearance::shown_effect_label(e.id); + if menu != row || step != menu || shown_row != menu { + differ.push(format!("{} {}: catalog {row:?}, menu {menu:?}, History {step:?}, Appearance {shown_row:?}", lang.code(), e.id)); + } + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(differ.is_empty(), "{differ:#?}"); + } + + /// A step another command names like an effect (Object › Transform's `Transform`, the name of + /// Distort & Transform › Transform) keeps its own name in every language. + #[test] + fn a_step_named_like_an_effect_keeps_its_own_name() { + let mut app = app_with_two_rectangles(); + app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); + for lang in crate::i18n::Lang::all() { + assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); + } + } + + /// The Feather dialog's preview, kept with OK, records a step that History and Edit › Undo and + /// Redo name as the Effect menu names Feather, in French as in English. + #[test] + fn an_effect_kept_from_its_dialog_preview_is_named_after_the_effect() { + let fr = crate::i18n::Lang::from_code("fr").expect("fr registered"); + let mut app = crate::testing::windowed(app_with_two_rectangles()); + crate::i18n::set_current(fr); + let item = crate::menus::shown_label(&app, "effect.dialog", &json!({ "effect": "stylize.feather" }), "Feather…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + let menu = item.trim_end_matches('…').to_string(); + let ctx = app.ui_ctx.clone().expect("a window"); + app.run("effect.dialog", json!({ "effect": "stylize.feather", "item": null })).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.in_interaction(), "the dialog previews"); + let id = app.effect_dialogs.effect.as_ref().expect("the Feather dialog is open").id; + app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.effect_dialogs.effect.is_none(), "OK closed the dialog"); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); + app.session.execute("edit.undo", &json!({})).unwrap(); + let undone = app.session.active().unwrap().history.redo.last().cloned().unwrap(); + crate::i18n::set_current(fr); + let names = (shown(&h), shown(&undone)); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(names, (menu.clone(), menu), "the step, and the step undone"); + } + fn app_with_two_rectangles() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 0dce28aaa8..afd294a0e5 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -14,21 +14,26 @@ use std::sync::Arc; // PLAN: assumed import paths of the framework items below: `craft::ui::primitives::IconId`, // `craft::ui::runtime::commands::{CommandState, CommandStates}`, `craft::ui::menu::PanelRow`, // `craft::ui::patterns::presets::*`, `crate::edits` (widgets-w13) and `crate::chrome::rank` (chrome-w16). -use craft::behavior::IconId; +use craft::behavior::{IconId, Metrics, Proposal, ScrollPos, Sense}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, IconButton, SplitButton, SplitMenu, ToggleButton}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{ + Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Entry, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, +}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, SliderField, SliderFieldLayout}; -use craft::ui::layout_components::Row; +use craft::ui::layout::BodyLayout; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::Env; use craft::ui::sections::Section; +use craft::ui::style::{ComponentStyle, StyleCx}; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; @@ -786,7 +791,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { st.preset = "Default".into(); st.params = list.presets.first().map(|p| p.1.clone()).unwrap_or_default(); } - let (is_trace, is_image, any_trace) = (t.is_trace, t.is_image, t.any_trace); // The saved preset changes since the last frame apply to the panel's settings before the selected object's // settings, which `sync_with_object` resolves against every change, are adopted. follow_preset_changes(app, &mut st, &list.presets); @@ -794,6 +798,135 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes) }; + let preview = app.ui.image_trace_preview; + let mut actions = (false, false, false); + let stack = Stack::new().label(tl!("Image Trace")).fill().scroll(Scroll::vertical()); + let env = Env::of(ui); + let settings_row = env.tokens.size.control.md + env.tokens.space.gap.row; + let footer = Stack::new().id_salt("trace-footer-measure").measure_in(ui, Proposal::Width(ui.available_width()), |ui, _| { + show_footer(ui, preview, &t); + }); + let compact_offset = ui.scope_id().with("trace-compact-offset"); + let settings = if ui.available_height() >= footer.y + settings_row { + if !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.remove::(compact_offset)); + } + stack.footer(|ui, _| actions = show_footer(ui, preview, &t)).show(ui, |ui, _| show_settings(app, ui, &mut st, &list, &t)) + } else { + // When the footer moves into the scroll area, start with its actions in view. + let before = ui.ctx().data(|data| data.get_temp(compact_offset)).unwrap_or_default(); + let mut offset = before; + let shown = CompactSettings::new(Bind::bound(&mut offset)).show(ui, |ui, _| { + actions = show_actions(ui, preview, &t); + Divider::horizontal().show(ui); + show_settings(app, ui, &mut st, &list, &t) + }); + if offset != before && !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.insert_temp(compact_offset, offset)); + } + shown + }; + let (mut retrace, held) = settings.inner.unwrap_or_default(); + let (preview_toggled, trace_clicked, expand_clicked) = actions; + if !ui.is_sizing_pass() { + hold_source(app, t.any_trace && held); + } + if preview_toggled { + run_reporting(app, "imageTrace.preview", json!({})); + } + if trace_clicked { + trace(app, &mut st); + } + if expand_clicked { + run_reporting(app, "imageTrace.expand", json!({})); + } + // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is + // traced with the settings that waited in the panel. With no Image Trace object selected, it is + // traced when it is selected again. An object whose settings waited while another object was + // selected is traced when it is selected again with Preview on. + let preview = app.ui.image_trace_preview; + retrace |= preview && (st.preview_off || restored) && t.is_trace && st.params != st.synced["params"]; + if t.is_trace || !preview { + st.preview_off = !preview; + } + cancel_disabled_ignore_sampler(app, &st.params); + if retrace && t.is_trace && preview { + trace(app, &mut st); + } + app.ui.image_trace_panel.shown = st; +} + +/// The very short layout needs a bound offset so returning to it shows the actions first. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(container, unregistered)] +struct CompactSettings<'a> { + #[common] + common: Common, + #[container] + props: ContainerProps, + offset: Bind<'a, ScrollPos>, +} + +impl<'a> CompactSettings<'a> { + fn new(offset: Bind<'a, ScrollPos>) -> Self { + let props = ContainerProps::new().sizing(Sizing::Fill).layout(BodyLayout::stack()).scroll(Scroll::vertical()); + Self { common: Common::new(), props, offset }.label(tl!("Image Trace")) + } +} + +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct CompactSettingsStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for CompactSettings<'_> { + const ROLE: Role = Role::GROUP; + type Style = CompactSettingsStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: CompactSettingsStyleKey) -> CompactSettingsStyle { + CompactSettingsStyle { metrics: Metrics::new() } + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn scroll(&mut self) -> Option> { + Some(self.offset.reborrow()) + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +impl Container for CompactSettings<'_> {} + +fn show_footer(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + Divider::horizontal().show(ui); + show_actions(ui, preview, target) +} + +fn show_actions(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + let mut value = preview; + let mut trace_clicked = false; + let mut expand_clicked = false; + Row::new().wrap(true).show(ui, |ui, _| { + Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); + let can_trace = target.is_trace || target.is_image; + let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); + if !can_trace { + trace_button = trace_button.tooltip(tl!("Select an image to trace")); + } + trace_clicked = trace_button.show(ui).clicked(); + expand_clicked = Button::new(tl!("Expand")).enabled(target.any_trace).show(ui).clicked(); + }); + (value != preview, trace_clicked, expand_clicked) +} + +fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: &PresetList, t: &Target) -> (bool, bool) { let mut retrace = false; // A preset button chooses its preset as the Preset row does; the button of the panel's @@ -804,7 +937,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut on = was; ToggleButton::new(label, Bind::bound(&mut on)).tooltip(preset_label(name)).show(ui); if on && !was { - retrace |= choose_preset(&mut st, &list.presets, name); + retrace |= choose_preset(st, &list.presets, name); } } }); @@ -824,7 +957,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); for event in preset_row.events { match event { - NamedPresetEvent::Apply(name) => retrace |= choose_preset(&mut st, &list.presets, &name), + NamedPresetEvent::Apply(name) => retrace |= choose_preset(st, &list.presets, &name), NamedPresetEvent::Create { name, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": name, "params": st.params })), NamedPresetEvent::Rename { key, text, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": key, "newName": text })), NamedPresetEvent::Delete(name) => run_reporting(app, "imageTrace.presets.delete", json!({ "name": name })), @@ -845,21 +978,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Row::new().show(ui, |ui, _| { picked = view_pick(ui, st.view); let tip = tl!("Press and hold to view the source image"); - held = - IconButton::new(IconId::new("eye")).label(tip).tooltip(tip).selected(app.ui.trace_hold_source.is_some()).enabled(any_trace).show(ui).held; + held = IconButton::new(IconId::new("eye")) + .label(tip) + .tooltip(tip) + .selected(app.ui.trace_hold_source.is_some()) + .enabled(t.any_trace) + .show(ui) + .held; }); if let Some(v) = picked { st.view = v; - if any_trace { + if t.any_trace { set_view(app, v); } } - hold_source(app, any_trace && held); split_row(app, ui); let data = RowsData::of(app); let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); - let sampler = Sampler { enabled: is_trace || is_image, armed: app.ui.trace_ignore_sampler.is_some() }; + let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; let advanced = Section::new(tl!("Advanced")) .open(Bind::bound(&mut app.ui.image_trace_advanced)) .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) @@ -880,7 +1017,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { cancel_ignore_sampler(app, true); } - Divider::horizontal().show(ui); if let Some((p, a, c)) = st.info { Text::new(crate::i18n::fmt( tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"), @@ -889,43 +1025,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .shade(Shade::Muted) .show(ui); } - let (mut preview_toggled, mut trace_clicked, mut expand_clicked) = (false, false, false); - Row::new().show(ui, |ui, _| { - let preview = app.ui.image_trace_preview; - let mut value = preview; - Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); - preview_toggled = value != preview; - let can_trace = is_trace || is_image; - let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); - if !can_trace { - trace_button = trace_button.tooltip(tl!("Select an image to trace")); - } - trace_clicked = trace_button.show(ui).clicked(); - expand_clicked = Button::new(tl!("Expand")).enabled(any_trace).show(ui).clicked(); - }); - if preview_toggled { - run_reporting(app, "imageTrace.preview", json!({})); - } - if trace_clicked { - trace(app, &mut st); - } - if expand_clicked { - run_reporting(app, "imageTrace.expand", json!({})); - } - // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is - // traced with the settings that waited in the panel. With no Image Trace object selected, it is - // traced when it is selected again. An object whose settings waited while another object was - // selected is traced when it is selected again with Preview on. - let preview = app.ui.image_trace_preview; - retrace |= preview && (st.preview_off || restored) && is_trace && st.params != st.synced["params"]; - if is_trace || !preview { - st.preview_off = !preview; - } - cancel_disabled_ignore_sampler(app, &st.params); - if retrace && is_trace && preview { - trace(app, &mut st); - } - app.ui.image_trace_panel.shown = st; + (retrace, held) } /// The panel menu's rows: Release and Expand act on the selected Image Trace objects. diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index b72c13639d..3935cbe8c2 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -99,6 +99,90 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp { app } +fn scroll_settings(panel: &mut Panel, dy: f32) { + panel.scroll_at(egui::pos2(30.0, 30.0), dy); + panel.advance(1.0); + panel.frame(); +} + +#[test] +fn preview_trace_and_expand_stay_reachable_in_a_compact_panel() { + let mut app = traced_app(); + app.run("imageTrace.release", json!({})).unwrap(); + app.ui.image_trace_advanced = true; + let source = first_selected(&app).unwrap(); + assert!(matches!(source.kind, NodeKind::Image(_))); + let mut panel = panel_over(app); + assert!(panel.rect_role("Image Trace", craft::ui::contract::Role::GROUP).is_positive()); + for size in [egui::vec2(148.0, 480.0), egui::vec2(240.0, 170.0), egui::vec2(148.0, 170.0)] { + panel.room(size); + panel.frame(); + panel.frame(); + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for label in ["Preview", "Trace", "Expand"] { + assert!(panel.in_view(label), "{label} is clipped at {size:?}"); + let rect = panel.rect(label); + assert!(room.contains_rect(rect), "the whole {label} control {rect:?} fits at {size:?}"); + } + assert!(panel.enabled("Trace")); + assert!(!panel.enabled("Expand")); + } + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview); + + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the settings scroll"); + assert_eq!(panel.rect("Trace"), action, "scrolling settings leaves the action in place"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "scrolling reaches the end of Advanced"); + + panel.click("Trace"); + assert!(selected_trace(&panel.app()).is_some()); + assert!(panel.enabled("Expand")); + panel.click("Expand"); + assert!(selected_trace(&panel.app()).is_none()); + assert!(!is_trace(&first_selected(&panel.app()).unwrap())); + panel.app().run("edit.undo", json!({})).unwrap(); + assert!(selected_trace(&panel.app()).is_some()); + + // A single action row needs less height than the wrapped footer in the narrow panel. + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.frame(); + scroll_settings(&mut panel, 1000.0); + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the short settings viewport scrolls"); + assert!(panel.in_view("Trace")); + assert_eq!(panel.rect("Trace"), action, "a short panel still pins the footer when the actions fit on one line"); + + // Shorten the panel while the settings-only body remains scrolled to Advanced. + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "Preview starts in view in a very short panel"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + scroll_settings(&mut panel, -1000.0); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "a very short panel still scrolls to the last setting"); + + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "shrinking a second time starts at the actions"); +} + #[test] fn sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source() { let mut app = traced_app(); diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index 1b9bdadd43..9d2eb797b9 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -33,10 +33,12 @@ const SQUARE_SIDE: f32 = 7.0; /// The side of the square of a row that holds selected art. const HELD_SIDE: f32 = 4.0; -/// The selected art a row's selection square carries to another row: the selected objects when the -/// drag started. Only the Layers rows take it. +/// The selected art a row's selection square carries to another row in the same document. #[derive(Clone, Debug)] -pub(super) struct ArtDrag(pub(super) Vec); +pub(super) struct ArtDrag { + pub(super) document: u64, + pub(super) ids: Vec, +} /// What a cell reports. #[derive(Clone, Copy, Debug, PartialEq)] @@ -204,6 +206,7 @@ impl Component for TargetCircle { pub(super) struct SelectionSquare { #[common] common: Common, + document: u64, id: Option, selected: bool, holds: bool, @@ -214,13 +217,13 @@ pub(super) struct SelectionSquare { } impl SelectionSquare { - fn new(id: Option, selected: bool, holds: bool, color: DataColor, art: Vec) -> Self { - Self { common: Common::new(), id, selected, holds, color, art, pick: None } + fn new(document: u64, id: Option, selected: bool, holds: bool, color: DataColor, art: Vec) -> Self { + Self { common: Common::new(), document, id, selected, holds, color, art, pick: None } } /// A selected row's square, for the suite. fn sample() -> Self { - Self::new(Some(NodeId(1)), true, false, DataColor::new(Color32::from_rgb(79, 128, 255)), vec![NodeId(1)]).label("Select art") + Self::new(1, Some(NodeId(1)), true, false, DataColor::new(Color32::from_rgb(79, 128, 255)), vec![NodeId(1)]).label("Select art") } } @@ -253,7 +256,7 @@ impl Component for SelectionSquare { self.pick = Some(CellPick::SelectArt(activation.mods)); } if (self.selected || self.holds) && !self.art.is_empty() && primary_drag_start(cx) { - cx.start_drag(ArtDrag(self.art.clone()), DragPreview::None); + cx.start_drag(ArtDrag { document: self.document, ids: self.art.clone() }, DragPreview::None); } } @@ -369,18 +372,18 @@ pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cell let selected = |id: NodeId| tree.is_selected(id); match *row { RowId::Node(id) => { - let Some(n) = tree.doc().node(id) else { return Cells::new(None, SelectionSquare::new(None, false, false, color, vec![])) }; + let Some(n) = tree.doc().node(id) else { return Cells::new(None, SelectionSquare::new(st.uid, None, false, false, color, vec![])) }; let is_sel = selected(id); let (full, holds) = square_marks(tree, n); let art = if full || holds { st.selection.objects.clone() } else { vec![] }; let circle = TargetCircle::new(id, shows_targeted(tree, n, is_sel), has_styled_target(n)) .label(crate::i18n::fmt(tl!("Target {row}"), &[("row", info.name.as_str())])); - let square = SelectionSquare::new(Some(id), full, holds, color, art) + let square = SelectionSquare::new(st.uid, Some(id), full, holds, color, art) .label(crate::i18n::fmt(tl!("Select art of {row}"), &[("row", info.name.as_str())])); Cells::new(Some(circle), square) } - RowId::Guide(i) => Cells::new(None, SelectionSquare::new(None, tree.guides().contains(&i), false, color, vec![])), - RowId::Spine(blend) => Cells::new(None, SelectionSquare::new(None, selected(blend), false, color, vec![])), + RowId::Guide(i) => Cells::new(None, SelectionSquare::new(st.uid, None, tree.guides().contains(&i), false, color, vec![])), + RowId::Spine(blend) => Cells::new(None, SelectionSquare::new(st.uid, None, selected(blend), false, color, vec![])), } } @@ -410,6 +413,6 @@ pub(super) fn output( /// layer or group that takes the objects ([`DocLayers::lands_in`]). pub(super) fn accepts_art<'a>(tree: &'a DocLayers<'a>) -> impl Fn(&ArtDrag, &RowId, LayerPosition) -> bool + 'a { move |art: &ArtDrag, row: &RowId, position: LayerPosition| { - position == LayerPosition::Into && matches!(*row, RowId::Node(id) if tree.lands_in(id, &art.0, true)) + art.document == tree.state().uid && position == LayerPosition::Into && matches!(*row, RowId::Node(id) if tree.lands_in(id, &art.ids, true)) } } diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index b337508c90..17c66bfe68 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -1,8 +1,8 @@ use craft::behavior::IconId; use craft::keymap::Mods; -use craft::layers::ui::panel::MenuTarget; // PLAN: assumed path of craft-layers' panel types +use craft::layers::ui::panel::{LayersDrag, MenuTarget, document_hash}; use craft::layers::ui::tree::LayerRowKey; -use craft::ui::contract::{Entry, ListDrag, Show as _}; +use craft::ui::contract::{Entry, Show as _}; use craft::ui::display::{Elide, Text}; use craft::ui::menu::{MenuRow, PanelRow}; use craft::ui::primitives::IconSpec; @@ -347,19 +347,18 @@ fn spine_menu(tree: &DocLayers, blend: NodeId) -> Vec> { /// What was dropped on a footer action. pub(super) enum FooterPayload<'a> { /// Rows of the panel. - Rows(&'a [LayerRowKey]), + Rows(&'a [&'a RowId]), /// The target circle of an appearance (its node id). Appearance(u64), } /// The node ids and the ruler guide indexes among `keys`. -fn row_ids(keys: &[LayerRowKey]) -> (Vec, Vec) { +fn row_ids(keys: &[&RowId]) -> (Vec, Vec) { let (mut nodes, mut guides) = (vec![], vec![]); for key in keys { match key { - LayerRowKey::Layer(RowId::Node(id) | RowId::Spine(id)) => nodes.push(id.0), - LayerRowKey::Layer(RowId::Guide(i)) => guides.push(*i), - _ => {} + RowId::Node(id) | RowId::Spine(id) => nodes.push(id.0), + RowId::Guide(i) => guides.push(*i), } } (nodes, guides) @@ -433,19 +432,19 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value let locate_ok = !layers_only || super::rows::locate_layer_listed(tree.doc(), tree.root()); let root = tree.root(); let icon = |name: &'static str| IconSpec::svg(IconId::new(name)); - let layer_rows = |keys: &[LayerRowKey]| keys.iter().all(|key| matches!(key, LayerRowKey::Layer(_))); + let document = document_hash(st.uid); + let own = move |drag: &LayersDrag| drag.document() == Some(document); + let duplicate = move |drag: &LayersDrag| { + let (nodes, guides) = row_ids(&drag.layers()); + own(drag) && !nodes.is_empty() && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0)) + }; let actions = [ // PLAN: the framework's `accepts_drops` takes one payload type, so Delete cannot also take // `PanelDrag` (the appearance drop `footer_drop` maps); it needs a second payload there. FooterAction::new(icon("trash-2"), tl!("Delete Selection").to_string()) .takes_drops_disabled(true) - .accepts_drops(move |d: &ListDrag>| layer_rows(&d.keys)), - FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops( - move |d: &ListDrag>| { - let (nodes, guides) = row_ids(&d.keys); - layer_rows(&d.keys) && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0)) - }, - ), + .accepts_drops(move |d: &LayersDrag| own(d) && !d.layers().is_empty()), + FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(duplicate), FooterAction::new(icon("plus"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok), FooterAction::new(icon("frame"), tl!("Make/Release Clipping Mask").to_string()), FooterAction::new(icon("search"), if layers_only { tl!("Locate Layer").to_string() } else { tl!("Locate Object").to_string() }) @@ -462,8 +461,8 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value } out.extend(output.picked.and_then(|index| footer_pick(tree, index, output.mods))); if let Some(drop) = &output.dropped { - let run = if let Some(d) = drop.payload::>>() { - footer_drop(tree, drop.index, FooterPayload::Rows(&d.keys)) + let run = if let Some(d) = drop.payload::>().filter(|d| own(d)) { + footer_drop(tree, drop.index, FooterPayload::Rows(&d.layers())) } else if let Some(PanelDrag::Appearance(id)) = drop.payload::() { footer_drop(tree, drop.index, FooterPayload::Appearance(id.0)) } else { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 6cf12c1a95..523e9653ed 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -463,8 +463,8 @@ fn drop_command(tree: &DocLayers<'_>, mv: &LayerMove) -> Option<(String, /// The selected art carried by a row's selection square, dropped on `target`: the selection's top /// objects, as Arrange and Group take them, move there (Alt copies them). fn art_drop(st: &DocState, payload: &DropPayload, target: NodeId, position: LayerPosition, copy: bool) -> Option<(String, Value)> { - let art = payload.get::()?; - let ids: Vec = st.doc.paint_order(art.0.iter().copied()).iter().map(|i| i.0).collect(); + let art = payload.get::().filter(|art| art.document == st.uid)?; + let ids: Vec = st.doc.paint_order(art.ids.iter().copied()).iter().map(|i| i.0).collect(); Some(("layer.move".into(), json!({"ids": ids, "target": target.0, "place": place(position), "copy": copy}))) } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index a8db112a6a..cddc183e9d 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -507,6 +507,52 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() { assert!(lock_enabled, "locked sublayer enables Unlock All Layers"); } +#[test] +fn layer_row_footer_drops_after_next_document_leave_the_new_document_alone() { + use crate::tests::panel_harness::Panel; + use craft::layers::ui::panel::{LayersDrag, document_hash}; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + for (button, deletes) in [("Delete Selection", true), ("Create New Layer", false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut setup = |x| { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let source = app.session.active().unwrap().doc.layers[0].id; + name_row(&mut app, source, "Dragged Layer"); + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 30})).unwrap(); + app.run("layer.new", json!({"name": "Other Layer"})).unwrap(); + (app.session.active().unwrap().uid, source) + }; + let (first_doc, first_layer) = setup(10); + let (second_doc, second_layer) = setup(60); + assert_eq!(first_layer, second_layer, "the documents have different layers with the same local ID"); + assert!(app.session.set_active(0)); + + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Dragged Layer", Role::TREE_ITEM).center(); + let to = panel.rect(button).center(); + panel.drag_hold_role("Dragged Layer", Role::TREE_ITEM, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "{button} accepts a drag from its own list"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, second_doc); + let carried = drag::active::>(panel.ctx()).expect("the shortcut leaves the drag held"); + assert_eq!(carried.document(), Some(document_hash(first_doc))); + assert!(drag::mark(panel.ctx()).is_none(), "{button} rejects a drag belonging to another document"); + panel.release(); + assert_eq!(panel.app().session.active().unwrap().doc.layers.len(), 2); + assert!(crate::dialogs::confirm::open_question(&panel.app()).is_none()); + + panel.drag("Dragged Layer", button, Modifiers::NONE); + if deletes { + assert!(crate::dialogs::confirm::open_question(&panel.app()).is_some(), "a same-document drop still asks to delete its layer"); + } else { + assert_eq!(panel.app().session.active().unwrap().doc.layers.len(), 3, "a same-document drop still duplicates its layer"); + } + } +} + /// The footer's layer count is in the accessibility tree, and it follows the document's layers. #[test] fn the_footer_counts_the_layers() { @@ -524,6 +570,46 @@ fn name_row(app: &mut VectorcraftApp, id: NodeId, name: &str) { app.session.execute("layer.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); } +#[test] +fn a_selection_square_drop_after_next_document_leaves_the_new_artwork_in_place() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut setup = |x| { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let source = app.session.active().unwrap().doc.layers[0].id; + name_row(&mut app, source, "Source"); + let id = app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let dst = app.run("layer.new", json!({"name": "Destination"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + (app.session.active().unwrap().uid, NodeId(id), source, NodeId(dst)) + }; + let (first_doc, first, _, _) = setup(10); + let (second_doc, second, source, destination) = setup(60); + assert_eq!(first, second, "the documents have different rectangles with the same local ID"); + assert!(app.session.set_active(0)); + + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Select art of Source", Role::BUTTON).center(); + let to = panel.rect("Destination").center(); + panel.drag_hold_role("Select art of Source", Role::BUTTON, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "the destination accepts artwork in its own document"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, second_doc); + let carried = drag::active::(panel.ctx()).expect("the shortcut leaves the drag held"); + assert_eq!((carried.document, carried.ids.as_slice()), (first_doc, &[first][..])); + assert!(drag::mark(panel.ctx()).is_none(), "the destination rejects the foreign artwork"); + panel.release(); + let layer = |app: &VectorcraftApp| app.session.active().unwrap().doc.layer_of(second); + assert_eq!(layer(&panel.app()), Some(source), "the same-ID rectangle in this document has not moved"); + + panel.drag("Select art of Source", "Destination", Modifiers::NONE); + assert_eq!(layer(&panel.app()), Some(destination), "a same-document selection-square drag still moves the rectangle"); +} + /// The target and the selected objects, sorted. fn targeted(app: &VectorcraftApp) -> (Option, Vec) { let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs index 985871889c..5753cc3bb5 100644 --- a/crates/ui-egui/src/panels/learn.rs +++ b/crates/ui-egui/src/panels/learn.rs @@ -27,7 +27,7 @@ use craft::ui::contract::{ Bind, CollectionEvent, Gap, LabelKind, MemoProps, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, Sizing, clicked, }; -use craft::ui::display::Text; +use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; @@ -221,8 +221,7 @@ fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::Tuto if let Some(next) = next { marked = Some((i, next)); } - // PLAN: the number should read in the muted ink; the caption role stands in until `Text` names it. - Text::new(format!("{}.", i + 1)).role(TypeRole::Caption).show(ui); + Text::new(format!("{}.", i + 1)).shade(Shade::Muted).show(ui); if step_text(ui, step) { locate = step.tool; } diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 655be80fb3..5d1955810a 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -162,21 +162,6 @@ enum Grab { New(ItemKind, Value), } -/// The item of library `library` that `drag` holds, or what it would add, if anything. -fn grabbed(drag: &PanelDrag, library: &str) -> Option { - match drag { - PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), - PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), - PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), - PanelDrag::Art { ids, .. } => { - let ids: Vec = ids.iter().map(|id| id.0).collect(); - Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) - } - PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), - _ => None, - } -} - /// The kind and `library.add` params of what `drag` holds, to add to library `library`: a color /// (not one of that library's own; a spot colour with its swatch's name), or a gradient or pattern /// swatch, by its name. @@ -205,6 +190,7 @@ fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { /// which keep their test, can read it: what a drop into a group, or out of every group, does. struct Membership { library: String, + active_document: Option, /// The group of each grouped item, by its index in the library's groups. index: HashMap<(ItemKind, String), usize>, /// The groups' names, in the library's order. @@ -212,9 +198,25 @@ struct Membership { } impl Membership { - fn of(library: &str, lib: &Library) -> Self { + fn of(library: &str, lib: &Library, active_document: Option) -> Self { let index = lib.group_index().into_iter().map(|((kind, item), group)| ((kind, item.to_string()), group)).collect(); - Membership { library: library.to_string(), index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + Membership { library: library.to_string(), active_document, index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + } + + /// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document. + fn grabbed(&self, drag: &PanelDrag) -> Option { + let library = &self.library; + match drag { + PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), + PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), + PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), + PanelDrag::Art { document, ids } if Some(*document) == self.active_document => { + let ids: Vec = ids.iter().map(|id| id.0).collect(); + Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) + } + PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), + _ => None, + } } fn group_of(&self, kind: ItemKind, key: &str) -> Option { @@ -232,7 +234,7 @@ impl Membership { /// another group moves in, art or a swatch is added there. `None` when nothing would change, /// as for an item dropped on its own group, so that the target does not take it. fn landing(&self, drag: &PanelDrag, group: Option) -> Option { - let (cmd, mut params) = match grabbed(drag, &self.library)? { + let (cmd, mut params) = match self.grabbed(drag)? { Grab::Item(kind, item) if self.group_of(kind, &item) != group => ("library.moveItem", json!({ "kind": kind_param(kind), "item": item })), Grab::New(_, add) => ("library.add", add), Grab::Item(..) => return None, @@ -303,8 +305,8 @@ struct View<'a> { } impl<'a> View<'a> { - fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, has_doc: bool, can_apply: bool) -> Self { - let membership = Membership::of(library, lib); + fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, active_document: Option, can_apply: bool) -> Self { + let membership = Membership::of(library, lib, active_document); let query = query.trim().to_lowercase(); let searching = !query.is_empty(); let items: Vec> = lib @@ -319,7 +321,20 @@ impl<'a> View<'a> { } } let empty = lib.items().next().is_none() && lib.groups.is_empty(); - View { library, lib, membership: Arc::new(membership), items, counts, query, searching, empty, list, fill_active, has_doc, can_apply } + View { + library, + lib, + membership: Arc::new(membership), + items, + counts, + query, + searching, + empty, + list, + fill_active, + has_doc: active_document.is_some(), + can_apply, + } } /// The list: the ungrouped items, then the groups as sections. A drop anywhere on it away from @@ -387,7 +402,7 @@ impl<'a> View<'a> { /// Whether the drag in progress holds an item of one of this library's groups. fn dragging_grouped(&self, ui: &Ui) -> bool { craft::ui::runtime::drag::active::(ui.ctx()).is_some_and( - |drag| matches!(grabbed(&drag, self.library), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), + |drag| matches!(self.membership.grabbed(&drag), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), ) } @@ -476,7 +491,7 @@ impl<'a> View<'a> { let source = keyed(shown, |item: &&Shown<'a>| item.key.to_string()); let takes = DropKind::new::( DropPlace::Between, - move |drag: &PanelDrag, _: &DropAt| matches!(grabbed(drag, self.library), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), + move |drag: &PanelDrag, _: &DropAt| matches!(self.membership.grabbed(drag), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), ); // A graphic is placed by a double click; every other item is used by a click. let activate = if kind == ItemKind::Graphic { ActivateOn::DoubleClick } else { ActivateOn::Click }; @@ -565,7 +580,7 @@ impl<'a> View<'a> { /// `kind` moves there, art or a swatch of that kind is added there. Nothing for an item dropped /// beside itself. fn dropped(&self, drag: &PanelDrag, kind: ItemKind, at: Option<(&'static str, &str)>, group: Option) -> Option { - match grabbed(drag, self.library)? { + match self.membership.grabbed(drag)? { Grab::Item(k, item) if k == kind => (at.is_none_or(|(_, key)| key != item)).then(|| self.moved(kind, &item, at, group)), Grab::New(k, mut params) if k == kind => { if let Some((side, key)) = at { @@ -761,7 +776,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let acts = RefCell::new(Vec::new()); - let has_doc = app.session.active().is_some(); + let active_document = app.session.active().map(|st| st.uid); + let has_doc = active_document.is_some(); { // PLAN: assumed `UiState::{libraries_list_view: bool, library_search: String, library_groups_closed: HashSet<(String, String)>}` (ap.AS17, hub-w1). let (session, state) = (&app.session, &mut app.ui); @@ -769,7 +785,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Whether a character style's Apply Character Style is enabled (looked up only when the library has one). let can_apply = has_doc && !lib.char_styles.is_empty() && vectorcraft_engine::cmd::textstyles::target_style_attrs(session, &json!({}), false).is_some(); - let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, has_doc, can_apply); + let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, active_document, can_apply); Panel::new(tl!("Libraries")).footer(|ui, _| footer(ui, has_doc, &acts)).show(ui, |ui, _| { let search = (!view.empty).then_some(&mut state.library_search); header(ui, &session.libraries, &lib_id, &mut state.libraries_list_view, search, &acts); diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 4d14dcb8a4..305e8eadbf 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -248,6 +248,34 @@ fn an_empty_library_takes_art_anywhere() { assert_eq!(graphics(&mut panel.app()).len(), 1); } +#[test] +fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() { + let mut app = app(); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + let first = art_drag(&mut app, 10.0); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let second = art_drag(&mut app, 50.0); + assert!(matches!((&first, &second), (PanelDrag::Art { ids: a, .. }, PanelDrag::Art { ids: b, .. }) if a == b)); + assert!(app.session.set_active(0)); + + let mut panel = Harness::new(app, with_source); + let from = panel.rect(SOURCE).center(); + let to = panel.rect("This library is empty").center(); + CARRIED.with(|carried| *carried.borrow_mut() = Some(first.clone())); + panel.drag_hold_role(SOURCE, craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_some()); + assert!(panel.app().session.set_active(1)); + panel.frame(); + let drag = craft::ui::runtime::drag::active::(panel.ctx()); + assert_eq!(drag.as_deref(), Some(&first)); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_none()); + panel.release(); + assert!(graphics(&mut panel.app()).is_empty(), "the library never collects the target document's same-ID artwork"); + + drop_at(&mut panel, second, to); + assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added"); +} + fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { let mut app = app(); app.run("library.create", json!({"name": "Brand"})).unwrap(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 72c90a8efc..87b574f820 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -96,7 +96,8 @@ pub(crate) struct LinksModel { pub(super) show: Option<(u64, u64)>, nested: NestedPicks, selection: Selection, - menu: Option, + /// The document uid and row ID whose context menu is open. + menu: Option<(u64, u64)>, } /// `links.list` and the first selected image's `links.info`, with what they were fetched for. @@ -710,13 +711,16 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option) { /// The Links panel: the images as a list with a footer of link actions and the Link Info section. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { drop_stale_picks(app); + let uid = app.session.active().map(|st| st.uid); + if app.ui.links.menu.is_some_and(|(document, _)| Some(document) != uid) { + app.ui.links.menu = None; + } let Some(mut cache) = cached(app, ui.ctx()) else { Panel::new(tl!("Links")).show(ui, |ui, _| { Text::new(tl!("No document")).shade(Shade::Muted).show(ui); }); return; }; - let uid = app.session.active().map(|st| st.uid); let reveal = app.ui.links.show.take().filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); // A Show filter that leaves the requested row out goes back to Show All. @@ -730,7 +734,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let selected = selected_links(app); let mut selection = std::mem::take(&mut app.ui.links.selection); selection.items = selected.clone(); - let open_menu = app.ui.links.menu; + let open_menu = app.ui.links.menu.map(|(_, row)| row); let units = app.session.general_unit(); let view: &VectorcraftApp = app; @@ -808,8 +812,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let items = app.ui.links.selection.items.clone(); apply_selection(app, rows_of(&cache), items); } - if menu_for.is_some() { - app.ui.links.menu = menu_for; + if let Some(row) = menu_for { + app.ui.links.menu = uid.map(|document| (document, row)); } if let Some(id) = activated { go_to(app, id); @@ -828,7 +832,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let Some((a, id)) = row_act { app.ui.links.menu = None; - act(app, a, Some(id)); + if app.session.active().map(|st| st.uid) == uid { + act(app, a, Some(id)); + } } } diff --git a/crates/ui-egui/src/panels/magic_wand.rs b/crates/ui-egui/src/panels/magic_wand.rs index 7a44811ed0..68a151d5fa 100644 --- a/crates/ui-egui/src/panels/magic_wand.rs +++ b/crates/ui-egui/src/panels/magic_wand.rs @@ -44,8 +44,10 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &'static str, fl app.run("magicWand.set", json!({ flag: now })).ok(); } if let Some((key, field)) = tol { - Field::new(tl!("Tolerance:")).id_salt(key).enabled(on).show(ui, |ui, _| { - if let Some(n) = field().enabled(on).show(ui).value().copied().flatten() { + let caption = tl!("Tolerance:"); + Field::new(caption).id_salt(key).enabled(on).show(ui, |ui, _| { + let name = format!("{caption} {label}"); + if let Some(n) = field().label(name).keeps_name(true).enabled(on).show(ui).value().copied().flatten() { app.run("magicWand.set", json!({ key: n })).ok(); } }); @@ -114,6 +116,19 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; + #[test] + fn each_tolerance_field_has_its_own_accessible_name() { + use craft::ui::contract::Role; + use craft::ui::testing::Fixture; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.settle(); + let names: Vec<_> = fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node)).collect(); + assert_eq!(names, ["Tolerance: Fill Color", "Tolerance: Stroke Color", "Tolerance: Stroke Weight", "Tolerance: Opacity"]); + assert_eq!(fixture.texts().iter().filter(|run| run.text == "Tolerance:").count(), 4); + } + #[test] fn color_tolerance_fields_go_to_100_in_a_cmyk_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 1f3ca8d638..93e93681f2 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -22,7 +22,7 @@ use craft::ui::text::{NumberField, TextField}; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::pattern::{PatternDef, RepeatKind, TileType}; -use vectorcraft_doc::{NodeKind, Unit}; +use vectorcraft_doc::{NodeId, NodeKind}; use super::attributes::side_name; use crate::VectorcraftApp; @@ -41,10 +41,10 @@ pub(crate) struct PatternOptionsPanel { pub(crate) chosen: String, } -fn editing(app: &VectorcraftApp) -> Option<(PatternDef, Unit)> { +fn editing(app: &VectorcraftApp) -> Option<(PatternDef, (u64, NodeId))> { let st = app.session.active()?; let pe = st.doc.pattern_edit.as_ref()?; - Some((st.doc.pattern(&pe.pattern)?.clone(), app.session.general_unit())) + Some((st.doc.pattern(&pe.pattern)?.clone(), (st.uid, pe.layer))) } fn set(app: &mut VectorcraftApp, name: &str, mut p: Value) { @@ -95,7 +95,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); return; } - let Some((def, _)) = editing(app) else { + let Some((def, edit_scope)) = editing(app) else { idle(app, ui); return; }; @@ -110,7 +110,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let sized = def.size_tile_to_art; let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); - FieldGroup::new(tl!("Pattern Options")).show(ui, |ui, _| { + // The temporary layer identifies this editing session even when the pattern is renamed. + FieldGroup::new(tl!("Pattern Options")).id_salt(edit_scope).show(ui, |ui, _| { // Name commits on Enter or focus loss; Shift+Enter commits too and keeps the focus, so the // renamed pattern's name stays selected for the next edit. Enter ends the editing: the keys go // to the document canvas, as with nothing focused. @@ -280,4 +281,32 @@ mod tests { assert!(named(&panel, "Waves"), "Enter applies the name"); assert!(!panel.focused("Name"), "Enter ends the editing"); } + + #[test] + fn a_name_draft_does_not_follow_pattern_options_to_the_next_document() { + let mut panel = editing_panel(); + { + let mut app = panel.app(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots"})).unwrap(); + } + let source = panel.app().session.active().unwrap().uid; + panel.click_role("Name", craft::ui::contract::Role::TEXT_INPUT); + panel.type_text("Stripes"); + assert_eq!(panel.value("Name").as_deref(), Some("Stripes")); + + panel.app().run("window.nextDocument", json!({})).unwrap(); + panel.frame(); + assert_ne!(panel.app().session.active().unwrap().uid, source); + assert_eq!(panel.value("Name").as_deref(), Some("Dots")); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); + + panel.app().run("window.previousDocument", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, source); + assert_eq!(panel.value("Name").as_deref(), Some("Dots")); + assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); + } } diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index f8ed1f6967..4b4353d8ac 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -302,7 +302,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { let rows = PreflightRows::new(report); let pending = Pending::default(); - let out = FindingsList::new("Findings").show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { + let out = FindingsList::new(tl!("Findings")).show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { Some(Entry_::Heading(c)) => heading_row(&rows.checks[*c], &pending), Some(Entry_::Finding(f)) => finding_row(*key, &rows.findings[*f], &icx.words::(), &pending), None => ListRow::new(String::new()), diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 3081b1a0c3..c2d41bdb06 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -22,8 +22,14 @@ pub struct PropertiesUi { pub global_edit_open: bool, /// The panel's More Options popover is open. pub more_options_open: bool, + /// The cache of `appearance_section::edited_strokes_profiled`, keyed by (document uid, revision, + /// active Appearance row). + pub edited_profiled: Option<(ProfiledKey, bool)>, } +/// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). +type ProfiledKey = (u64, u64, Option); + /// Two equal columns: the Quick Actions and the paired buttons of the sections. const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0); 2]; diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index 72fce87d45..cd71a0f035 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -97,13 +97,35 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( } } +/// Whether a stroke that `stroke.set` edits has a width profile +/// ([`vectorcraft_engine::Session::edited_strokes_profiled`]), cached per document revision and +/// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or +/// the Live Paint Bucket is active, when the list edits the stroke the panel shows. +fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { + if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + return false; + } + let Some(st) = app.session.active() else { return false }; + let key = (st.uid, st.revision, app.session.appearance_item()); + if let Some((k, v)) = app.ui.properties_panel.edited_profiled + && k == key + { + return v; + } + let v = app.session.edited_strokes_profiled(); + app.ui.properties_panel.edited_profiled = Some((key, v)); + v +} + /// The stroke's Variable Width Profile (the Control bar's list), shown while the Width tool is in /// use or the stroke has a variable width, as the Properties panel overview places it /// (). +/// The row also shows when the shown stroke is uniform and another stroke the list edits has a +/// variable width ([`edited_strokes_profiled`]), so that Uniform can remove it. fn width_profile_row(app: &mut VectorcraftApp, ui: &mut Ui) { let stroke = panels::current_stroke(app); let profile = stroke.as_ref().and_then(|s| s.profile.as_ref()); - if app.session.tool_id() != "width" && WidthProfile::id_of(profile) == "uniform" { + if app.session.tool_id() != "width" && WidthProfile::id_of(profile) == "uniform" && !edited_strokes_profiled(app) { return; } Field::new(tl!("Profile")).show(ui, |ui, _| stroke::profile_select(app, ui)); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 57017c03c3..faeb91c166 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1003,6 +1003,66 @@ fn the_width_profile_of_a_brushed_stroke_offers_only_uniform() { assert_eq!(profile, None); } +/// Two selected strokes, the shown one uniform and the other with a variable width: the Width +/// Profile row still shows, and its Uniform removes the other stroke's profile. With brushes on both +/// strokes the list holds only Uniform. Once both are uniform the row is hidden again. +#[test] +fn the_width_profile_shows_while_another_selected_stroke_has_a_variable_width() { + for brushed in [false, true] { + let mut app = new_app(); + let a = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + let b = app.run("shape.line", json!({"x1": 20, "y1": 160, "x2": 300, "y2": 160})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + if brushed { + app.run("brush.apply", json!({"ids": [a, b], "name": "3 pt. Round"})).unwrap(); + } + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(super::super::current_stroke(&app).and_then(|s| s.profile), None, "the shown stroke is uniform"); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Profile"), "brushed {brushed}"); + panel.click("Profile"); + assert_eq!(panel.shows("Taper Start"), !brushed, "brushed {brushed}"); + panel.click("Uniform"); + let profile = panel + .app() + .session + .active() + .unwrap() + .doc + .node(vectorcraft_doc::NodeId(b.as_u64().unwrap())) + .unwrap() + .appearance + .stroke() + .unwrap() + .profile + .clone(); + assert_eq!(profile, None, "brushed {brushed}"); + assert!(!panel.shows("Profile"), "brushed {brushed}: every stroke is uniform"); + } +} + +/// The Width Profile row follows a change of selection that leaves the document as it was: it +/// hides when the stroke with a variable width leaves the selection and shows again when it comes +/// back. +#[test] +fn the_width_profile_row_follows_a_selection_change() { + let mut app = new_app(); + let a = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + let b = app.run("shape.line", json!({"x1": 20, "y1": 160, "x2": 300, "y2": 160})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Profile"), "the other stroke has a variable width"); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Profile"), "the uniform stroke alone"); + panel.app().run("select.set", json!({"ids": [a, b]})).unwrap(); + panel.frame(); + assert!(panel.shows("Profile"), "both strokes again"); +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. @@ -1016,7 +1076,7 @@ fn direct_selected_corners_show_their_kind_and_radius() { panel.app().select_tool("directSelection"); panel.app().run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap(); panel.frame(); - assert!(panel.shows("Corner") && panel.shows("Corner Radius")); + assert!(panel.shows("Corner") && panel.shows("Corner Radius") && panel.shows("Corners")); let corners = |panel: &Panel| { let n = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(star)).unwrap().clone(); let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); @@ -1041,6 +1101,152 @@ fn direct_selected_corners_show_their_kind_and_radius() { panel.app().run("select.anchors", json!({"id": r, "anchors": [[0, 1]], "mode": "set"})).unwrap(); panel.frame(); assert!(panel.shows("Corner") && panel.shows("Corner Radius")); + // And the Corners link, for the pop-up's rounding: Relative on the picked corner's rectangle. + panel.click("Corners"); + panel.click("Relative"); + let n = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// With Direct Selection, a live rectangle or live polygon selected whole keeps its own rows and +/// shows the Corners link, whose pop-up sets every corner of the shape. A path with Live Corners +/// selected whole shows no corner rows. +#[test] +fn a_whole_live_shape_with_direct_selection_shows_the_corners_link() { + let mut app = new_app(); + app.select_tool("directSelection"); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + let polygon = app.run("shape.polygon", json!({"cx": 200, "cy": 150, "radius": 50, "sides": 5})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [polygon]})).unwrap(); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Corners"), "polygon"); + panel.app().run("select.set", json!({"ids": [r]})).unwrap(); + panel.frame(); + assert!(panel.shows("Corners") && panel.shows("Corner Radius"), "rectangle"); + // The pop-up's rounding: Relative on the rectangle. + panel.click("Corners"); + let depth = undo_depth(&panel.app()); + panel.click("Relative"); + assert_eq!(undo_depth(&panel.app()), depth + 1, "one undo step"); + let n = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); + // A plain path selected whole: no corner selected. + let path = square_path(&mut panel.app(), 200.0); + panel.app().select_tool("directSelection"); + panel.app().run("select.set", json!({"ids": [path]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Corner") && !panel.shows("Corners")); +} + +/// A live rectangle with Relative rounding shows its radius as a document length in its Corner +/// Radius field, as the Corners pop-up does, not as the fraction it stores. +#[test] +fn a_relative_live_rectangle_shows_its_radius_as_a_length() { + let mut app = new_app(); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "radius": 10})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "relativeRadii": true})).unwrap(); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); + let shown = crate::panels::corner_radius(&app, &n).unwrap(); + assert!((shown - 10.0).abs() < 1e-6, "the field shows {shown}"); + assert_eq!(crate::panels::picked_corners(&app).unwrap().radius.map(|r| (r - 10.0).abs() < 1e-6), Some(true), "as the pop-up does"); +} + +/// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. +fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { + let id = rect(app, x, 50.0, 100.0, 100.0); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + id.as_u64().unwrap() +} + +/// The radius and kind of each corner of path `id`, from the top-left clockwise. +fn path_corners(app: &VectorcraftApp, id: u64) -> Vec<(f64, vectorcraft_geom::shapes::CornerKind)> { + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + (0..4).map(|k| (lc.radius(k), lc.kind(k))).collect() +} + +/// The Corners link opens a pop-up with the corner kind, the radius and the rounding of the +/// Direct-Selected corners. A radius typed there, or a kind or rounding picked, sets the three +/// picked corners and leaves the fourth as it is, each in one undo step. +#[test] +fn the_corners_link_opens_the_settings_of_the_picked_corners() { + let mut app = new_app(); + let id = square_path(&mut app, 50.0); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let mut panel = Panel::new(app, show); + assert!(!panel.shows("Relative") && !panel.shows("Chamfer"), "closed"); + panel.click("Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius", "Relative", "Absolute"] { + assert!(panel.shows(name), "the pop-up has {name}"); + } + let depth = undo_depth(&panel.app()); + panel.type_into("Radius", "18"); + assert_eq!(undo_depth(&panel.app()), depth + 1, "one undo step"); + let (round, chamfer) = (vectorcraft_geom::shapes::CornerKind::Round, vectorcraft_geom::shapes::CornerKind::Chamfer); + assert_eq!(path_corners(&panel.app(), id), vec![(18.0, round), (18.0, round), (18.0, round), (0.0, round)]); + // A kind, picked in the pop-up. + panel.click("Chamfer"); + assert_eq!(undo_depth(&panel.app()), depth + 2, "one undo step"); + assert_eq!(path_corners(&panel.app(), id), vec![(18.0, chamfer), (18.0, chamfer), (18.0, chamfer), (0.0, round)]); + // Relative rounding, for the path the corners are on. + panel.click("Relative"); + assert_eq!(undo_depth(&panel.app()), depth + 3, "one undo step"); + let n = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// With a corner of each of two paths Direct-Selected and their radii different, the pop-up's +/// radius is blank; a radius typed there sets both corners, and no other, in one undo step. +#[test] +fn the_corners_pop_up_sets_picked_corners_across_paths() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + app.run("select.anchors", json!({"id": b, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + assert_eq!(crate::panels::picked_corners(&app).unwrap().radius, None, "blank while the radii differ"); + let mut panel = Panel::new(app, show); + panel.click("Corners"); + let depth = undo_depth(&panel.app()); + panel.type_into("Radius", "7"); + assert_eq!(undo_depth(&panel.app()), depth + 1, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&panel.app(), a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&panel.app(), b), vec![(0.0, round), (7.0, round), (0.0, round), (0.0, round)]); +} + +/// With a corner of one path Direct-Selected and a second path selected whole, the pop-up picks +/// that corner and every corner of the second path. While one path is Relative and the other +/// Absolute, no rounding is chosen; picking Absolute sets both paths in one undo step. +#[test] +fn the_corners_pop_up_takes_every_corner_of_a_whole_path_and_mixed_rounding() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [a], "relativeRadii": true})).unwrap(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let picked = crate::panels::picked_corners(&app).unwrap(); + assert_eq!(picked.relative, None, "no rounding while the paths differ"); + assert_eq!(picked.items.len(), 2); + let mut panel = Panel::new(app, show); + panel.click("Corners"); + let depth = undo_depth(&panel.app()); + panel.click("Absolute"); + assert_eq!(undo_depth(&panel.app()), depth + 1, "one undo step"); + assert_eq!(crate::panels::picked_corners(&panel.app()).unwrap().relative, Some(false), "both Absolute"); + panel.type_into("Radius", "7"); + assert_eq!(undo_depth(&panel.app()), depth + 2, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&panel.app(), a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&panel.app(), b), vec![(7.0, round); 4], "every corner of the path selected whole"); } /// One effect on the one selected object shows its name and a Delete icon beside the fx button, diff --git a/crates/ui-egui/src/panels/properties/transform_section.rs b/crates/ui-egui/src/panels/properties/transform_section.rs index 8db935d3fb..5a9ffebe94 100644 --- a/crates/ui-egui/src/panels/properties/transform_section.rs +++ b/crates/ui-egui/src/panels/properties/transform_section.rs @@ -12,11 +12,13 @@ use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::pickers::Select; use craft::ui::popover::Popover; +use craft::ui::text::NumberField; use egui::Ui; use serde_json::json; use vectorcraft_doc::{LiveCorners, LiveShape, NodeKind}; use crate::VectorcraftApp; +use crate::edits::{EditPath, apply_edits}; use crate::panels::{self, first_selected, transform}; /// The Transform section for the selection: its position and size about the reference point, the @@ -73,34 +75,60 @@ fn more_options(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.properties_panel.more_options_open = open; } -/// The Corners of the one path whose corners Direct Selection has selected: their kind and radius, -/// which `object.setLiveShape` sets on those corners. The Properties panel overview shows the -/// control while the Direct Selection tool is chosen and a corner of an object is selected -/// (). -/// A live rectangle's and a live polygon's own rows already set the selected corners. +/// The Corners of the paths whose corners Direct Selection has selected: their kind, and their +/// radius with the Corners link beside it, which `object.setLiveShape` sets on those corners +/// ([`panels::picked_corners`]); the link opens the Corners pop-up for them. The Properties panel +/// overview shows the control while the Direct Selection tool is chosen and a corner of an object +/// is selected +/// (), +/// and the Corners link opens the corner settings +/// (). +/// One live rectangle or live polygon selected alone has its own kind and radius rows, which +/// already set the selected corners: it shows the Corners link alone, also while it is selected +/// whole. pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.tool_id() != "directSelection" { return; } let Some(st) = app.session.active() else { return }; - let [id] = st.selection.objects[..] else { return }; - let Some(n) = st.doc.node(id) else { return }; - if matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })) { + let own_rows = matches!(st.selection.objects[..], [id] + if st.doc.node(id).is_some_and(|n| matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })))); + // A corner of a path is Direct-Selected. + let corner_selected = st.selection.objects.iter().any(|id| { + st.doc.node(*id).and_then(LiveCorners::of).is_some_and(|lc| st.selection.partial(*id).is_some_and(|a| !lc.corners_of(a).is_empty())) + }); + if !own_rows && !corner_selected { return; } - let Some(lc) = LiveCorners::of(n) else { return }; - if st.selection.partial(id).is_none_or(|a| lc.corners_of(a).is_empty()) { + let Some(picked) = panels::picked_corners(app) else { return }; + if own_rows { + Row::new().show(ui, |ui, _| panels::corners_link(app, ui)); return; } - let n = n.clone(); // The corners differ in kind: no entry is the value. - let kind = panels::corner_style(app, &n).1.map_or(Mixed::Mixed, Mixed::Same); + let kind = picked.kind.map_or(Mixed::Mixed, Mixed::Same); let entries = panels::corner_entries(); - let picked = Field::new(tl!("Corner")).show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied()).inner; - if let Some(Some(kind)) = picked { - app.run("object.setLiveShape", json!({"kind": kind})).ok(); + let chosen = Field::new(tl!("Corner")).show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied()).inner; + if let Some(Some(kind)) = chosen { + panels::set_picked_corners(app, &picked, json!({"kind": kind})); + } + let lengths = crate::canvas::general_lengths(app); + let mut edit = None; + Field::new(tl!("Corner Radius")).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + edit = Some(NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit); + panels::corners_link(app, ui); + }); + }); + if let Some(edit) = edit { + // Every value of a scrub sets the corners; the gesture is one undo step. + apply_edits(app, &edit, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + panels::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); } - Field::new(tl!("Corner Radius")).show(ui, |ui, _| panels::corner_radius_field(app, ui, &n)); } /// Ruler guides selected on their own: a Transform section with the X of the vertical ones and diff --git a/crates/ui-egui/src/panels/retype.rs b/crates/ui-egui/src/panels/retype.rs index 77dd92e764..16d607393c 100644 --- a/crates/ui-egui/src/panels/retype.rs +++ b/crates/ui-egui/src/panels/retype.rs @@ -2,7 +2,8 @@ //! by how many of its shapes each matches (`type.retypeFonts`), each with a sample //! (, //! ). -//! Find Matching Fonts lists ten, and Find more font matches at the end of the list five more. The +//! Find Matching Fonts lists ten, after reading the installed fonts not loaded yet off the UI +//! thread ([`crate::retype_runs`]), and Find more font matches at the end of the list five more. The //! list stays after the selection changes, so choosing a font in it sets that font on the live text //! selected then, as the font menus do. The sample field sets the text the samples show, and the //! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`, @@ -84,14 +85,18 @@ fn size_name(size: Size) -> &'static str { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut run: Option<(&str, Value)> = None; let has_path = vectorcraft_engine::cmd::has_selected_path(&app.session).is_ok(); - if Button::new(tl!("Find Matching Fonts")).variant(Variant::PRIMARY).enabled(has_path).show(ui).clicked() { - run = Some(("retype.find", json!({}))); + // The button searches the installed fonts off the UI thread, as `retype.find` from a menu does. + if Button::new(tl!("Find Matching Fonts")).variant(Variant::PRIMARY).enabled(has_path).show(ui).clicked() + && let Err(e) = find_in_background(app, &json!({})) + { + app.status(e); } let typed = TextField::new(tl!("Type your text to preview"), Bind::given(Mixed::Same(app.ui.retype.text.clone()))) .placeholder(tl!("Type your text to preview")) + .keeps_on_escape() .limit(MAX_TEXT) .show(ui); - if let Some(text) = typed.events.committed() { + if let Some(text) = typed.events.value().filter(|text| **text != app.ui.retype.text) { run = Some(("retype.preview", json!({ "text": text }))); } Divider::horizontal().show(ui); @@ -180,6 +185,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(list(&app.ui.retype)), "retype.preview" => preview(app, p), "retype.reset" => { + // A search Find Matching Fonts started does not fill the list again. + crate::retype_runs::drop_panel_search(app); let v = &mut app.ui.retype; (v.searched, v.fonts, v.rest, v.shapes, v.truncated) = (false, vec![], vec![], 0, false); Ok(list(&app.ui.retype)) @@ -202,11 +209,16 @@ fn list(v: &View) -> Value { }) } -/// `retype.find {more?}`: show the panel and list the first ten fonts matching the selected -/// outlined text, or with `more` add the next five the last search found, whatever is selected -/// now → what `retype.list` returns. The list stays as it was when the search fails. +/// `retype.find {more?, installed?}`: show the panel and list the first ten fonts matching the +/// selected outlined text (with `installed` false, the loaded fonts only), or with `more` add the +/// next five the last search found, whatever is selected now → what `retype.list` returns. The +/// list stays as it was when the search fails. fn find(app: &mut VectorcraftApp, p: &Value) -> Result { let more = crate::menus::opt_bool(p, "more")?.unwrap_or(false); + // A bad installed is an error even when no search runs. + if p.get("installed").is_some_and(|v| !v.is_null() && !v.is_boolean()) { + return Err("`installed` must be true, false or null".into()); + } if more && app.ui.retype.searched { // The panel shows first: a failure leaves the list as it was. crate::panel_docking::reveal_panel(app, ID)?; @@ -215,7 +227,34 @@ fn find(app: &mut VectorcraftApp, p: &Value) -> Result { v.fonts.extend(next); return Ok(list(&app.ui.retype)); } - let r = app.session.execute("type.retypeFonts", &json!({ "count": MAX })).map_err(|e| e.to_string())?; + // A search Find Matching Fonts started in the background does not replace this one's list. + crate::retype_runs::drop_panel_search(app); + search(app, &search_params(p)) +} + +/// Find Matching Fonts as the user asks for it (the panel's button, `retype.find` from a menu or the +/// command palette, `p` its params without `more`): the installed fonts are searched off the UI +/// thread ([`crate::retype_runs`]), then the list is filled. +pub(crate) fn find_in_background(app: &mut VectorcraftApp, p: &Value) -> Result { + // A bad more is an error here too, as `retype.find` has it. + crate::menus::opt_bool(p, "more")?; + crate::retype_runs::start(app, "type.retypeFonts", search_params(p), true) +} + +/// `type.retypeFonts`' params for a new search with `retype.find`'s params `p`. +fn search_params(p: &Value) -> Value { + let mut q = json!({ "count": MAX }); + if let Some(installed) = p.get("installed") { + q["installed"] = installed.clone(); + } + q +} + +/// Shows the panel and lists the first ten fonts `type.retypeFonts` with params `p` finds for the +/// selected outlined text → what `retype.list` returns. The list stays as it was when the search +/// fails. +pub(crate) fn search(app: &mut VectorcraftApp, p: &Value) -> Result { + let r = app.session.execute("type.retypeFonts", p).map_err(|e| e.to_string())?; crate::panel_docking::reveal_panel(app, ID)?; let mut fonts: Vec = r["fonts"] .as_array() diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 41cc0de514..992147064c 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_engine::Session; use super::{ID, Size, show}; use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; const SCREEN: egui::Rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(600.0, 900.0)); @@ -82,7 +83,8 @@ fn more_adds_fonts_until_none_is_left() { let mut app = app(); let g = outlined(&mut app, json!({"x": 40, "y": 100, "text": "More", "size": 30})); select(&mut app, &[g]); - let first = app.run("retype.find", json!({})).unwrap(); + // The installed fonts are left out, so the searches compare the same fonts. + let first = app.run("retype.find", json!({"installed": false})).unwrap(); // How many fonts match depends on the fonts loaded: ask until none is left. let mut last = first.clone(); for _ in 0..20 { @@ -99,10 +101,16 @@ fn more_adds_fonts_until_none_is_left() { // A null more is omitted: a new search lists the first ten again. A font added to the list // tells the new search apart from adding more when ten or fewer fonts match. app.ui.retype.fonts.push(super::Found { family: "Not Found".into(), style: "Regular".into(), matched: 0 }); - assert_eq!(app.run("retype.find", json!({"more": null})).unwrap(), first); + assert_eq!(app.run("retype.find", json!({"more": null, "installed": false})).unwrap(), first); // Before any search, more is a first search. app.run("retype.reset", json!({})).unwrap(); - assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), first); + assert_eq!(app.run("retype.find", json!({"more": true, "installed": false})).unwrap(), first); + // A bad installed is the command's error, and leaves the list as it was. + for p in [json!({"installed": 1}), json!({"more": true, "installed": "yes"})] { + let e = app.run("retype.find", p.clone()).unwrap_err(); + assert!(e.contains("`installed` must be true, false or null"), "{p}: {e}"); + assert_eq!(app.run("retype.list", json!({})).unwrap(), first, "{p}"); + } assert!(app.run("retype.find", json!({"more": "yes"})).is_err()); } @@ -138,6 +146,23 @@ fn a_failed_search_leaves_the_list_as_it_was() { assert_eq!(app.run("retype.list", json!({})).unwrap(), listed); } +#[test] +fn typing_updates_the_preview_without_enter_and_escape_keeps_it() { + let mut panel = Panel::new(app(), show); + let label = "Type your text to preview"; + panel.click(label); + assert!(panel.focused(label)); + panel.type_text("Preview"); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview"); + panel.type_text(" sample"); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview sample"); + + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert!(!panel.focused(label)); + assert_eq!(panel.value(label).as_deref(), Some("Preview sample")); + assert_eq!(panel.app().run("retype.list", json!({})).unwrap()["text"], "Preview sample"); +} + #[test] fn preview_sets_the_size_and_text_and_reset_keeps_them() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/script_console.rs b/crates/ui-egui/src/panels/script_console.rs index 28f747e897..27925a9ed0 100644 --- a/crates/ui-egui/src/panels/script_console.rs +++ b/crates/ui-egui/src/panels/script_console.rs @@ -17,14 +17,15 @@ use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry}; use craft::behavior::{DisplayOrder, IconId, ItemSource}; use craft::keymap::CommandRef; use craft::theme::variant::Tone; -use craft::ui::contract::{Bind, ScrollAnchor, Show, ShowCollection}; +use craft::ui::buttons::Button; +use craft::ui::contract::{Bind, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked}; +use craft::ui::layout::RowAlign; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, RowInk}; use craft::ui::menu::PanelRow; use craft::ui::notices::Notice; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandState, CommandStates}; -use craft::ui::sections::FooterBar; -use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::TypeRole; use crate::VectorcraftApp; @@ -165,11 +166,28 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let any = !app.session.script_console().lines().is_empty(); let selected = selected_range(app).is_some(); - for (id, title, on) in [(COMMANDS[0], tl!("Clear"), any), (COMMANDS[1], tl!("Copy Selected"), selected), (COMMANDS[2], tl!("Copy All"), any)] { + for (id, title, on) in buttons(any, selected) { states.set(CommandRef::new(id), CommandState::new().enabled(on).title(title)); } } +fn buttons(any: bool, selected: bool) -> [(&'static str, &'static str, bool); 3] { + [(COMMANDS[0], tl!("Clear"), any), (COMMANDS[1], tl!("Copy Selected"), selected), (COMMANDS[2], tl!("Copy All"), any)] +} + +fn footer(ui: &mut Ui, buttons: [(&'static str, &'static str, bool); 3]) -> Option<&'static str> { + let mut picked = None; + Row::new().fill_width().align(RowAlign::End).wrap(true).show(ui, |ui, _| { + for (id, title, on) in buttons { + let button = Button::new(title).id_salt(id).least_width(LeastWidth::DialogButton).enabled(on); + if clicked(&button.show(ui)) { + picked = Some(id); + } + } + }); + picked +} + /// What the panel's menu model depends on, for the menu cache's key. pub(crate) fn key(app: &VectorcraftApp) -> u64 { let c = app.session.script_console(); @@ -189,31 +207,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { selection.items.retain(held); selection.lead = selection.lead.take().filter(held); selection.anchor = selection.anchor.take().filter(held); - if let Some(n) = notice(c) { - Notice::new(Tone::Info, n).show(ui); - } - List::::new(tl!("Script Console")).scroll_anchor(ScrollAnchor::End).selection(Bind::bound(&mut app.ui.script_console_selection)).show_items( - ui, - &Lines { start, count }, - &mut |key, icx| { - let line = key.checked_sub(start).and_then(|at| c.lines().get(at as usize)); - let Some(line) = line else { return ListRow::new(String::new()) }; - let row = ListRow::new(shown(line)).role(TypeRole::Mono).state(icx.row.clone()); - match line.entry { - Entry::Error(_) => row.icon(IconSpec::svg(IconId::new("error"))).tone(Tone::Bad), - Entry::Start | Entry::End(_) | Entry::Report { .. } => row.ink(RowInk::Muted), - Entry::Output(_) | Entry::Log(_) => row, - } - }, - ); - let picked = FooterBar::buttons([ - FooterButton::new(tl!("Clear"), DialogRole::Other).enabled(count > 0), - FooterButton::new(tl!("Copy Selected"), DialogRole::Other).enabled(selected_range(app).is_some()), - FooterButton::new(tl!("Copy All"), DialogRole::Other).enabled(count > 0), - ]) - .show_footer(ui) - .picked; - if let Some(id) = picked.and_then(|at| COMMANDS.get(at)) { + let buttons = buttons(count > 0, !selection.items.is_empty()); + let mut picked = None; + Stack::new().fill().footer(|ui, _| picked = footer(ui, buttons).or(picked)).show(ui, |ui, _| { + if let Some(n) = notice(c) { + Notice::new(Tone::Info, n).show(ui); + } + List::::new(tl!("Script Console")) + .sizing(Sizing::Fill) + .scroll_anchor(ScrollAnchor::End) + .selection(Bind::bound(&mut *selection)) + .show_items(ui, &Lines { start, count }, &mut |key, icx| { + let line = key.checked_sub(start).and_then(|at| c.lines().get(at as usize)); + let Some(line) = line else { return ListRow::new(String::new()) }; + let row = ListRow::new(shown(line)).role(TypeRole::Mono).state(icx.row.clone()); + match line.entry { + Entry::Error(_) => row.icon(IconSpec::svg(IconId::new("error"))).tone(Tone::Bad), + Entry::Start | Entry::End(_) | Entry::Report { .. } => row.ink(RowInk::Muted), + Entry::Output(_) | Entry::Log(_) => row, + } + }); + }); + if let Some(id) = picked { run_ui(app, id, json!({})); } } diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 46bed23b0e..1a3e0fefd1 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -14,8 +14,8 @@ use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{ - Bind, CollectionEvent, ColumnSpec, Entry, Lazy, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, ToggleColumn, - clicked, + Bind, CollectionEvent, ColumnSpec, Entry, Lazy, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, + ToggleColumn, clicked, }; use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; @@ -49,9 +49,6 @@ const EYE: ColumnKey = ColumnKey::new("eye"); const NAME: ColumnKey = ColumnKey::new("name"); /// The command of the panel menu's Show All Plates row. const SHOW_ALL_PLATES: &str = "ui.separations.showAllPlates"; -/// How long the Color Settings section is, for the scroll area before it has been shown once. -const COLOR_SETTINGS_ESTIMATE: f32 = 460.0; - /// Runs command `id` with `p`; a failure goes to the status bar, so it returns `None`. fn act(app: &mut VectorcraftApp, id: &str, p: Value) -> Option { match app.run(id, p) { @@ -421,12 +418,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The flag is read by every pass of the frame, so a second pass reveals as well; only a real // pass (not a sizing one) spends it. let reveal = app.ui.color_settings_scroll; - Stack::new().label(tl!("Separations Preview")).show(ui, |ui, _| { + Stack::new().label(tl!("Separations Preview")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| { crate::panels::section(tl!("Separations Preview")).show(ui, |ui, _| plates_section(app, ui)); crate::panels::section(tl!("Proof Setup")).show(ui, |ui, _| proof_section(app, ui)); - Lazy::new("color-settings", COLOR_SETTINGS_ESTIMATE).reveal(reveal).show(ui, |ui| { - crate::panels::section(tl!("Color Settings")).show(ui, |ui, _| settings_rows(app, ui)); - }); + // The scroll target is separate from the controls so they are registered for keyboard navigation + // even before the section has scrolled into view. + Lazy::new("color-settings", 0.0).reveal(reveal).show(ui, |_| {}); + crate::panels::section(tl!("Color Settings")).show(ui, |ui, _| settings_rows(app, ui)); }); if reveal && !ui.is_sizing_pass() { app.ui.color_settings_scroll = false; @@ -522,11 +520,6 @@ mod tests { } } - /// The panel inside a vertical scroll area, as the window shows it. - fn scrolled(app: &mut VectorcraftApp, ui: &mut Ui) { - Stack::new().fill().scroll(craft::ui::contract::Scroll::vertical()).show(ui, |ui, _| show(app, ui)); - } - /// #6419: Edit › Assign Profile… and Color Settings… show the panel scrolled to its Color /// Settings section, which a window shorter than the panel (a floated panel stops at 320 /// points) otherwise shows only after scrolling past the plates and Proof Setup. Once: the @@ -534,14 +527,15 @@ mod tests { #[test] fn color_settings_and_assign_profile_scroll_the_color_settings_into_view() { const BPC: &str = "Use Black Point Compensation"; + const HEIGHT: f32 = 200.0; for id in ["edit.assignProfile", "edit.colorSettings"] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({})).unwrap(); - let mut panel = Panel::new(app, scrolled); - panel.room(egui::vec2(300.0, 120.0)); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(300.0, HEIGHT)); panel.frame(); - // The section draws lazily: below the view it is not drawn at all. - assert!(!panel.shows(BPC) || !panel.in_view(BPC), "the section starts below the view"); + // The settings controls start below the view. + assert!(panel.rect(BPC).top() >= HEIGHT, "the section starts below the view"); panel.app().run(id, json!({})).unwrap(); panel.frame(); assert!(!panel.app().ui.color_settings_scroll, "{id}: the pass that read the request spent it"); @@ -549,11 +543,51 @@ mod tests { panel.advance(1.0); panel.frame(); panel.frame(); - assert!(panel.in_view(BPC), "{id} scrolls the section into the view"); + let shown = panel.rect(BPC); + assert!(panel.in_view(BPC) && shown.top() >= 0.0 && shown.bottom() <= HEIGHT, "{id} scrolls the section into the view: {shown:?}"); // PLAN: the harness has no scroll driver, so "a later scroll to the top stays there" is // covered only as far as the spent request not scrolling again. panel.frame(); - assert!(panel.in_view(BPC), "{id}: nothing scrolls it again"); + assert_eq!(panel.rect(BPC), shown, "{id}: nothing scrolls it again"); } } + + #[test] + fn a_short_separations_panel_scrolls_to_the_color_settings_actions() { + use craft::ui::testing::{Fixture, pointer}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.room(egui::vec2(220.0, 320.0)).settle(); + let at = |fixture: &Fixture, name| fixture.by_label(name).unwrap().rect; + assert!(at(&fixture, "Load Profile…").top() >= 320.0, "Color Settings starts below the view"); + for _ in 0..6 { + fixture.frame(vec![pointer::moved(egui::pos2(120.0, 250.0)), pointer::wheel(-300.0)]).settle(); + } + for name in ["Load Profile…", "Gamut Check"] { + let rect = at(&fixture, name); + assert!(rect.top() >= 0.0 && rect.bottom() <= 320.0, "{name} scrolls into the view: {rect:?}"); + } + } + + #[test] + fn tab_reaches_color_settings_before_any_manual_scroll() { + use craft::ui::testing::Fixture; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.room(egui::vec2(300.0, 120.0)).settle(); + let focused_gamut_check = |fixture: &Fixture| fixture.tree().name_of(fixture.tree().focused_key()) == Some("Gamut Check"); + for _ in 0..32 { + fixture.key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + if focused_gamut_check(&fixture) { + break; + } + } + assert!(focused_gamut_check(&fixture)); + let gamut = fixture.by_label("Gamut Check").unwrap().rect; + assert!(gamut.top() >= 0.0 && gamut.bottom() <= 120.0, "focused action scrolls into the view: {gamut:?}"); + } } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index e47111a613..d7406230d7 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -136,7 +136,7 @@ pub(crate) fn builtin_arrow_name(label: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label) } -/// The preview cache key of `a`: its name, and for a custom head its art. +/// The preview cache key of `a`: its name, and for a custom head its art and where the stroke ends. fn arrow_key(a: Option<&Arrowhead>) -> String { match a { Some(Arrowhead::Custom(c)) => { @@ -148,6 +148,7 @@ fn arrow_key(a: Option<&Arrowhead>) -> String { (p.x.to_bits(), p.y.to_bits()).hash(&mut h); } } + c.stop().to_bits().hash(&mut h); format!("custom:{}:{:x}", c.name, h.finish()) } _ => format!("{a:?}"), @@ -487,8 +488,13 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - let weight = fit(w - 6.0, long).min(fit(h / 2.0 - 1.0, half)).min(2.5); inset = -b.x0.min(0.0) * weight; if weight < LEAST { - let path = c.path.transformed(vectorcraft_geom::Affine::scale(weight / LEAST)); - a = Some(Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path)))); + let shrink = weight / LEAST; + let path = c.path.transformed(vectorcraft_geom::Affine::scale(shrink)); + let mut head = vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path); + if let Some(stop) = c.stop { + head = head.with_stop(stop * shrink); + } + a = Some(Arrowhead::Custom(std::sync::Arc::new(head))); } scale = scale.min(weight.max(LEAST) / WIDTH * 100.0); } @@ -735,6 +741,26 @@ mod tests { assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); } + #[test] + fn custom_arrowhead_thumbnails_preserve_where_the_stroke_ends() { + use vectorcraft_doc::CustomArrowhead; + use vectorcraft_geom::{PathData, Point, SubPath}; + + let outline = PathData::single(SubPath::polyline(&[Point::new(0.0, -60.0), Point::new(4.0, 60.0), Point::new(4.0, -60.0)], true)); + let custom = CustomArrowhead::new("Wide Flag".into(), outline); + let halfway = Arrowhead::Custom(std::sync::Arc::new(custom.clone())); + let explicit_stop = Arrowhead::Custom(std::sync::Arc::new(custom.with_stop(0.75))); + assert_ne!(arrow_key(Some(&halfway)), arrow_key(Some(&explicit_stop)), "each stroke attachment needs its own thumbnail"); + + let preview = arrow_doc(Some(explicit_stop), true, 56.0, 22.0).unwrap(); + let node = preview.node(preview.selectable_art()[0]).unwrap(); + let Some(Arrowhead::Custom(head)) = &node.appearance.stroke().unwrap().start_arrow else { + panic!("the preview should draw the custom arrowhead"); + }; + // The preview has 10 points above the line. At the minimum weight, 60 units would need 15. + assert_eq!(head.stop, Some(0.5)); + } + #[test] fn while_typing_the_panel_strokes_the_selected_characters() { use vectorcraft_doc::{LineJoin, NodeKind}; diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index e444ba1eba..3f85c1215a 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -6,14 +6,20 @@ //! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`). //! Everything reads `svgInteractivity.info`. -use craft::behavior::{IconId, Selection, keyed}; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use craft::behavior::{IconId, Selection, SelectionChange, keyed}; use craft::keymap::CommandRef; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; +use craft::ui::contract::{ + Bind, CollectionEvent, Entry, Politeness, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce, +}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; +use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow}; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; +use craft::ui::primitives::SubmitKey; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::sections::{FooterAction, FooterBar}; use craft::ui::text::TextField; @@ -34,6 +40,7 @@ const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents"; pub(crate) struct SvgInteractivityPanel { /// The event picked to edit ([`picked`] reads it). pub(crate) event: String, + list_stamp: u64, } /// The panel's values: whether there are targets, and their events (`None` where they differ). @@ -41,6 +48,7 @@ pub(crate) struct SvgInteractivityPanel { pub(crate) struct Info { has: bool, events: Option>, + script_target: Option, } /// What [`info`] was read for: (document uid, revision, selection size, first and last selected object). @@ -75,7 +83,12 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info { let events = r["events"] .as_array() .map(|a| a.iter().filter_map(|e| Some((e["event"].as_str()?.to_string(), e["script"].as_str()?.to_string()))).collect::>()); - let v = Info { has: r["ids"].as_array().is_some_and(|a| !a.is_empty()), events }; + let mut targets: Vec = r["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + targets.sort_unstable(); + let has = !targets.is_empty(); + // The editor's draft belongs to the actual targets, even if the selection is reordered. + let script_target = has.then(|| egui::IdSalt::new((key.0, targets))); + let v = Info { has, events, script_target }; app.canvas.svg_info = Some((key, v.clone())); v } @@ -96,54 +109,108 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let out = Select::new(caption("Event:"), Bind::given(event.to_string()), &names).enabled(info.has).show(ui); pick = out.events.committed().cloned(); }); + let menu_changed = pick.as_deref().is_some_and(|picked| picked != event); + let reveal = pick.as_ref().filter(|picked| menu_changed && events.iter().any(|(key, _)| key == *picked)).cloned(); // Blank where the objects' events differ; empty where none of them has the event. let script = info.events.as_ref().map(|l| l.iter().find(|(e, _)| e == event).map_or("", |(_, js)| js.as_str())); let shown = script.unwrap_or_default(); let mut typed = None; Field::new(caption("JavaScript:")).show(ui, |ui, _| { - let out = TextField::new(caption("JavaScript:"), Bind::given(shown.to_string())).lines(3).id_salt(event).enabled(info.has).show(ui); + let out = TextField::new(caption("JavaScript:"), Bind::given(shown.to_string())) + .lines(3) + .submits() + .submit_key(SubmitKey::Enter) + .id_salt((event, info.script_target)) + .enabled(info.has) + .show(ui); typed = out.events.committed().filter(|js| js.as_str() != shown).cloned(); }); let source = keyed(events, |(e, _): &(String, String)| e.clone()); - let selection = if events.iter().any(|(e, _)| e == event) { Selection::single(event.to_string()) } else { Default::default() }; - let list = List::::options(tl!("Events")) - .selection(Bind::given(selection)) - .sizing(Sizing::Fill) - // Event names and scripts are data: shown as they are. - .show_items(ui, &source, &mut |key, _| { - let js = events.iter().find(|(e, _)| e == key).map_or("", |(_, js)| js.as_str()); - ListRow::new(format!("{key}: {js}")) - }); - for e in list.events { - if let CollectionEvent::Activate(key) = e { - pick = Some(key); - } - } - if !info.has && selection_len(app) == 0 { - Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui); + let mut stamp = DefaultHasher::new(); + app.ui.svg_interactivity_panel.list_stamp.hash(&mut stamp); + for (key, _) in events { + key.hash(&mut stamp); } + let rows_stamp = stamp.finish(); + let mut remove = None; + let mut footer_pick = None; let has_doc = app.session.active().is_some(); let listed = events.iter().any(|(e, _)| e == event); - let footer = FooterBar::actions([ - FooterAction::new(IconId::new("trash"), tl!("Remove Selected Entry")).enabled(listed), - FooterAction::new(IconId::new("new_file"), tl!("Link JavaScript Files…")).enabled(has_doc), - ]) - .show_footer(ui); + Stack::new() + .fill() + .footer(|ui, _| { + let footer = FooterBar::actions([ + FooterAction::new(IconId::new("trash"), tl!("Remove Selected Entry")).enabled(listed), + FooterAction::new(IconId::new("new_file"), tl!("Link JavaScript Files…")).enabled(has_doc), + ]) + .show_footer(ui); + if !ui.is_sizing_pass() { + footer_pick = footer.picked; + } + }) + .show(ui, |ui, _| { + if !info.has && selection_len(app) == 0 { + Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui); + return; + } + let selection = if listed { Selection::single(event.to_string()) } else { Default::default() }; + let mut list = List::::new(tl!("Events")) + .select(SelectMode::Single) + .arrows_select(true) + .deletable(true) + .rows_stamp(rows_stamp) + .selection(Bind::given(selection)) + .sizing(Sizing::Fill); + if let Some(key) = reveal.as_ref() { + list = list.reveal(key.clone()); + } + // Event names and scripts are data: shown as they are. + let list = list.show_items(ui, &source, &mut |key, _| { + let js = events.iter().find(|(e, _)| e == key).map_or("", |(_, js)| js.as_str()); + ListRow::new(format!("{key}: {js}")) + }); + if ui.is_sizing_pass() { + return; + } + for e in list.events { + match e { + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { + if let Some(key) = keys.into_iter().next() { + pick = Some(key); + } + } + CollectionEvent::Activate(key) => pick = Some(key), + CollectionEvent::Delete(_) => { + remove = pick.as_deref().or(listed.then_some(event)).map(str::to_owned); + } + _ => {} + } + } + }); if let Some(e) = pick { - app.ui.svg_interactivity_panel.event = e; + let state = &mut app.ui.svg_interactivity_panel; + state.event = e; + if menu_changed { + // The list must seed its keyboard position from the new picker selection. + state.list_stamp = state.list_stamp.wrapping_add(1); + } } if let Some(js) = typed { app.run("svgInteractivity.setEvent", json!({ "event": event, "script": js })).ok(); } - match footer.picked { - Some(0) => { - app.run("svgInteractivity.removeEvent", json!({ "event": event })).ok(); - } + match footer_pick { + Some(0) => remove = Some(event.to_string()), Some(1) => { crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({})); } _ => {} } + if let Some(event) = remove + && app.run("svgInteractivity.removeEvent", json!({ "event": event })).is_ok_and(|out| out["changed"].as_u64().unwrap_or(0) > 0) + { + let message = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", &event)]); + announce(ui.ctx(), message, Politeness::Polite); + } } /// The panel (≡) menu's rows: Clear Events. @@ -176,10 +243,66 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn script_draft_does_not_follow_the_editor_to_other_artwork() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in ["First", "Second"] { + app.run("file.new", json!({ "name": name, "width": 100, "height": 100 })).unwrap(); + run(&mut app, "shape.rectangle", json!({ "x": 0, "y": 0, "width": 50, "height": 50 })); + } + let mut panel = Panel::new(app, show); + let field = caption("JavaScript:"); + let multiline = craft::ui::contract::Role::MULTILINE_TEXT_INPUT; + let doc = panel.app().session.active().unwrap().uid; + panel.click_role(field, multiline); + panel.type_text("1;"); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("1;")); + + panel.app().run("window.nextDocument", json!({})).unwrap(); + panel.frame(); + assert_ne!(panel.app().session.active().unwrap().uid, doc); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("")); + assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); + + panel.click_role(field, multiline); + panel.type_text("2;"); + let first = panel.app().session.active().unwrap().selection.objects[0].0; + let second = run(&mut panel.app(), "shape.ellipse", json!({ "x": 0, "y": 0, "width": 10, "height": 20 }))["id"].clone(); + panel.frame(); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("")); + assert_eq!(run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"], json!([])); + + run(&mut panel.app(), "select.set", json!({ "ids": [first, second] })); + panel.frame(); + panel.click_role(field, multiline); + panel.type_text("3;"); + run(&mut panel.app(), "select.set", json!({ "ids": [second, first] })); + panel.frame(); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some("3;")); + } + fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value { app.session.execute(id, &p).unwrap() } + #[test] + fn enter_applies_the_event_script_and_shift_enter_adds_a_line() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + let mut panel = Panel::new(app, show); + + panel.click_role(caption("JavaScript:"), craft::ui::contract::Role::MULTILINE_TEXT_INPUT); + panel.type_text("1;"); + panel.key(egui::Key::Enter, egui::Modifiers::SHIFT); + panel.type_text("2;"); + let events = |app: &mut VectorcraftApp| run(app, "svgInteractivity.info", json!({}))["events"].clone(); + assert_eq!(events(&mut panel.app()), json!([]), "the script is still a draft"); + + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(events(&mut panel.app()), json!([{"event": SVG_EVENTS[0], "script": "1;\n2;"}])); + } + // (Only names and scripts are checked: they are shown as they are, while tests running // alongside change the language the labels are drawn in.) #[test] @@ -215,4 +338,71 @@ mod tests { assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("")); assert!(info(&mut panel.app()).events.is_none()); } + + #[test] + fn keyboard_selection_edits_and_removes_the_chosen_event() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "2;"})); + let mut panel = Panel::new(app, show); + + panel.click("onclick: 1;"); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;")); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + + panel.click(caption("Event:")); + panel.click("onclick"); + panel.focus(tl!("Events")); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + + panel.key(egui::Key::ArrowUp, egui::Modifiers::SHIFT); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + let delete = + |pressed| egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + panel.frame_with(vec![delete(true)]); + let removed = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", "onmouseover")]); + assert!(panel.announces(&removed), "the removal is announced"); + panel.frame_with(vec![delete(false)]); + panel.frame(); + assert!(panel.shows("onclick: 1;")); + assert!(!panel.shows("onmouseover: 2;")); + assert_eq!(panel.app().session.active().unwrap().selection.objects.len(), 1); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;")); + panel.key(egui::Key::Delete, egui::Modifiers::NONE); + assert!(!panel.shows("onmouseover: 2;")); + panel.key(egui::Key::Delete, egui::Modifiers::NONE); + assert!(panel.shows("onclick: 1;"), "Delete must leave an unselected event alone"); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;")); + panel.click("Remove Selected Entry"); + assert!(!panel.shows("onclick: 1;")); + } + + #[test] + fn picking_an_event_reveals_its_row_in_a_short_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({ "width": 100, "height": 100 })); + run(&mut app, "shape.rectangle", json!({ "x": 0, "y": 0, "width": 50, "height": 50 })); + for (i, event) in SVG_EVENTS.into_iter().enumerate() { + run(&mut app, "svgInteractivity.setEvent", json!({ "event": event, "script": i.to_string() })); + } + let script = (SVG_EVENTS.len() - 1).to_string(); + let last = format!("{}: {script}", SVG_EVENTS.last().unwrap()); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(300.0, 220.0)); + panel.frame(); + assert!(!panel.shows(&last) || !panel.in_view(&last)); + + panel.click(caption("Event:")); + panel.key(egui::Key::End, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(script.as_str())); + assert!(panel.in_view(&last), "the picker scrolls the selected event into view"); + } } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9995752ec1..e7209609e3 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use craft::color_ui::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchKind use craft::color_ui::ui::{SwatchKey, SwatchesPanel, SwatchesState}; use craft::theme::Srgba; use craft::ui::choice::SwatchFace; -use craft::ui::contract::{Bind, DropAt, DropPlace, ListDrag, MemoProps, SelectMode}; +use craft::ui::contract::{Bind, DropPlace, ListDrag, MemoProps, SelectMode}; use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; @@ -407,22 +407,24 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { doc: Arc::clone(&st.doc), }; let dragged_doc = Arc::clone(&thumbs.doc); + let document = st.uid; let shown_app: &VectorcraftApp = app; - let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) + let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), _ => vec![], }) .row_items(|key| row_items(shown_app, key)) - .takes_drop::(DropPlace::Between, takes) - .takes_drop::(DropPlace::Onto, takes) + .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document)) + .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document)) .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) - .footer(None) - .show(ui); + .footer(None); + // A list drag is keyed by its browser ID. Each document has its own browser. + let out = ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner; app.ui.swatches_panel = model; let shown = shown_keys(&data); if let Some((at, _, alt)) = out.used @@ -467,12 +469,6 @@ fn on_event(app: &mut VectorcraftApp, shown: &[SwatchKey], event: PresetEvent) -> bool { - matches!(d, PanelDrag::Paint { .. } | PanelDrag::Art { .. }) -} - /// A double click or Enter: Swatch Options for a swatch, Edit or Apply Color Group for a group. fn activate(app: &mut VectorcraftApp, key: &SwatchKey) { match key { @@ -771,7 +767,8 @@ fn footer(app: &mut VectorcraftApp, ui: &mut Ui) { let opts = actions::editable(app, &sel); let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); - let rows_drag = |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(_), .. }); + let document = app.session.active().map(|state| state.uid); + let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); let edit = if group.is_some() { FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) } else { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index dd3aff50f9..097903063e 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,6 +4,16 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; +/// Swatches take paints, and take swatch rows or canvas art from the current document. +pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { + match drag { + PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, + PanelDrag::Paint { .. } => true, + PanelDrag::Art { document: source, .. } => *source == document, + _ => false, + } +} + /// A drag released on the panel. pub(super) enum Drop { /// Swatches (or colour groups) dropped before or `after` row `target`, into folder `target`, or @@ -44,7 +54,7 @@ impl Drop { /// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own /// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> PanelDrag { +pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { let name = name_of(key); let (paint, params) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name)), @@ -54,7 +64,7 @@ pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> Pane }, _ => (Paint::None, Value::Null), }; - let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; + let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } @@ -75,6 +85,9 @@ fn place(shown: &[SwatchKey], at: &DropAt) -> (Option, bool) /// `drag` dropped onto a swatch or between rows of the `shown` list (ap.AP2 `Dropped`); a gap with no /// row under the pointer is the end of the list. pub(super) fn on_dropped(app: &mut VectorcraftApp, shown: &[SwatchKey], at: &DropAt, drag: &PanelDrag, mods: Mods) { + if !app.session.active().is_some_and(|st| accepts(drag, st.uid)) { + return; + } let (target, after) = place(shown, at); if let Some(drop) = Drop::of(drag, target, after, mods) { apply_drop(app, drop); @@ -112,6 +125,9 @@ pub(super) enum FooterTarget { /// the button does. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; + if !app.session.active().is_some_and(|state| state.uid == r.document) { + return; + } let rows = footer_rows(app, r); match target { FooterTarget::Delete => { diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index b638b289f5..ee83ab240a 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::dialogs::swatch_options::KIND; use crate::tests::picks::{answer_dialog, cancel_dialog, draw_dialogs, open_dialogs}; use craft::keymap::Mods; -use craft::ui::contract::ReorderMove; +use craft::ui::contract::{DropAt, ReorderMove}; use craft::ui::dialog::DialogId; use egui::Pos2; use vectorcraft_color::Color; @@ -96,7 +96,61 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { /// The drag the row `name` starts, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - dnd::drag_of(&doc(app), &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) + let document = app.session.active().unwrap().uid; + dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) +} + +#[test] +fn a_swatch_row_drag_reorders_only_its_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, Role}; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let before_source = names_of(&app, None); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let destination = app.session.active().unwrap().uid; + let before_destination = names_of(&app, None); + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + + let mut panel = Panel::new(app, show); + let drag_red = |panel: &mut Panel| { + let red = "Red, #ed1c24"; + let from = panel.rect(red).center(); + let to = panel.rect("Green, #39b54a").center(); + panel.drag_hold_role(red, Role::LIST_ITEM, to - from); + let grabbed = drag::active::>(panel.ctx()).map(|d| d.grabbed.clone()); + assert_eq!(grabbed, Some(SwatchKey::Swatch("Red".into()))); + }; + drag_red(&mut panel); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + panel.release(); + assert_eq!(names_of(&panel.app(), None), before_destination); + + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, source); + assert_eq!(names_of(&panel.app(), None), before_source); + drag_red(&mut panel); + panel.release(); + assert_ne!(names_of(&panel.app(), None), before_source); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(names_of(&panel.app(), None), before_source); +} + +#[test] +fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { + let mut app = app(); + let drag = rows_drag(&app, "Red", &["Red"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let before = doc(&app); + assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid)); + dropped_below(&mut app, drag.clone(), none()); + dropped(&mut app, drag, "Green", alt()); + assert_eq!(doc(&app).swatches, before.swatches); } /// Art `ids` dragged off the canvas. @@ -551,6 +605,22 @@ fn drops_on_the_buttons_and_the_panel_run_their_commands() { } } +#[test] +fn footer_drops_ignore_rows_from_another_document() { + let mut app = app(); + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#ff8000"})).unwrap(); + let before = doc(&app); + let undo = undo_steps(&app); + for target in [dnd::FooterTarget::New, dnd::FooterTarget::Delete] { + dnd::on_footer_drop(&mut app, target, &drag); + assert_eq!(doc(&app), before); + assert_eq!(undo_steps(&app), undo); + assert!(!dialog_open(&app, crate::dialogs::confirm::KIND)); + } +} + /// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that /// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch /// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection @@ -602,6 +672,29 @@ fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { assert_eq!(doc(&app).node(vectorcraft_doc::NodeId(id)), before.node(vectorcraft_doc::NodeId(id)), "the art stays as it was"); } +#[test] +fn swatches_ignore_artwork_from_another_document_with_the_same_object_id() { + let mut app = app(); + let shape = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + let source = app.run("shape.rectangle", shape.clone()).unwrap()["id"].as_u64().unwrap(); + let drag = art_drag(&app, vec![vectorcraft_doc::NodeId(source)]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let local = app.run("shape.rectangle", shape).unwrap()["id"].as_u64().unwrap(); + assert_eq!(source, local); + + dropped_below(&mut app, drag.clone(), none()); + assert!(doc(&app).patterns.is_empty(), "foreign artwork cannot create a pattern"); + + let star = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap(); + let local_drag = art_drag(&app, vec![vectorcraft_doc::NodeId(star)]); + dropped_below(&mut app, local_drag, none()); + assert_eq!(doc(&app).patterns.len(), 1, "the same document's artwork can create a pattern"); + let before = doc(&app).patterns[0].clone(); + let name = before.name.clone(); + dropped(&mut app, drag, &name, alt()); + assert_eq!(doc(&app).patterns[0].art, before.art, "foreign artwork cannot replace an existing pattern"); +} + /// Art released with Alt held over a pattern swatch becomes that pattern's tile art in one undo /// step: no pattern or swatch is added and the art stays. With Alt over a color swatch, or without /// Alt over the pattern swatch, the art becomes a new pattern swatch. diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index bde196ffd2..e14e6c0ea3 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -56,6 +56,56 @@ fn assets(app: &mut VectorcraftApp) -> Vec { app.run("assets.list", json!({})).unwrap()["assets"].as_array().unwrap().clone() } +/// Draws a row carrying the selected artwork's payload above the Asset Export panel. +fn art_and_assets(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + + let st = app.session.active().unwrap(); + let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + super::asset_export::show(app, ui); +} + +#[test] +fn asset_export_accepts_artwork_only_from_its_document() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let mut rectangle = |x| { + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let first = rectangle(10); + let second = rectangle(70); + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + let source = app.session.active().unwrap().uid; + + let mut p = Panel::new(app, art_and_assets); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("No assets").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_some(), "Asset Export accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_none(), "Asset Export withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert!(assets(&mut p.app()).is_empty(), "the foreign drag must never collect the active document's same-ID artwork"); + + p.drag("Dragged artwork", "No assets", egui::Modifiers::NONE); + let list = assets(&mut p.app()); + assert_eq!(list.len(), 1, "dropping artwork from the active document still collects it"); + assert_eq!(list[0]["nodes"], json!([second])); +} + /// The document's export settings, which the panel and Export for Screens share. fn settings(p: &Panel) -> Value { run(p, "document.exportSettings", json!({}))["settings"].clone() diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 1485986f31..3cd0167b50 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -7,11 +7,72 @@ use std::rc::Rc; use craft::ui::testing::focus::AccessActionKind; use craft::ui::testing::{Fixture, Target}; use egui::{Key, Modifiers, vec2}; -use serde_json::Value; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; use super::color_wheel::show; use crate::VectorcraftApp; +/// An app with a selected rectangle filled with `fill`. +fn app(fill: &str) -> 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": fill})).unwrap(); + app +} + +/// A hue given to a gray is remembered only until the document's next undo step: after the paint +/// changes and the same gray comes back while the rows are hidden, the rows show the gray's own hue. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes_while_the_rows_are_hidden() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut a = app("#808080"); + a.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut p = Panel::new(a); + p.set(hue, 240.0); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the gray keeps the hue it was given"); + p.run("ui.colorWheel", json!({"sliders": "none"})); + p.run("paint.setFill", json!({"color": "#ff0000"})); + p.run("paint.setFill", json!({"color": "#808080"})); + p.run("ui.colorWheel", json!({"sliders": rows})); + assert_ne!(p.number(hue), Some(240.0), "{rows}: the remembered hue is dropped"); + } +} + +/// `sliders: "oklch"` follows the active document's RGB space: it is an error in a document assigned +/// Display P3 while the working RGB space is sRGB, and is taken in a document without a profile. +#[test] +fn oklch_sliders_follow_the_active_documents_rgb_space() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_DOC_PROFILE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: assign the profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel::oklch_sliders_follow_the_active_documents_rgb_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated document profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + let mut a = app("#339966"); + a.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + a.run("edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let mut p = Panel::new(a); + assert!(cms::working_settings().rgb != cms::DISPLAY_P3, "the working RGB space is not Display P3"); + let refused = p.app_mut().run("ui.colorWheel", json!({"sliders": "oklch"})); + assert!(refused.is_err(), "{refused:?}"); + p.run("document.activate", json!({"index": 0})); + p.run("ui.colorWheel", json!({"sliders": "oklch"})); + assert_eq!(p.app().ui.color_wheel.sliders, super::color_wheel::Sliders::Oklch); +} + /// The app shown through the panel's `show`, driven by the parts' names and keys. // PLAN: sh.SH4 `crate::testing::ui_context()` has no entry point on `Fixture` here, so the app's fonts are not installed. pub(super) struct Panel { 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 27def08cd7..ea7aec7096 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -165,6 +165,23 @@ fn screen_readers_read_and_set_the_opacity() { assert!((fill_opacity(&p.app()) - 0.24).abs() < 1e-6); } +/// A hue given to a gray in the HSL or OKLCH rows stays after the row's opacity edit, as the wheel's +/// HSB hue does. +#[test] +fn an_opacity_edit_keeps_the_hue_given_to_a_gray() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut a = app(); + a.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + a.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut p = Panel::new(a); + p.set(hue, 240.0); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the gray takes the hue"); + act(&mut p, AccessActionKind::SetValue(40.0)); + assert!((fill_opacity(&p.app()) - 0.4).abs() < 1e-6, "{rows}: the opacity is set"); + assert_eq!(p.number(hue), Some(240.0), "{rows}: the hue is kept"); + } +} + /// The stroke proxy in front: the row sets the stroke item's opacity and leaves the fill's. #[test] fn with_the_stroke_in_front_the_row_sets_the_stroke() { diff --git a/crates/ui-egui/src/panels/tests_effectedit.rs b/crates/ui-egui/src/panels/tests_effectedit.rs index 3d2a921678..656262c2b2 100644 --- a/crates/ui-egui/src/panels/tests_effectedit.rs +++ b/crates/ui-egui/src/panels/tests_effectedit.rs @@ -163,6 +163,39 @@ fn alt_dragging_an_item_duplicates_it_and_several_items_delete_together() { assert_eq!(kinds(&panel).len(), 3, "one undo step"); } +#[test] +fn an_appearance_row_drop_after_next_document_leaves_the_new_stack_alone() { + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = app_with_rect(); + let first = app.session.active().unwrap().uid; + run(&mut app, "file.new", json!({"width": 400, "height": 300})); + run(&mut app, "shape.rectangle", json!({"x": 20, "y": 30, "width": 50, "height": 30})); + let second = app.session.active().unwrap().uid; + let kinds = |app: &VectorcraftApp| first_selected(app).unwrap().appearance.items.iter().map(|item| item.kind_name()).collect::>(); + let before = kinds(&app); + assert_eq!(before, ["fill", "stroke"]); + assert!(app.session.set_active(0)); + + let mut panel = Panel::new(app, appearance::show); + let from = row_spot(&mut panel, "Stroke:"); + let to = panel.rect("Delete Selected Item").center(); + panel.drag_hold_between(from, to); + assert!(drag::mark(panel.ctx()).is_some(), "the footer accepts the stroke before switching documents"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, second); + assert!(drag::mark(panel.ctx()).is_none(), "the footer withdraws the drop indicator after the document switch"); + panel.release(); + assert_eq!(kinds(&panel.app()), before, "the active document's stroke stays in its own stack"); + + drag_row(&mut panel, "Stroke:", "Delete Selected Item", Modifiers::NONE); + assert_eq!(kinds(&panel.app()), ["fill"], "a stroke from the active document can still be removed by dragging"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, first); + assert_eq!(kinds(&panel.app()), ["fill", "stroke"], "the original document keeps its stroke"); +} + #[test] fn stroke_rows_note_dashes_brushes_and_show_all_hidden_attributes() { let mut panel = Panel::new(app_with_rect(), appearance::show); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 7c07781d02..6f9a6c5046 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -663,6 +663,41 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } +#[test] +fn switching_documents_dismisses_a_links_row_menu() { + let dir = Folder::new("context-switched-document"); + let (mut app, first, _) = app(&dir); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let path = dir.file("other.png", &png(40, 20)); + let second = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents have different images at the same local ID"); + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, super::links::show); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + panel.secondary_click("linked.png"); + assert!(panel.menu_item_enabled("Embed Image")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Embed Image"), "the other document must not inherit the row menu"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["linked"], true); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Embed Image"), "switching back must not revive the menu"); + assert_eq!(panel.app().run("links.info", json!({"id": first})).unwrap()["linked"], true); + + activate(&mut panel, 1, destination); + panel.secondary_click("other.png"); + panel.click_menu_item("Embed Image"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["status"], "embedded"); +} + #[test] fn right_click_context_menu_in_links_panel() { let dir = Folder::new("context-menu"); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index e249c1ea95..01ed51a6a6 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -74,7 +74,15 @@ fn the_document_info_rows_wrap_in_a_narrow_panel_in_german() { #[test] fn the_magic_wand_rows_wrap_in_a_narrow_panel_in_french() { - let past = past_a_narrow_panel("magicWand", "fr", &["Tolerance:"]); + use crate::i18n::{Lang, LangExt as _, tr}; + + let captions = ["Tolerance:"]; + let panel = floated(app_with_rect(), "magicWand", "fr", Place::Floating(PANEL_MIN_WIDTH), &captions); + let prefix = format!("{} ", tr(Lang::from_code("fr").unwrap(), "Tolerance:")); + let fields: Vec<_> = panel.nodes.iter().filter(|(name, _)| name.starts_with(&prefix)).cloned().collect(); + assert_eq!(fields.len(), 4, "{fields:?}"); + let mut past = panel.past_named(&captions); + past.extend(panel.past(fields)); assert!(past.is_empty(), "past the panel: {past:?}"); } diff --git a/crates/ui-egui/src/panels/tests_script_console.rs b/crates/ui-egui/src/panels/tests_script_console.rs index c67218ba0b..71766dce0a 100644 --- a/crates/ui-egui/src/panels/tests_script_console.rs +++ b/crates/ui-egui/src/panels/tests_script_console.rs @@ -8,7 +8,9 @@ use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_engine::script::console::{Ending, Entry}; -use super::script_console::{menu_states, shown}; +use super::script_console::{menu_states, show, shown}; +use crate::panel_docking::PANEL_MIN_WIDTH; +use crate::tests::panel_harness::{Panel, Place, ROOM, floated}; use crate::{Services, VectorcraftApp, script_runs}; fn app() -> VectorcraftApp { @@ -37,6 +39,44 @@ fn enabled(app: &VectorcraftApp, id: &str) -> bool { states.get(&CommandRef::new(id)).is_some_and(|s| s.is_enabled()) } +#[test] +fn the_console_footer_stays_inside_the_panel_at_minimum_width() { + let names = ["Clear", "Copy Selected", "Copy All"]; + for lang in ["en", "fr", "de"] { + let mut app = app(); + run(&mut app, "$.writeln('one')"); + let panel = floated(app, "scriptConsole", lang, Place::Floating(PANEL_MIN_WIDTH), &names); + for name in names { + let bounds = panel.rects(name); + assert!( + bounds.iter().all(|rect| panel.body.expand(0.5).contains_rect(*rect)), + "{lang}: {name} at {bounds:?} is outside {:?}", + panel.body + ); + } + } + + let wide = floated(app(), "scriptConsole", "en", Place::Floating(380.0), &names); + assert!(wide.middles(&names).windows(2).all(|pair| (pair[0] - pair[1]).abs() < 1.0), "the wide footer uses one row"); +} + +#[test] +fn the_console_footer_buttons_run_their_commands_at_minimum_width() { + let mut app = app(); + run(&mut app, "$.writeln('one'); $.writeln('two')"); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(PANEL_MIN_WIDTH, ROOM.y)).frame(); + assert!(!panel.enabled("Copy Selected")); + panel.click("#1 c.js: one"); + panel.click("Copy Selected"); + assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: one")); + panel.click("Copy All"); + assert!(panel.app().clipboard_out.take().is_some_and(|text| text.contains("#1 c.js: two"))); + panel.click("Clear"); + assert!(panel.app().session.script_console().lines().is_empty()); + assert!(!panel.enabled("Copy All")); +} + #[test] fn clear_works_during_a_run_and_the_run_goes_on_writing() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index e13cf649a6..cc1c1593da 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -686,6 +686,54 @@ fn art_can_be_added_as_a_graphic_before_any_3d_effect() { assert!(painted_text(&mut app, show).contains("Add as Single Graphic")); } +#[test] +fn three_d_graphics_accepts_artwork_only_from_its_document() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + let add_existing = |app: &mut VectorcraftApp| app.run("threeD.addGraphic", json!({"name": "Existing Graphic"})).unwrap(); + add_existing(&mut app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + add_existing(&mut app); + assert_eq!(first.0, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + + let mut p = Panel::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Existing Graphic").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphics accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphics withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 1, "the foreign drop adds no symbol from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Existing Graphic", egui::Modifiers::NONE); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 2, "a same-document drop still makes a graphic"); +} + #[test] fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { let (mut app, _) = materials_app(); diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index dbd7447b34..bfcffa6e65 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -66,6 +66,8 @@ impl StylesPanels { pub(crate) struct StylesPanel { /// The uid of the document the highlight was made in. document: Option, + /// Changes when the panel switches documents, so reopening a document cannot restore its old popup. + scope_generation: u64, /// The highlighted styles, in the order they were picked. highlight: Vec, /// The selection's lead style. @@ -83,7 +85,7 @@ fn highlighted(app: &mut VectorcraftApp, kind: Kind, listed: &[&str]) -> Vec = listed.iter().enumerate().map(|(i, name)| TextStyleRow::new(i as u64, super::label_or_name(name, i == 0))).collect(); @@ -271,7 +274,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if let Some(id) = reveal.as_deref().and_then(id_of) { list = list.reveal(id); } - let out = list.show(ui); + // The framework's row menu and footer drag use list indices that are local to this document. + let out = ui.push_id(("text-styles-document", kind.panel_kind(), scope), |ui| list.show(ui)).inner; let name_of = |id: &u64| listed.get(*id as usize).map(|n| n.to_string()); let panel = app.ui.text_styles.of(kind); panel.highlight = sel.items.iter().filter_map(name_of).collect(); diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index 3e80710437..5144f8ce9a 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -4,6 +4,54 @@ use crate::tests::picks::{answer_dialog, cancel_dialog, open_dialogs, poll, scri use crate::tests::synthetic::key_frame; use vectorcraft_doc::{NodeId, NodeKind}; +#[test] +fn switching_documents_dismisses_text_styles_row_menus() { + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + for kind in [Kind::Char, Kind::Para] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let command = format!("{}.new", kind.prefix()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "First Style"})).unwrap(); + let first = style_id(&mut app, kind, "First Style"); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "Second Style"})).unwrap(); + let second = style_id(&mut app, kind, "Second Style"); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents carry styles at the same list index"); + app.run("window.previousDocument", json!({})).unwrap(); + + let draw: fn(&mut VectorcraftApp, &mut Ui) = match kind { + Kind::Char => |app, ui| show(app, ui, Kind::Char), + Kind::Para => |app, ui| show(app, ui, Kind::Para), + }; + let mut panel = Panel::new(app, draw); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + let has_copy = |panel: &Panel, name: &str| styles(&mut panel.app(), kind).iter().any(|style| style.0 == name); + panel.secondary_click("First Style"); + assert!(panel.menu_item_enabled("Duplicate Style")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Duplicate Style"), "the new document does not inherit the row menu"); + assert!(!has_copy(&panel, "Second Style copy")); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Duplicate Style"), "the old row menu does not reappear"); + assert!(!has_copy(&panel, "First Style copy")); + + activate(&mut panel, 1, destination); + panel.secondary_click("Second Style"); + panel.click_menu_item("Duplicate Style"); + assert!(has_copy(&panel, "Second Style copy")); + } +} + // PLAN: assumed type-w19 items reachable through `super::*`: `run_action(app, kind, action)`, // `StylesPanel { highlight: Vec, .. }` and `StylesPanels { char, para, made }` at // `app.ui.text_styles`, `highlighted(app, kind, listed: &[&str]) -> Vec`, `TextStyleAction`, and a diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index b418d3d2b4..e08d0bf603 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -546,6 +546,8 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } if !opening_menu => { acts.extend(keys.into_iter().next().map(Act::Click)); } + // A click on the highlighted row changes no selection, and still selects what it drives. + CollectionEvent::Picked { key, .. } if !opening_menu => acts.push(Act::Click(key)), CollectionEvent::Activate(name) if !states.locked => acts.push(Act::Options(name)), _ => {} } @@ -1240,6 +1242,30 @@ mod tests { assert_eq!(sets["datasets"][0]["name"], "Data Set 2"); } + /// A click on the highlighted row selects what it drives again, as a click on any other row + /// does: after the art is deselected on the canvas, the row stays highlighted, and a second + /// click on it selects the bound object. + #[test] + fn a_click_on_the_highlighted_row_selects_its_bound_object_again() { + use crate::tests::panel_harness::Panel; + let mut app = app_with_data(); + let bound = app.session.doc().unwrap().doc.variables.objects_of("Name")[0]; + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let mut p = Panel::new(app, show); + let selected = |p: &Panel| p.app().session.doc().unwrap().selection.objects.clone(); + let highlighted = |p: &Panel| highlighted_row(p.app().session.doc().unwrap()); + p.click("Name"); + assert_eq!(highlighted(&p).as_deref(), Some("Name")); + assert_eq!(selected(&p), vec![bound], "the first click selects the bound object"); + p.app().session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(selected(&p).is_empty()); + // A second later, so the two clicks are not a double click. + p.advance(1.0); + p.click("Name"); + assert_eq!(highlighted(&p).as_deref(), Some("Name")); + assert_eq!(selected(&p), vec![bound], "a click on the highlighted row selects the bound object again"); + } + /// The rows as the panel built them on every frame before [`cached_rows`] kept them: the /// identity checks compare against it. fn old_rows(st: &DocState, xml_id: bool) -> Rows { diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 7163a20cf0..04a800ede3 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -304,9 +304,9 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { let r = crate::placing::start(app, &p, dropped); diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 6be029beba..f6fbeef6a2 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -658,7 +658,7 @@ pub(crate) fn settle_swatch_paste(app: &mut VectorcraftApp) { let command = answer["command"].as_str().unwrap_or_default().to_string(); let seen = answer["asked"].clone(); let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| match question { - Question::SwatchConflict => crate::dialogs::swatch_conflict::changed(app, params, &seen), + Question::SwatchConflict => crate::dialogs::swatch_conflict::changed(app, command, params, &seen), Question::ProfileMismatch => { crate::dialogs::profile_mismatch::paste_changed(app, command, params, seen.as_array().map_or(&[], Vec::as_slice)) } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index b1d2c72616..5a66573eef 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -22,6 +22,7 @@ use crate::i18n::LangExt as _; mod descriptions; mod model; mod runtime; +mod script_access; pub use runtime::*; @@ -52,6 +53,9 @@ pub struct PrefsWindow { reset_asked: Option, /// The draft's text and choice values, which the model's rows borrow (the draft hands out owned values only). strings: std::collections::BTreeMap, + /// General › Script File Access: the file access kept with Always, read when the window opens; `None` where the + /// session keeps none (no settings folder, and the web). + script_access: Option, } impl PrefsWindow { @@ -140,6 +144,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { draft.set("__snapToGrid", &app.ui.view.snap_to_grid); draft.set("__taskBar", &app.ui.task_bar); let selected = category.and_then(|c| PREF_CATEGORIES.iter().find(|x| x.eq_ignore_ascii_case(c))).copied().unwrap_or(PREF_CATEGORIES[0]); + let script_access = script_access::load(app); let mut w = PrefsWindow { state: PreferencesState::default(), opened: draft.clone(), @@ -148,6 +153,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { nested: DialogHost::new(), reset_asked: None, strings: Default::default(), + script_access, }; w.state.selected = selected.to_string(); w.sync_strings(); @@ -210,12 +216,15 @@ pub(crate) fn draft_language(app: &VectorcraftApp) -> Option Some(crate::i18n::Lang::from_pref(&code)) } -/// The draft as JSON, plus `__category` and `__search`; `None` while the window is closed. +/// The draft as JSON, plus `__category`, `__search` and General › Script File Access's rows and error +/// (`__scriptAccess`, `__scriptAccessError`, each script and path named as `script.grants` names it to the request +/// being served); `None` while the window is closed. pub(crate) fn fields(app: &VectorcraftApp) -> Option> { let w = app.prefs.as_ref()?; let mut fields = w.draft.to::>().unwrap_or_default(); fields.insert("__category".into(), json!(w.state.selected)); fields.insert("__search".into(), json!(w.state.search)); + script_access::inspect(w.script_access.as_ref(), &mut fields); Some(fields) } diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 6aa1c4cd8b..5835cd1684 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -18,6 +18,10 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("showToolTips", "Shows a tip when the pointer rests on a button or field that has one."), ("showToolCards", "Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips."), ("showExternalScriptWarning", "Shows a warning before a script you choose runs."), + ( + "runStartupScripts", + "Runs the scripts in the Startup Scripts folder when VectorCraft starts and before each script from File › Scripts; not in Safe Mode.", + ), ("antiAliasedArtwork", "Smooths the edges of artwork on the canvas."), ( "selectSameTintPercent", diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 25740a3dce..217bb592b6 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -17,7 +17,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_engine::Prefs; use vectorcraft_engine::cmd::prefscmds::{PREF_CATEGORIES, PREF_SPECS, PrefKind, PrefSpec, folder_check, spec}; -use super::{APP_TITLE_BAR_SHOWN, PrefsWindow, UI_FIELDS, descriptions}; +use super::{APP_TITLE_BAR_SHOWN, PrefsWindow, UI_FIELDS, descriptions, script_access}; use crate::VectorcraftApp; use crate::i18n::{Lang, LangExt as _}; use craft::color_ui::ui::ColorPickerDialog; @@ -129,6 +129,8 @@ impl Live<'_> { "appTitleBar" => APP_TITLE_BAR_SHOWN, "linuxDisplayServer" => cfg!(target_os = "linux"), "monitorProfileDisplay" | "lowLatencyDrawing" => !cfg!(target_arch = "wasm32"), + // Only where the session keeps script grants: not without a settings folder, and not on the web. + script_access::KEY => self.w.script_access.is_some(), "editOriginal" => self.app.services.check_application.is_some() && self.app.services.open_in_application.is_some(), _ => true, } @@ -258,6 +260,10 @@ impl Live<'_> { if sp.key == "editOriginalSystemDefaults" { groups.add(sp.section, self.row("editOriginal", "", "Edit Original with PhotoCraft", RowKind::Custom)); } + if sp.key == "showExternalScriptWarning" { + let english = "Script File Access revoke read write file folder"; + groups.add(sp.section, self.row(script_access::KEY, tl!("Script File Access"), english, RowKind::CustomRows)); + } } if cat == PREF_CATEGORIES[0] { let tools = self.row("prefsFile", "", "export import reset preferences", RowKind::Custom); @@ -360,6 +366,10 @@ impl PreferencesModel for Live<'_> { crate::original_editor::show(self.app, ui, enabled); false } + script_access::KEY => { + script_access::show(self.app, &mut self.w.script_access, ui); + false + } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); let web = crate::io::is_web(self.app); diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs new file mode 100644 index 0000000000..b0de2cd30d --- /dev/null +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -0,0 +1,277 @@ +//! Preferences › General › Script File Access: the file access people allowed scripts with Always +//! Allow This Script in a script's file dialog (`script.grants`), one row for each script and path, +//! each with a Revoke button (`script.grants.revoke`). + +use std::collections::BTreeMap; + +use craft::theme::TypeRole; +use craft::theme::variant::Tone; +use craft::ui::buttons::Button; +use craft::ui::contract::{Lazy, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; +use craft::ui::display::{Elide, Shade, Text}; +use craft::ui::layout_components::{Row as Line, Stack}; +use craft::ui::runtime::focus::FocusRequest; +use serde_json::{Map, Value, json}; +use vectorcraft_plugins::permissions; + +use crate::VectorcraftApp; + +/// The key of the section's row in General, after Show External Script Warning. +pub(super) const KEY: &str = "scriptAccess"; + +/// The field of `ui.inspect`'s Preferences dialog that holds the rows, `[{script, path, access, versions}]`. +/// It is absent where the session keeps no grants (no settings folder, and the web), and the section is not shown. +pub(super) const ROWS: &str = "__scriptAccess"; + +/// The field of `ui.inspect`'s Preferences dialog that holds, in English, why the grants file cannot be read +/// (`script.grants`' error), absent when it can. +pub(super) const ERROR: &str = "__scriptAccessError"; + +/// The most characters of a path a row shows. +const MAX_SHOWN_PATH: usize = 1024; + +/// How tall a line of the list is taken to be before it was first shown. +const LINE_ESTIMATE: f32 = 30.0; + +/// The height the list offers its lines before it scrolls. +const LIST_HEIGHT: f32 = 180.0; + +/// One script and path with kept access. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Grant { + /// The script file's path, whole, for `script.grants.revoke`. + script: String, + /// The allowed file or folder's path, whole, for `script.grants.revoke`. + path: String, + /// The script as the request that opened Preferences may see it ([`as_listed`]). + shown_script: String, + /// The path as the request that opened Preferences may see it ([`as_listed`]). + shown_path: String, + /// The widest access any kept version has: `folder`, `write` or `read`. + access: &'static str, + /// How many versions of the script keep access to the path. + versions: usize, +} + +/// The section's state while Preferences is open: the rows, why the grants file cannot be read, and the row whose +/// Revoke button takes the keyboard focus next. +#[derive(Debug, Default)] +pub(super) struct Access { + rows: Vec, + error: Option, + focus: Option, +} + +/// The kept grants (`script.grants`), or `None` where the session keeps none (no settings folder, and the web), and +/// the section is not shown. The grants file is the app's own, so it is read with no automation roots in force: each +/// row keeps its script and path whole for `script.grants.revoke`, and shows them as `script.grants` names them to +/// the request that opened Preferences ([`as_listed`]). When the grants file cannot be read, the section holds the +/// error and no rows. +pub(super) fn load(app: &mut VectorcraftApp) -> Option { + match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { + Ok(v) if v["file"].is_null() => None, + Ok(v) => Some(Access { rows: rows(&v["grants"]), error: None, focus: None }), + Err(e) => Some(Access { rows: Vec::new(), error: Some(e.to_string()), focus: None }), + } +} + +/// The rows for the grants `grants` lists: one for each script and path, sorted by script and then by path, with the +/// widest access any kept version of the pair has (`folder`, then `write`, then `read`) and how many versions are +/// kept. A grant without a script or a path, or with an empty one, which `script.grants.revoke` does not take, is +/// left out. +fn rows(grants: &Value) -> Vec { + let rank = |access: &str| match access { + "folder" => 2, + "write" => 1, + _ => 0, + }; + let mut pairs: BTreeMap<(&str, &str), (&'static str, usize)> = BTreeMap::new(); + for g in grants.as_array().into_iter().flatten() { + let (Some(script), Some(path)) = (g["script"].as_str(), g["path"].as_str()) else { continue }; + if script.is_empty() || path.is_empty() { + continue; + } + let access = if g["folder"] == true { + "folder" + } else if g["write"] == true { + "write" + } else { + "read" + }; + let pair = pairs.entry((script, path)).or_insert((access, 0)); + if rank(access) > rank(pair.0) { + pair.0 = access; + } + pair.1 += 1; + } + pairs + .into_iter() + .map(|((script, path), (access, versions))| Grant { + script: script.to_string(), + path: path.to_string(), + shown_script: as_listed(script).to_string(), + shown_path: as_listed(path).to_string(), + access, + versions, + }) + .collect() +} + +/// `path` as a row shows it: control and bidirectional formatting characters written as escapes, and at most +/// [`MAX_SHOWN_PATH`] characters. +pub(super) fn shown(path: &str) -> String { + permissions::display_text(path, MAX_SHOWN_PATH) +} + +/// `path` as a row's tooltip and its Revoke button's screen-reader description give it: control and bidirectional +/// formatting characters written as escapes, and whole, so two paths that a row shows alike stay apart. +fn shown_whole(path: &str) -> String { + permissions::display_text(path, usize::MAX) +} + +/// A kept script or path as `script.grants` names it to the request being served: whole where that request may read +/// it, else its file name alone (empty for a path that ends in no name). +fn as_listed(path: &str) -> &str { + if vectorcraft_engine::file_access::check_read(path).is_ok() { + return path; + } + let name = path.rsplit(vectorcraft_doc::links::path_separators(path)).next().unwrap_or_default(); + if matches!(name, "." | "..") { "" } else { name } +} + +/// Puts the section in `fields`, the Preferences dialog `ui.inspect` shows: the rows in [`ROWS`], each script and +/// path as [`as_listed`] gives it to the request being served, and the error in [`ERROR`]. +pub(super) fn inspect(access: Option<&Access>, fields: &mut Map) { + let Some(access) = access else { return }; + let rows = access + .rows + .iter() + .map(|g| json!({"script": as_listed(&g.script), "path": as_listed(&g.path), "access": g.access, "versions": g.versions})) + .collect(); + fields.insert(ROWS.into(), Value::Array(rows)); + if let Some(error) = &access.error { + fields.insert(ERROR.into(), json!(error)); + } +} + +/// The label of a row's access. +fn access_label(access: &str) -> &'static str { + match access { + "folder" => tl!("Read and write folder"), + "write" => tl!("Read and write file"), + _ => tl!("Read file"), + } +} + +/// A line of the list: the script that the rows below it belong to, or a row, by its index. +enum Entry { + Script(usize), + Grant(usize), +} + +/// The section: its heading, each script, its paths with their access and a Revoke button, or a line saying there +/// are none. When the grants file cannot be read, its error shows in place of that line. Nothing shows without +/// `access`. +pub(super) fn show(app: &mut VectorcraftApp, access: &mut Option, ui: &mut egui::Ui) { + let Some(state) = access.as_mut() else { return }; + Text::new(tl!("Script File Access")).role(TypeRole::BodyStrong).show(ui); + if let Some(error) = &state.error { + Text::new(crate::i18n::msg(error).to_string()).tone(Tone::Bad).show(ui); + } + if state.rows.is_empty() { + if state.error.is_none() { + Text::new(tl!("No script has kept file access.")).shade(Shade::Muted).show(ui); + } + return; + } + let rows = &state.rows; + let mut lines = Vec::with_capacity(rows.len() * 2); + for (i, row) in rows.iter().enumerate() { + if i == 0 || rows[i - 1].script != row.script { + lines.push(Entry::Script(i)); + } + lines.push(Entry::Grant(i)); + } + let focus = state.focus.take(); + // The body returns the row whose Revoke was clicked; the revoke runs after the list is shown. + let list = Stack::new().id_salt("prefs-script-access").label(tl!("Script File Access")).fill_width(); + let shown_list = list.scroll(Scroll::vertical()).room_height(LIST_HEIGHT).show(ui, |ui, _| { + let mut clicked = None; + // Each line runs only while it is in view, so a long list costs no more per frame than a short one. + for line in &lines { + match *line { + Entry::Script(i) => { + let script = &rows[i].shown_script; + Lazy::new(("prefs-script", i), LINE_ESTIMATE).show(ui, |ui| { + Text::new(shown(script)).role(TypeRole::BodyStrong).elide(Elide::Path).tooltip(shown_whole(script)).show(ui); + }); + } + Entry::Grant(i) => { + let row = &rows[i]; + let shown_line = Lazy::new(("prefs-script-row", i), LINE_ESTIMATE).reveal(focus == Some(i)).show(ui, |ui| { + let (script, path) = (shown_whole(&row.shown_script), shown_whole(&row.shown_path)); + let line = Line::new().id_salt(("prefs-script-row", i)).show(ui, |ui, _| { + Text::new(shown(&row.shown_path)).elide(Elide::Path).sizing(Sizing::FillWidth).tooltip(path.clone()).show(ui); + Text::new(access_label(row.access)).shade(Shade::Muted).show(ui); + // A screen reader names the script and the path along with the button. + let mut button = Button::new(tl!("Revoke")).id_salt(("prefs-script-revoke", i)).tooltip(path.clone()); + button = button.description(format!("{script}: {path}")); + if focus == Some(i) { + button = button.request_focus(FocusRequest::Take); + } + button.show(ui).clicked() + }); + line.inner + }); + if shown_line.flatten() == Some(true) { + clicked = Some(i); + } + } + } + } + clicked + }); + let revoke_at = shown_list.inner.flatten(); + Text::new(tl!("Revoke removes the access kept for every version of the script. A folder's access covers everything in it.")) + .shade(Shade::Muted) + .show(ui); + if let Some(i) = revoke_at { + revoke(app, access, i); + } +} + +/// Revoke on the row `i`: every kept grant of its script and path, whole, is removed (`script.grants.revoke`), the +/// rows are read again and the row now at `i`, or the last row, takes the keyboard focus. The status bar says what +/// happened; on an error the rows stay as they were. +pub(super) fn revoke(app: &mut VectorcraftApp, access: &mut Option, i: usize) { + let Some(row) = access.as_ref().and_then(|a| a.rows.get(i)).cloned() else { return }; + match app.run("script.grants.revoke", json!({"script": row.script, "path": row.path})) { + Ok(v) => { + *access = load(app); + if let Some(state) = access.as_mut() + && !state.rows.is_empty() + { + state.focus = Some(i.min(state.rows.len() - 1)); + } + if v["removed"].as_u64().unwrap_or(0) > 0 { + app.status("Script file access revoked"); + } else { + app.status("The script file access was already revoked"); + } + } + Err(e) => app.status(e), + } +} + +/// The rows the section shows, as (script, path, access, versions), with the script and path as they show. +#[cfg(test)] +pub(super) fn shown_rows(access: Option<&Access>) -> Vec<(String, String, String, usize)> { + let rows = access.map_or(&[][..], |a| a.rows.as_slice()); + rows.iter().map(|g| (g.shown_script.clone(), g.shown_path.clone(), g.access.to_string(), g.versions)).collect() +} + +/// Why the grants file cannot be read, as the section holds it. +#[cfg(test)] +pub(super) fn error(access: Option<&Access>) -> Option<&str> { + access?.error.as_deref() +} diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index daad8a6bef..81b8e4219e 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1002,3 +1002,307 @@ fn every_description_names_a_setting_and_fits_in_every_language() { } assert!(bad.is_empty(), "{}", bad.join("\n")); } + +/// A kept script file grant, as the grants file holds it. +fn grant(script: &std::path::Path, path: &std::path::Path, sha256: &str, write: bool, folder: bool) -> Value { + json!({"script": script.to_string_lossy(), "sha256": sha256, "code": [], "path": path.to_string_lossy(), "write": write, "folder": folder}) +} + +/// An app whose session keeps its script data in a new folder for test `name`, with a grants file +/// beside it that holds `grants`. → The app and the grants file. +fn app_with_grants(name: &str, grants: Value) -> (VectorcraftApp, std::path::PathBuf) { + let base = temp_folder(name); + let store = base.join(vectorcraft_engine::script::files::GRANTS_FILE); + std::fs::write(&store, serde_json::to_vec_pretty(&json!({"version": 1, "grants": grants})).unwrap()).unwrap(); + let mut a = app(); + a.session.attach_script_data(base.join("Script Data")); + (a, store) +} + +/// The rows General › Script File Access shows, as (script, path, access, versions). +fn access_rows(a: &VectorcraftApp) -> Vec<(String, String, String, usize)> { + script_access::shown_rows(a.prefs.as_ref().and_then(|w| w.script_access.as_ref())) +} + +/// One frame of General › Script File Access in the window's context with `events` → the texts it drew, each with +/// its place, and the frame's output. +fn access_frame(a: &mut VectorcraftApp, events: Vec) -> (Vec<(String, egui::Rect)>, egui::FullOutput) { + let ctx = a.ui_ctx.clone().expect("a window context"); + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), events, ..Default::default() }; + let out = crate::testing::part_frame(a, &ctx, raw, |a, ui| { + let Some(mut w) = a.prefs.take() else { return }; + script_access::show(a, &mut w.script_access, ui); + a.prefs = Some(w); + }); + (crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()), out) +} + +/// The texts of General › Script File Access after the frames it lays itself out in. +fn access_texts(a: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> { + access_frame(a, vec![]); + access_frame(a, vec![]).0 +} + +/// Click the first text `label` the section draws, with the pointer. +fn click_access(a: &mut VectorcraftApp, label: &str) { + let texts = access_texts(a); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + access_frame(a, vec![egui::Event::PointerMoved(at)]); + access_frame(a, vec![press(true)]); + access_frame(a, vec![press(false)]); + access_frame(a, vec![]); +} + +/// Revoke on the section's row `i`, as its button does. +fn revoke_row(a: &mut VectorcraftApp, i: usize) { + let mut w = a.prefs.take().expect("Preferences is open"); + script_access::revoke(a, &mut w.script_access, i); + a.prefs = Some(w); +} + +/// General › Script File Access lists each script and path once, with the widest access any kept +/// version of the pair has, and Revoke removes every kept version of that pair through +/// `script.grants.revoke`, so the next run asks again; the other pairs stay. +#[test] +fn script_file_access_lists_each_script_and_path_once_and_revoke_removes_them() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (a_js, b_js) = (dir.join("a.jsx"), dir.join("b.jsx")); + let (out, folder) = (dir.join("out.txt"), dir.join("work")); + let grants = json!([ + grant(&a_js, &out, "1", false, false), + grant(&a_js, &out, "2", true, false), + grant(&a_js, &folder, "1", true, true), + grant(&b_js, &out, "3", false, false), + ]); + let (mut a, store) = app_with_grants("grants-list", grants); + open(&mut a, Some("General")); + let (a_s, b_s, out_s, folder_s) = (a_js.to_string_lossy(), b_js.to_string_lossy(), out.to_string_lossy(), folder.to_string_lossy()); + let row = |s: &str, p: &str, access: &str, n: usize| (s.to_string(), p.to_string(), access.to_string(), n); + assert_eq!( + access_rows(&a), + [row(&a_s, &out_s, "write", 2), row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)], + "one row for each script and path, sorted by script and then path" + ); + assert_eq!(row_state(&mut a, script_access::KEY).map(|r| r.0), Some(true), "General shows the section"); + let texts = access_texts(&mut a); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + let note = "Revoke removes the access kept for every version of the script. A folder's access covers everything in it."; + for label in ["Script File Access", "Read and write file", "Read and write folder", "Read file", note] { + assert_eq!(painted(label), 1, "{label:?} in {texts:?}"); + } + assert_eq!(painted("Revoke"), 3, "a Revoke for each row: {texts:?}"); + assert_eq!(painted(&a_s), 1, "the script shows once over its rows: {texts:?}"); + assert_eq!(painted(&out_s), 2, "{texts:?}"); + let rect = |label: &str| texts.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("no `{label}`")); + let (path, access, revoke) = (rect(&out_s), rect("Read and write file"), rect("Revoke")); + assert!(path.max.x < access.min.x && access.max.x < revoke.min.x, "a row's path, access and Revoke do not overlap: {texts:?}"); + // The first Revoke is the first row's: a.jsx and out.txt, kept for two versions. + click_access(&mut a, "Revoke"); + assert_eq!(a.ui.status, "Script file access revoked"); + assert_eq!(access_rows(&a), [row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)]); + let kept = a.session.execute("script.grants", &json!({})).unwrap(); + assert_eq!(kept["grants"].as_array().unwrap().len(), 2, "{kept}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().unwrap().iter().all(|g| !(g["script"] == *a_s && g["path"] == *out_s)), "{stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// A long list scrolls and draws only the lines in view: of 200 rows, the first shows and the last +/// does not, and fewer than 200 Revoke buttons are drawn. +#[test] +fn script_file_access_draws_only_the_rows_in_view() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let script = dir.join("a.jsx"); + let paths: Vec<_> = (0..200).map(|n| dir.join(format!("out{n:03}.txt"))).collect(); + let grants: Vec = paths.iter().map(|p| grant(&script, p, "1", false, false)).collect(); + let (mut a, store) = app_with_grants("grants-many", Value::Array(grants)); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 200); + let texts = access_texts(&mut a); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + let (first, last) = (paths[0].to_string_lossy(), paths[199].to_string_lossy()); + assert_eq!(painted(&first), 1, "the first row shows: {texts:?}"); + assert_eq!(painted(&last), 0, "the last row is out of view: {texts:?}"); + let revokes = painted("Revoke"); + assert!(revokes > 0 && revokes < 200, "{revokes} Revoke buttons drawn"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// Revoke on a row whose grants were removed elsewhere removes nothing and says so; with no kept +/// grants the section says there are none, and a session without a settings folder (the web among +/// them) shows no section. +#[test] +fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (mut a, store) = app_with_grants("grants-gone", json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 1); + a.session.execute("script.grants.revoke", &json!({"all": true})).unwrap(); + revoke_row(&mut a, 0); + assert_eq!(a.ui.status, "The script file access was already revoked"); + assert!(access_rows(&a).is_empty()); + let texts = access_texts(&mut a); + for label in ["Script File Access", "No script has kept file access."] { + assert!(texts.iter().any(|(t, _)| t == label), "{label:?} in {texts:?}"); + } + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + let mut web = app(); + open(&mut web, Some("General")); + assert!(web.prefs.as_ref().unwrap().script_access.is_none()); + assert_eq!(row_state(&mut web, script_access::KEY), None, "no section without a settings folder"); + assert!(!fields(&web).unwrap().contains_key(script_access::ROWS)); + assert!(access_texts(&mut web).is_empty()); +} + +/// A kept grant with an empty script or path, which `script.grants` lists and `script.grants.revoke` does not take, +/// has no row. +#[test] +fn script_file_access_leaves_out_a_grant_with_an_empty_script_or_path() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let grants = json!([ + grant(&script, &path, "1", false, false), + grant(&script, "".as_ref(), "1", false, false), + grant("".as_ref(), &path, "1", false, false) + ]); + let (mut a, store) = app_with_grants("grants-empty", grants); + assert_eq!(a.session.execute("script.grants", &json!({})).unwrap()["grants"].as_array().map(Vec::len), Some(3)); + open(&mut a, Some("General")); + let row = (script.to_string_lossy().into_owned(), path.to_string_lossy().into_owned(), "read".to_string(), 1); + assert_eq!(access_rows(&a), [row]); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// Preferences opened with a read root in force shows a script and a path outside it by their file +/// names alone, as `script.grants` lists them, and `ui.inspect` names them the same way; Revoke +/// still removes that pair's kept grants, both with the root in force and without it. +#[test] +fn script_file_access_revokes_a_pair_outside_the_read_roots() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let root = temp_folder("grants-root-in"); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[root.as_path()], &[]).unwrap(); + for confined in [true, false] { + let (mut a, store) = app_with_grants("grants-outside-roots", json!([grant(&script, &path, "1", false, false)])); + let ctx = a.ui_ctx.clone().expect("a window context"); + let (shown, inspected) = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + open(&mut a, Some("General")); + (access_rows(&a), crate::control::inspect(&a, &ctx)) + }); + assert_eq!(shown, [("a.jsx".to_string(), "out.txt".to_string(), "read".to_string(), 1)]); + // The person's frame draws the rows as the request that opened the window was shown them. + let texts = access_texts(&mut a); + let whole = dir.to_string_lossy(); + assert!(texts.iter().any(|(t, _)| t == "a.jsx") && !texts.iter().any(|(t, _)| t.contains(&*whole)), "{texts:?}"); + let row = &inspected["ui"]["dialog"]["fields"][script_access::ROWS][0]; + assert_eq!(json!({"script": row["script"], "path": row["path"]}), json!({"script": "a.jsx", "path": "out.txt"}), "{inspected}"); + let roots_now = if confined { roots.as_ref() } else { None }; + vectorcraft_engine::file_access::confine(roots_now, || revoke_row(&mut a, 0)); + assert_eq!(a.ui.status, "Script file access revoked", "confined: {confined}"); + assert!(access_rows(&a).is_empty(), "confined: {confined}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().is_some_and(Vec::is_empty), "confined: {confined}: {stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// A grants file that is not well formed or is larger than may be read is refused: Revoke shows +/// the error, grants nothing and leaves the file and the rows as they were. +#[test] +fn script_file_access_revoke_refuses_a_malformed_or_oversized_grants_file() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held) in + [("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.to_vec()), ("broken", b"{ not json".to_vec()), ("oversized", oversized)] + { + let (mut a, store) = app_with_grants(&format!("grants-{name}"), json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + let before = access_rows(&a); + assert_eq!(before.len(), 1, "{name}"); + std::fs::write(&store, &held).unwrap(); + revoke_row(&mut a, 0); + assert!(a.ui.status.contains("could not be saved"), "{name}: {}", a.ui.status); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + assert_eq!(access_rows(&a), before, "{name}: the rows stay"); + let listed = a.session.execute("script.grants", &json!({})); + assert!( + listed.as_ref().is_ok_and(|v| v["grants"].as_array().is_some_and(Vec::is_empty)) || listed.is_err(), + "{name}: nothing is granted: {listed:?}" + ); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + +/// Preferences opened over a grants file `script.grants` cannot read (not JSON, or over 4 MiB) shows +/// why under Script File Access instead of saying that no script has kept file access, and leaves the +/// file as it was; a grant in the file that is not well formed is left out of the rows. +#[test] +fn script_file_access_shows_why_the_grants_file_cannot_be_read() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let kept = grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false); + let malformed = serde_json::to_vec(&json!({"version": 1, "grants": [kept, {"script": "x"}]})).unwrap(); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held, rows, unread) in + [("malformed", malformed, 1, false), ("broken", b"{ not json".to_vec(), 0, true), ("oversized", oversized, 0, true)] + { + let (mut a, store) = app_with_grants(&format!("grants-unread-{name}"), json!([])); + std::fs::write(&store, &held).unwrap(); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), rows, "{name}"); + let error = script_access::error(a.prefs.as_ref().and_then(|w| w.script_access.as_ref())).map(str::to_string); + assert_eq!(error.is_some(), unread, "{name}: {error:?}"); + let texts = access_texts(&mut a); + if let Some(error) = &error { + assert!(error.starts_with("the script file permissions could not be read: "), "{name}: {error:?}"); + assert!(texts.iter().any(|(t, _)| t == error), "{name}: {texts:?}"); + assert_eq!(fields(&a).unwrap()[script_access::ERROR], json!(error), "{name}"); + } + assert!(!texts.iter().any(|(t, _)| t == "No script has kept file access."), "{name}: {texts:?}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + +/// A script or path with control or bidirectional formatting characters shows them as escapes, so +/// it cannot break its row or draw as another name. +#[test] +fn script_file_access_shows_paths_as_plain_text() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a\u{202E}txt.jsx"), dir.join("two\nlines.txt")); + let (mut a, store) = app_with_grants("grants-plain", json!([grant(&script, &path, "1", false, false)])); + open(&mut a, Some("General")); + let (script_s, path_s) = (script_access::shown(&script.to_string_lossy()), script_access::shown(&path.to_string_lossy())); + assert!(script_s.ends_with("a\\u{202E}txt.jsx") && path_s.ends_with("two\\u{000A}lines.txt"), "{script_s} {path_s}"); + let texts = access_texts(&mut a); + assert!(texts.iter().any(|(t, _)| *t == script_s) && texts.iter().any(|(t, _)| *t == path_s), "{texts:?}"); + assert!(!texts.iter().any(|(t, _)| t.contains('\u{202E}') || t.contains("two\nlines")), "{texts:?}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// Two paths that differ only after the characters a row shows keep their whole paths in the Revoke +/// buttons' screen-reader descriptions, so each button names the grant it removes. +#[test] +fn script_file_access_revoke_names_the_whole_path() { + let mut long = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + for _ in 0..11 { + long.push("d".repeat(100)); + } + let (script, one, two) = (long.with_file_name("a.jsx"), long.join("1.txt"), long.join("2.txt")); + let (mut a, store) = app_with_grants("grants-long", json!([grant(&script, &one, "1", false, false), grant(&script, &two, "1", false, false)])); + open(&mut a, Some("General")); + access_frame(&mut a, vec![]); + let (_, out) = access_frame(&mut a, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let descriptions: Vec = + nodes.iter().filter(|(_, n)| n.label() == Some("Revoke")).filter_map(|(_, n)| n.description().map(str::to_string)).collect(); + for path in [&one, &two] { + let whole = path.to_string_lossy(); + assert!(descriptions.iter().any(|d| d.ends_with(&*whole)), "{whole} in {descriptions:?}"); + } + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} diff --git a/crates/ui-egui/src/retype_runs.rs b/crates/ui-egui/src/retype_runs.rs new file mode 100644 index 0000000000..81f774d5d3 --- /dev/null +++ b/crates/ui-egui/src/retype_runs.rs @@ -0,0 +1,235 @@ +//! Retype's search of the installed fonts off the UI thread. Type › Retype and the Retype panel's +//! Find Matching Fonts read installed font files that nothing has loaded yet, which can take +//! seconds. Asked for by the user, the search is prepared at once, so bad params and a selection +//! with nothing to match fail before anything runs, and runs on a thread of its own ([`start`]): +//! the status bar shows it, and after the progress window's delay +//! ([`crate::export_progress::DELAY`]) the window shows how many files are read, with Cancel (also +//! Esc, `retype.cancelSearch`). When it is done, the command runs with the fonts it loaded, unless +//! the document or its selection changed meanwhile: then nothing changes and the status bar says to +//! run it again. The control channel, MCP and scripts run the commands at once, and so does every +//! search on the web, in unit tests that don't set `off_the_ui_thread`, and with +//! `VECTORCRAFT_SYNC_OPEN` set ([`available`]). + +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; + +use serde_json::{Value, json}; +use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink}; +use vectorcraft_engine::EngineError; +use vectorcraft_engine::cmd::{RetypeFound, RetypeRun}; + +use crate::{VectorcraftApp, export_progress}; + +/// What the status bar and the progress window say. +const LABEL: &str = "Finding matching fonts"; + +/// A search running. +pub struct Running { + /// [`crate::export_progress::now`] when it started: the progress window's delay counts from it. + pub(crate) started: f64, + run: RetypeRun, + /// Its Cancel. + token: CancelToken, + /// The Retype panel started it, and lists what its command finds. + from_panel: bool, + /// Files read so far and in all (0 in all until the files are listed). + steps: Arc<[AtomicU64; 2]>, + done: Receiver>, +} + +impl Running { + /// The share of the files read, once they are listed. + fn fraction(&self) -> Option { + let [done, total] = &*self.steps; + let (done, total) = (done.load(Ordering::Relaxed), total.load(Ordering::Relaxed)); + (total > 0).then(|| done.min(total) as f32 / total as f32) + } +} + +/// The search running, if any. +#[derive(Default)] +pub struct RetypeRuns { + pub running: Option, + /// Set by unit tests whose app searches off the UI thread. + pub(crate) off_the_ui_thread: bool, +} + +/// Does `app` search off the UI thread? Where documents open off it ([`crate::opening::available`]), +/// and in the unit tests that set `off_the_ui_thread`. +pub fn available(app: &VectorcraftApp) -> bool { + app.retype_runs.off_the_ui_thread || crate::opening::available() +} + +/// Runs `command` (`type.retype`, or `type.retypeFonts` for the Retype panel when `from_panel`) +/// with params `p`, searching the installed fonts on a thread of its own → `{background: true, +/// status}`. Where no thread can run it, or no installed font needs reading, at once (what the +/// command, or for the panel `retype.find`, returns). Unless its params are bad, it stops the +/// search before it. +pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool) -> Result { + let at_once = |app: &mut VectorcraftApp, p: Value| { + if from_panel { + let installed = p.get("installed").cloned().unwrap_or(Value::Null); + app.run("retype.find", json!({ "installed": installed })) + } else { + app.run(command, p) + } + }; + if !available(app) { + stop(app); + return at_once(app, p); + } + // Bad params and nothing to match fail here, before anything runs; the search running goes on. + let prepared = RetypeRun::prepare(&app.session, command, &p).map_err(|e| e.to_string())?; + // The search before this one stops, so it cannot finish after this request. + stop(app); + let Some(run) = prepared else { + return at_once(app, p); + }; + let (tx, done) = channel(); + let token = CancelToken::new(); + let scoped = token.clone(); + let steps = Arc::new([AtomicU64::new(0), AtomicU64::new(0)]); + let counts = Arc::clone(&steps); + let search = run.search(); + std::thread::Builder::new() + .name("vectorcraft-retype".into()) + .spawn(move || { + let sink: ProgressSink = std::rc::Rc::new(move |done, total, _| { + let [done_now, total_now] = &*counts; + done_now.store(done, Ordering::Relaxed); + total_now.store(total, Ordering::Relaxed); + }); + let r = vectorcraft_engine::guard::catch_panic(|| cancel::scope(&scoped, Some(sink), || search.run())) + .map_err(|msg| format!("internal error: {msg} (please report this bug)")) + .and_then(|r| r.map_err(|e| e.to_string())); + // The app may have quit meanwhile: nothing to hand it to. + let _ = tx.send(r); + }) + .map_err(|e| e.to_string())?; + let started = export_progress::now(app); + app.retype_runs.running = Some(Running { started, run, token, from_panel, steps, done }); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + let status = format!("{}…", crate::i18n::msg(LABEL)); + app.status(status.clone()); + Ok(json!({ "background": true, "status": status })) +} + +/// Stops the search running, if any, without a word. +fn stop(app: &mut VectorcraftApp) { + if let Some(r) = app.retype_runs.running.take() { + r.token.cancel(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + } +} + +/// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while +/// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`]. +pub fn poll(app: &mut VectorcraftApp) { + if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + return; + } + let Some(r) = &app.retype_runs.running else { return }; + let done = match r.done.try_recv() { + Ok(done) => Some(done), + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => None, + }; + let Some(r) = app.retype_runs.running.take() else { return }; + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + +/// Waits for the search running, then does what [`poll`] does once it is done. +#[cfg(test)] +pub(crate) fn wait(app: &mut VectorcraftApp) { + let Some(r) = app.retype_runs.running.take() else { return }; + let done = r.done.recv().ok(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + +/// Runs search `r`'s command with the fonts it loaded, while its document and selection are as +/// they were; else why not, in the status bar. +fn finish(app: &mut VectorcraftApp, r: Running, done: Option>) { + // Cancel changes nothing, even when the search ended just before it. + if r.token.is_cancelled() { + app.status(EngineError::Cancelled.to_string()); + return; + } + let found = match done { + Some(Ok(found)) => found, + Some(Err(e)) => { + app.status(e); + return; + } + None => { + app.status("Retype failed: internal error: its thread stopped (please report this bug)"); + return; + } + }; + if !r.run.current(&app.session) { + app.status("Retype finished, but the document or its selection changed meanwhile: run it again"); + return; + } + // The command compares the faces found without reading the installed fonts again. + found.hand_in(&mut app.session); + let result = if r.from_panel { crate::panels::retype::search(app, r.run.params()) } else { app.run(r.run.command(), r.run.params().clone()) }; + // A command that failed before it took the faces found leaves them for no later command. + RetypeFound::drop_handed(&mut app.session); + if let Err(e) = result { + app.status(e); + } +} + +/// The progress window's Cancel (also Esc): the search stops before its next file and changes +/// nothing → `{cancelled: n}`. +pub fn cancel(app: &mut VectorcraftApp) -> Value { + let n = app.retype_runs.running.as_ref().filter(|r| !r.token.is_cancelled()).map_or(0, |r| { + r.token.cancel(); + 1 + }); + json!({ "cancelled": n }) +} + +/// Stops the Retype panel's search running, without a word: Reset Retype Panel clears the list +/// the search would fill, and a search `retype.find` runs at once fills it. +pub fn drop_panel_search(app: &mut VectorcraftApp) { + if app.retype_runs.running.as_ref().is_some_and(|r| r.from_panel) + && let Some(r) = app.retype_runs.running.take() + { + r.token.cancel(); + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + } +} + +/// Is a search running that hasn't been canceled? +pub fn any_running(app: &VectorcraftApp) -> bool { + app.retype_runs.running.as_ref().is_some_and(|r| !r.token.is_cancelled()) +} + +/// The progress window of the search running; `export_progress::show` decides when it shows and +/// runs `retype.cancelSearch` when Cancel is pressed. The search has no Continue in Background. +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let r = app.retype_runs.running.as_ref().filter(|r| !r.token.is_cancelled())?; + Some(export_progress::Shown { + title: format!("{}…", crate::i18n::msg(LABEL)), + step: tl!("Reading the installed fonts…").to_string(), + fraction: r.fraction(), + counts: None, + queued: None, + started: r.started, + cancel: "retype.cancelSearch", + hide: None, + }) +} diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..11d6c7e599 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -3,11 +3,14 @@ //! 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. +use serde_json::{Value, json}; + use crate::VectorcraftApp; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { + startup_failures(app); if !app.session.script_running() { return; } @@ -15,8 +18,16 @@ pub fn poll(app: &mut VectorcraftApp) { if ask(app) { return; } + // Between two queued runs, the next one waits for the answer to the quit question. + if app.session.script_name().is_none() && (script_run::asking_to_close(app) || script_run::answer_close_between_runs(app)) { + return; + } let name = app.session.script_name().unwrap_or_default(); + let startup = app.session.startup_script_running(); let Some(result) = app.session.script_pump() else { + // A pump that started the next queued run shows the runs before it that could not start + // in this frame: with none left running, the app may draw no next one. + startup_failures(app); // The app draws no more frames while the run waits: its question opens in this one. ask(app); return; @@ -30,11 +41,61 @@ pub fn poll(app: &mut VectorcraftApp) { app.status(format!("Ran {name}")); } } - Err(e) => failed(app, e.to_string()), + Err(e) => ended_with_error(app, startup, e.to_string()), } + startup_failures(app); app.sync_views(); } +/// Shows each run `script.startup.run` queued that could not start ([`add_notes`]), and once the +/// round has no run left, the round's notes again ([`end_round`]). +fn startup_failures(app: &mut VectorcraftApp) { + let failures: Vec = app.session.take_startup_failures().into_iter().map(|(name, error)| format!("{name}: {error}")).collect(); + if app.session.script_running() { + add_notes(app, failures); + } else { + app.ui.startup_notes.extend(failures); + end_round(app); + } +} + +/// Adds `notes` to those of the startup scripts' round under way and shows them all +/// ([`show_notes`]); a round with no run left keeps none. +fn add_notes(app: &mut VectorcraftApp, notes: Vec) { + if notes.is_empty() { + return; + } + app.ui.startup_notes.extend(notes); + show_notes(app, app.ui.startup_notes.clone()); + if !app.session.script_running() { + app.ui.startup_notes.clear(); + } +} + +/// When the startup scripts' round has notes and its last run has ended: shows them again, before +/// the message that run ended with and its own notes, so a later message does not hide them. +fn end_round(app: &mut VectorcraftApp) { + if app.ui.startup_notes.is_empty() { + return; + } + let mut notes = std::mem::take(&mut app.ui.startup_notes); + match app.ui.status_notes.take() { + Some((status, more)) if status == app.ui.status && more == notes => {} + Some((status, more)) if status == app.ui.status && !more.is_empty() => notes.extend(more), + _ if app.ui.status.is_empty() || notes.contains(&app.ui.status) => {} + _ => notes.push(app.ui.status.clone()), + } + show_notes(app, notes); +} + +/// Shows the first of `notes` in the status bar, and keeps them all for its hover, which lists +/// them when there are several. Without notes the status bar keeps its message. +fn show_notes(app: &mut VectorcraftApp, notes: Vec) { + if let Some(first) = notes.first().cloned() { + crate::io::show_with_notes(app, first, notes); + } +} + /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. @@ -63,6 +124,89 @@ fn ask(app: &mut VectorcraftApp) -> bool { false } +/// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after +/// the startup scripts when General › Run Startup Scripts is on (`script.startup.run`). A startup +/// script that cannot start, a listing of the Startup Scripts folder that was not read in full, and +/// a folder that is there and cannot be read show in the status bar ([`reply_notes`]). +/// → `script.run`'s reply, with `startup` holding `script.startup.run`'s when the startup scripts +/// were run: the chosen script's own reply when it ran to its end at once, `{running: true, name}` +/// when it is running, or `{running: true, queued: true}` while the chosen script waits to start. +/// A chosen script that could not start gives its error, as `script.run` does. +pub(crate) fn run_chosen(app: &mut VectorcraftApp, params: Value) -> Result { + if app.session.startup_skip().is_some() { + return app.run("script.run", params); + } + let mut startup = app.run("script.startup.run", json!({"reason": "menu", "then": params}))?; + reply_notes(app, &startup); + let mut reply = match startup.as_object_mut().and_then(|o| o.remove("then")) { + Some(then) => then, + // Nothing runs and the chosen script gave no reply: it could not start, and it is the + // last of the runs that could not start. + None if !app.session.script_running() => { + let last = startup["failed"].as_array().and_then(|failed| failed.last()); + return Err(last.and_then(|failed| failed["error"].as_str()).unwrap_or_default().to_string()); + } + None if app.session.startup_script_running() || app.session.script_name().is_none() => json!({"running": true, "queued": true}), + None => json!({"running": true, "name": app.session.script_name().unwrap_or_default()}), + }; + if let Some(o) = reply.as_object_mut() { + o.insert("startup".to_string(), startup); + } + Ok(reply) +} + +/// Starts the notes of a startup scripts' round with what its `script.startup.run` reply says was +/// left out ([`add_notes`]): each startup script it names under `failed` (the queued runs that +/// could not start before the first one did), then a listing that was not read in full +/// (`truncated`) or a folder that cannot be read (`unreadable`). The notes show again when the +/// round's last run ends ([`end_round`]). +pub(crate) fn reply_notes(app: &mut VectorcraftApp, reply: &Value) { + app.ui.startup_notes.clear(); + let mut notes: Vec = reply["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failed| format!("{}: {}", failed["name"].as_str().unwrap_or_default(), failed["error"].as_str().unwrap_or_default())) + .collect(); + if reply["truncated"] == true { + notes.push(STARTUP_TRUNCATED.to_string()); + } + if reply["unreadable"] == true { + notes.push(STARTUP_UNREADABLE.to_string()); + } + add_notes(app, notes); +} + +/// The status bar's note when a listing of the Startup Scripts folder stopped at a limit, left out +/// scripts past its limit or skipped an entry it could not read. +pub(crate) const STARTUP_TRUNCATED: &str = "The Startup Scripts folder was not read in full"; +/// The status bar's note when the Startup Scripts folder is there and cannot be read. +pub(crate) const STARTUP_UNREADABLE: &str = "The Startup Scripts folder cannot be read"; + +/// When the app has started, out of Safe Mode: the startup scripts run when General › Run Startup +/// Scripts is on (`script.startup.run`). A failure to start them, a listing of the folder that was +/// not read in full, or a Startup Scripts folder that is there and cannot be read shows in the +/// status bar ([`reply_notes`]). +pub fn run_at_launch(app: &mut VectorcraftApp) { + if app.session.startup_skip().is_some() { + return; + } + match app.run("script.startup.run", json!({"reason": "launch"})) { + Ok(reply) => reply_notes(app, &reply), + Err(e) => app.status(e), + } +} + +/// Shows why a run ended without its changes ([`failed`]). When the run was a startup script +/// (`startup`), the message also stays in the round's notes, so the message of the run that ends +/// the round does not hide it ([`end_round`]). +pub(crate) fn ended_with_error(app: &mut VectorcraftApp, startup: bool, error: String) { + failed(app, error); + if startup { + app.ui.startup_notes.push(app.ui.status.clone()); + } +} + /// Shows why a run ended without its changes. A stopped run that wrote no file says only that it /// was stopped; any other failure shows its error, which names the files left written. pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { @@ -73,3 +217,18 @@ pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { app.status(error); } } + +/// Shows that the runs `script.startup.run` queued were stopped between two of them, before the +/// next one started. The message shows first, before the round's notes ([`end_round`]). +pub(crate) fn stopped_between_runs(app: &mut VectorcraftApp) { + let message = "The scripts waiting to run were not run"; + let mut notes = vec![message.to_string()]; + notes.append(&mut app.ui.startup_notes); + if notes.len() == 1 { + // Notes an earlier round left for the same message are not this round's. + app.ui.status_notes = None; + app.status(message); + } else { + show_notes(app, notes); + } +} diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index a715f982af..c27df08742 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -13,7 +13,8 @@ //! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a -//! listing gave; a file that is no longer a plain script under the folder is not run. +//! listing gave; a file that is no longer a plain script under the folder is not run. With General › +//! Run Startup Scripts on, the startup scripts run first (`script.startup.run`). // PLAN: needs craft-menu, craft-host and craft-platform in crates/ui-egui/Cargo.toml (shell owner). use std::path::{Path, PathBuf}; @@ -276,7 +277,12 @@ pub fn readable(p: &Value) -> bool { /// folder is read again. pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; - app.run("script.run", json!({ "path": path, "installed": true })).inspect_err(|e| { + // With startup scripts to run first, a script no longer in the folder is found before they run. + let listed = match app.session.startup_skip() { + Some(_) => Ok(()), + None => app.session.installed_script(path).map(drop).map_err(|e| e.to_string()), + }; + listed.and_then(|()| crate::script_runs::run_chosen(app, json!({ "path": path, "installed": true }))).inspect_err(|e| { if e == NOT_LISTED && let Some(ctx) = app.ui_ctx.clone() { diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 42f01d739b..90f45203b0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1109,7 +1109,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) { let prefs = &app.session.prefs; let hold = HoldSetting::new(prefs.hold_shortcuts, prefs.key_hold_delay(), min..=max); app.shortcuts_dialog = Some(ShortcutsDialogState { - state: DialogState::new().with_tab("tools"), + state: DialogState::new(), keymap: None, window: None, hold, @@ -1141,6 +1141,7 @@ fn accept(def: &CommandDef, binding: &Binding) -> Result<(), String> { fn options() -> Options { Options::default().with(|o| { o.area_tabs = true; + o.own_areas = true; o.areas = vec![Area::new("tools", "Tools", is_tool), Area::new("menu", MENU_COMMANDS, |def| !is_tool(def))]; o.summary = false; o.accept = Some(Box::new(accept)); @@ -2161,6 +2162,31 @@ mod tests { } } + #[test] + fn the_dialog_opens_with_only_tools_and_menu_commands() { + use egui::accesskit::Role; + + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let raw = || egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + for _ in 0..3 { + crate::testing::app_frame(&mut app, &ctx, raw()); + } + open(&mut app); + for _ in 0..3 { + crate::testing::app_frame(&mut app, &ctx, raw()); + } + let nodes = crate::testing::app_frame(&mut app, &ctx, raw()).platform_output.accesskit_update.expect("dialog access tree").nodes; + let (_, areas) = nodes.iter().find(|(_, n)| n.role() == Role::TabList && n.label() == Some("shortcuts.area")).expect("area tabs"); + let labels: Vec<_> = areas + .children() + .iter() + .filter_map(|child| nodes.iter().find(|(id, n)| id == child && n.role() == Role::Tab).and_then(|(_, n)| n.label())) + .collect(); + assert_eq!(labels, ["Tools", "Menu Commands"]); + } + /// An open dialog lists a live-effect plug-in installed while it is open, with the shortcut its /// set gives it, and drops the row while the plug-in is removed, keeping that shortcut in the /// set. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1ed56d8faa..27aa8d39f4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -707,6 +707,11 @@ pub struct UiState { /// Not saved. #[serde(skip)] pub status_notes: Option<(String, Vec)>, + /// What the startup scripts' round under way left out ([`crate::script_runs`]): the runs that + /// could not start and the notes on the Startup Scripts folder, shown again when its last run + /// ends. Not saved. + #[serde(skip)] + pub startup_notes: Vec, /// The status text a plug-in wrote, with the app's words before and after it: while the status /// is these three together, the status bar translates the app's words and shows the plug-in's /// as they are ([`crate::plugin_runs::show_notice`]). Not saved. @@ -1482,6 +1487,7 @@ impl Default for UiState { replace_font_warning: None, last_find: None, status_notes: None, + startup_notes: Vec::new(), status_kept: None, palette_open: false, palette_query: String::new(), diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 73df461574..476ab0b16f 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -50,6 +50,19 @@ pub(crate) fn app_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, ra /// [`app_frame`] with `draw` showing part of the window in place of the whole app. pub(crate) fn part_frame( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + raw: egui::RawInput, + draw: impl FnMut(&mut crate::VectorcraftApp, &mut egui::Ui), +) -> egui::FullOutput { + let mut out = part_frame_uploads(app, ctx, raw, draw); + out.textures_delta.clear(); + out +} + +/// [`part_frame`] with the frame's texture uploads kept in the output, for a test that reads them. The test clears +/// `textures_delta` once it has read it. +pub(crate) fn part_frame_uploads( app: &mut crate::VectorcraftApp, ctx: &egui::Context, mut raw: egui::RawInput, @@ -58,9 +71,8 @@ pub(crate) fn part_frame( app.adopt_context(ctx); app.raw_input(ctx, &mut raw); embed::before_input(ctx, |out| app.frame_input(out)); - let mut out = ctx.run_ui(raw, |ui| draw(app, ui)); + let out = ctx.run_ui(raw, |ui| draw(app, ui)); run_fired(app, ctx); - out.textures_delta.clear(); out } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 67f24afa73..bdd82189bd 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -35,6 +35,7 @@ mod quickpenbar; mod recolor; mod recovery; pub(super) mod removeanchors; +mod retype_runs; mod rotateview; mod ruler_origin; mod save; diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 441817c8b8..ecc57daddd 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -304,6 +304,27 @@ fn cmd_alt_shift_u_switches_to_the_next_unit() { assert_eq!(app.session.general_unit(), Unit::Points, "Feet → Points"); } +/// With the Quick Pen, the menu has Delete, which removes the selected anchor points; with another +/// tool it does not. +#[test] +fn the_quick_pen_menu_deletes_the_selected_anchors() { + let mut app = app(); + let a = rect(&mut app, 0.0, 0.0); + app.run("select.anchors", json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + assert!(!has(&app, "Delete"), "the Selection tool"); + app.select_tool("quickPen"); + assert!(has(&app, "Delete"), "{:?}", labels(&app)); + let delete = menus::context_entries(&app).into_iter().find(|e| e.label == "Delete").expect("Delete"); + assert_eq!(delete.command.as_deref(), Some("edit.clear")); + menus::invoke(&mut app, "edit.clear", json!({})); + let st = app.session.active().unwrap(); + let pd = st.doc.node(a).unwrap().path_data().unwrap().clone(); + assert_eq!(pd.subpaths[0].anchors.len(), 3, "one anchor removed"); + // Nothing selected: no Delete. + app.run("select.none", json!({})).unwrap(); + assert!(!has(&app, "Delete")); +} + #[test] fn the_menu_follows_the_selection() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 71977801c5..12bb325ca8 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -11,6 +11,7 @@ use std::{ }; use craft::behavior::PartRef; +use craft::ui::contract::Role; use craft::ui::runtime::frame::take_output; use craft::ui::testing::pointer::part_rect_of_node; use craft::ui::testing::{Fixture, Target}; @@ -63,7 +64,7 @@ impl Panel { } /// One frame with `events`, its input taken from the app first. - fn frame_with(&mut self, events: Vec) { + pub(crate) fn frame_with(&mut self, events: Vec) { self.take_input(); self.fixture.frame(events); self.take_input(); @@ -182,8 +183,13 @@ impl Panel { /// the name (a slider beside its number box). pub(crate) fn drag_hold_role(&mut self, name: &str, role: craft::ui::contract::Role, by: Vec2) { self.frame(); - let target = self.look_role(name, role); - self.fixture.drag_hold_at(target.center(), by); + let from = self.look_role(name, role).center(); + self.drag_hold_between(from, from + by); + } + + /// Drags from `from` to `to`, keeping the button down for another input before release. + pub(crate) fn drag_hold_between(&mut self, from: Pos2, to: Pos2) { + self.fixture.drag_hold_at(from, to - from); self.after(); } @@ -218,6 +224,13 @@ impl Panel { self.after(); } + /// Turns the wheel by `dy` points over `at`. + pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) { + self.frame_with(vec![Event::PointerMoved(at)]); + self.frame_with(vec![craft::ui::testing::pointer::wheel(dy)]); + self.after(); + } + /// Drags from the control named `from` to the one named `to`. pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) { let to = self.find(to).center(); @@ -293,6 +306,12 @@ impl Panel { self.fixture.by_label(name).is_some() } + /// Whether the latest frame has a status announcement with this text. + pub(crate) fn announces(&self, text: &str) -> bool { + let tree = self.fixture.tree(); + tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::STATUS) && tree.name_of(key) == Some(text)) + } + /// Whether some of the control named `name` can be seen in the latest frame. pub(crate) fn in_view(&self, name: &str) -> bool { self.fixture.visible(&self.look(name)).is_some() diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 7b51659271..948cfe2b1d 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -777,3 +777,47 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); } + +/// File › Open of a JavaScript plug-in's `.vcplugin` installs it with the script beside it. Without +/// a path (the web file picker), the manifest alone is refused, the error says how the script is +/// given, and nothing is installed. +#[test] +fn opening_a_javascript_manifest_installs_it_with_its_script() { + let mut app = app(); + let id = "test.ui.js.open"; + let dir = std::env::temp_dir().join(format!("vc-ui-js-open-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = json!({"id": id, "name": "Open JS", "kind": "filter", "runtime": "js", "script": "open.js"}).to_string(); + let path = dir.join("open.vcplugin"); + std::fs::write(&path, &manifest).unwrap(); + std::fs::write(dir.join("open.js"), "function run(input) { return input; }").unwrap(); + let e = io::open_bytes(&mut app, "open.vcplugin", manifest.as_bytes(), None).unwrap_err(); + assert!(e.contains(vectorcraft_plugins::js::SOURCE_RULE), "{e}"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + io::open_bytes(&mut app, "open.vcplugin", manifest.as_bytes(), Some(path.display().to_string())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js")); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + +/// Opening a JavaScript plug-in's `.vcplugin` by its path installs it through `plugin.install +/// {path}` without the app's file reader reading the manifest first. +#[test] +fn opening_a_javascript_manifest_by_path_does_not_read_it_first() { + let mut app = app(); + app.services.read = Some(Box::new(|_: &str| Err("the whole file was read".to_string()))); + let id = "test.ui.js.open.path"; + let dir = std::env::temp_dir().join(format!("vc-ui-js-open-path-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = json!({"id": id, "name": "Open JS by path", "kind": "filter", "runtime": "js", "script": "open.js"}).to_string(); + let path = dir.join("open.vcplugin"); + std::fs::write(&path, &manifest).unwrap(); + std::fs::write(dir.join("open.js"), "function run(input) { return input; }").unwrap(); + let r = io::open_path(&mut app, &path.display().to_string()); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r, Ok(Value::Null)); + assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js")); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index b56303f960..b4fa530205 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -447,6 +447,39 @@ fn a_gray_row_keeps_the_hsb_sliders_while_it_is_edited() { assert_eq!(field(&r, "sliderMode"), json!("hsb")); } +#[test] +fn other_library_picker_only_limits_the_recolor_opening_that_requested_it() { + let path = vectorcraft_testkit::temp_dir("recolor-other-library").join("Recolor Test.gpl"); + std::fs::write(&path, "GIMP Palette\nName: Recolor Test\n#\n12 34 56 Test Color\n").unwrap(); + let path = path.to_str().unwrap(); + for reopen in [true, false] { + let mut r = open(app(), json!({"colors": ["#123456"], "library": "document"})); + let picker = super::picks::scripted(&mut r.app()); + r.settled(); + tap(&mut r, "Other Library…"); + assert_eq!(picker.requests().len(), 1, "the dialog asked for a file"); + if reopen { + r.cancel(); + assert!(!r.is_open(), "the first opening closed while its answer was pending"); + r.app().run("ui.recolorDialog", json!({"colors": ["#abcdef"], "library": "document"})).unwrap(); + r.settled(); + } + assert_eq!(field(&r, "limitTo"), "document"); + + picker.answer(&[path]); + crate::file_asks::poll(&mut r.app()); + r.settled(); + let libraries = r.app().run("swatch.library.list", json!({})).unwrap(); + let imported = libraries["libraries"].as_array().unwrap().iter().find(|lib| lib["category"] == "loaded").expect("the library still loads"); + if reopen { + assert_eq!(field(&r, "limitTo"), "document", "the reopened dialog keeps its own Limit to Library choice"); + } else { + assert_eq!(field(&r, "limitTo"), imported["id"], "an answer for the current opening selects its library"); + } + r.cancel(); + } +} + /// With Limit to Library, a row whose new color is a spot color of the library shows Tint, whose T /// slider sets the row's tint of it; OK links the art to the spot color at that tint. #[test] diff --git a/crates/ui-egui/src/tests/retype_runs.rs b/crates/ui-egui/src/tests/retype_runs.rs new file mode 100644 index 0000000000..946c94b865 --- /dev/null +++ b/crates/ui-egui/src/tests/retype_runs.rs @@ -0,0 +1,230 @@ +//! Retype in the app ([`crate::retype_runs`]): Type › Retype and the Retype panel's Find Matching +//! Fonts search the installed fonts off the UI thread, then run their command, unless the document +//! or its selection changed meanwhile; Cancel stops the search and changes nothing; its progress +//! window shows it. + +use serde_json::json; +use vectorcraft_engine::{EngineError, Session}; + +use crate::export_progress::{self, DELAY}; +use crate::{VectorcraftApp, retype_runs}; + +/// An app whose searches run off the UI thread, with "Retype me" set in Source Sans 3, outlined and +/// selected → the app and the outlines' group. +fn outlined() -> (VectorcraftApp, u64) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 40, "y": 100, "text": "Retype me", "size": 30, "font": "Source Sans 3"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = app.session.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + app.retype_runs.off_the_ui_thread = true; + (app, g) +} + +fn undos(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn has_type(app: &VectorcraftApp) -> bool { + let mut found = false; + app.session.doc().unwrap().doc.walk(|n| found |= matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))); + found +} + +/// Draws the progress window at `time` seconds in a frame as the hosts run it → the texts it drew. +fn progress(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> String { + let out = crate::testing::part_frame(app, ctx, egui::RawInput { time: Some(time), ..Default::default() }, export_progress::show); + let mut texts = String::new(); + for shape in out.shapes { + if let egui::epaint::Shape::Text(t) = shape.shape { + texts.push_str(t.galley.text()); + texts.push('\n'); + } + } + texts +} + +#[test] +fn type_retype_searches_off_the_ui_thread_then_retypes_as_one_undo_step() { + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some(), "the search runs in the background"); + assert_eq!(app.ui.status, "Finding matching fonts…"); + assert_eq!(undos(&app), before, "nothing yet"); + retype_runs::wait(&mut app); + assert!(app.retype_runs.running.is_none()); + assert_eq!(undos(&app), before + 1, "one undo step: {}", app.ui.status); + assert!(has_type(&app), "the outlines are type again"); +} + +/// Starting a search asks for a frame, so its result is picked up without input. +#[test] +fn starting_a_search_asks_for_a_frame() { + let (mut app, _) = outlined(); + let ctx = crate::testing::ui_context(); + for _ in 0..5 { + crate::testing::part_frame(&mut app, &ctx, Default::default(), |_, _| {}); + if !ctx.has_requested_repaint() { + break; + } + } + assert!(!ctx.has_requested_repaint(), "the context settled"); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some()); + assert!(ctx.has_requested_repaint()); + retype_runs::wait(&mut app); +} + +#[test] +fn cancel_changes_nothing() { + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 1})); + assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 0}), "already canceled"); + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before, "canceled: nothing changes, even when the search ended first"); + assert!(!has_type(&app)); + assert_eq!(app.ui.status, EngineError::Cancelled.to_string()); +} + +/// The progress window opens after its delay with Cancel and no Continue in Background; its Cancel +/// stops the search, which then changes nothing. +#[test] +fn the_progress_window_shows_a_search() { + let (mut app, _) = outlined(); + let ctx = crate::testing::ui_context(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some()); + assert!(!progress(&mut app, &ctx, 0.0).contains("Finding matching fonts"), "not before the delay"); + // The delay counts on the monotonic clock: the search started that long ago. + if let Some(r) = app.retype_runs.running.as_mut() { + r.started -= DELAY; + } + let shown = progress(&mut app, &ctx, DELAY + 0.05); + assert!(shown.contains("Finding matching fonts…") && shown.contains("Reading the installed fonts…"), "{shown}"); + assert!(shown.contains("Cancel") && !shown.contains("Continue in Background"), "{shown}"); + assert_eq!(app.run("retype.cancelSearch", json!({})).unwrap(), json!({"cancelled": 1})); + // The window open in the last frame is gone from the next two. + for time in [DELAY + 1.0, DELAY + 1.1] { + assert!(!progress(&mut app, &ctx, time).contains("Finding matching fonts"), "a canceled search isn't shown"); + } + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before, "canceled: nothing changes"); +} + +#[test] +fn a_search_whose_selection_changed_meanwhile_changes_nothing() { + let (mut app, g) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + // The same objects selected again: it still applies. + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before + 1); + // Another selection when it is done: nothing changes. + app.run("edit.undo", json!({})).unwrap(); + app.session.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + retype_runs::wait(&mut app); + assert_eq!(undos(&app), before); + assert_eq!(app.ui.status, "Retype finished, but the document or its selection changed meanwhile: run it again"); +} + +#[test] +fn find_matching_fonts_lists_the_fonts_once_the_search_is_done() { + let (mut app, _) = outlined(); + let r = retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + assert_eq!(r["background"], json!(true), "{r}"); + assert!(!app.ui.retype.searched, "nothing listed yet"); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // Other tests load renamed copies of the bundled fonts, which tie with it: it may be among the + // fonts Find more font matches adds. + let v = &app.ui.retype; + assert!(!v.fonts.is_empty()); + assert!(v.fonts.iter().chain(&v.rest).any(|f| f.family == "Source Sans 3"), "{:?} {:?}", v.fonts, v.rest); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::retype::ID), "the panel shows"); + // From a menu or the command palette, retype.find searches in the background too; with the + // installed fonts left out it lists at once. + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({})); + assert!(app.retype_runs.running.is_some() && !app.ui.retype.searched); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // Find more font matches before any search is a first search, in the background too. + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({"more": true})); + assert!(app.retype_runs.running.is_some() && !app.ui.retype.searched); + retype_runs::wait(&mut app); + assert!(app.ui.retype.searched); + // After a search it adds to the list at once. + crate::menus::invoke(&mut app, "retype.find", json!({"more": true})); + assert!(app.retype_runs.running.is_none()); + app.run("retype.reset", json!({})).unwrap(); + crate::menus::invoke(&mut app, "retype.find", json!({"installed": false})); + assert!(app.retype_runs.running.is_none() && app.ui.retype.searched); +} + +#[test] +fn reset_retype_panel_stops_the_panel_s_search() { + let (mut app, _) = outlined(); + retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + app.run("retype.reset", json!({})).unwrap(); + assert!(app.retype_runs.running.is_none(), "the search is stopped"); + retype_runs::wait(&mut app); + assert!(!app.ui.retype.searched, "the list stays cleared"); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // A new search the command runs at once stops it too, so it does not replace the new list. + retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + let listed = app.run("retype.find", json!({"installed": false})).unwrap(); + assert!(app.retype_runs.running.is_none(), "the older search is stopped"); + retype_runs::wait(&mut app); + assert_eq!(app.run("retype.list", json!({})).unwrap(), listed); + // Retype's own search goes on. + crate::menus::invoke(&mut app, "type.retype", json!({})); + app.run("retype.reset", json!({})).unwrap(); + assert!(app.retype_runs.running.is_some()); + retype_runs::wait(&mut app); +} + +#[test] +fn without_a_thread_or_with_the_installed_fonts_left_out_the_command_runs_at_once() { + let (mut app, _) = outlined(); + let r = retype_runs::start(&mut app, "type.retype", json!({"installed": false}), false).unwrap(); + assert!(r["ids"].is_array(), "the command's own result: {r}"); + assert!(app.retype_runs.running.is_none()); + let (mut app, _) = outlined(); + app.retype_runs.off_the_ui_thread = false; + let r = retype_runs::start(&mut app, "type.retypeFonts", json!({"count": 96}), true).unwrap(); + assert_eq!(r["searched"], json!(true), "what retype.find returns: {r}"); + assert!(app.retype_runs.running.is_none()); + // A request that runs at once stops the search before it, which does not apply later. + let (mut app, _) = outlined(); + let before = undos(&app); + crate::menus::invoke(&mut app, "type.retype", json!({})); + assert!(app.retype_runs.running.is_some()); + // A request with bad params leaves it running. + assert!(retype_runs::start(&mut app, "type.retype", json!({"installed": 1}), false).is_err()); + assert!(app.retype_runs.running.is_some(), "the search goes on"); + retype_runs::start(&mut app, "type.retype", json!({"installed": false}), false).unwrap(); + assert!(app.retype_runs.running.is_none(), "the older search is stopped"); + assert_eq!(undos(&app), before + 1, "the new request retyped once"); + // Bad params fail before anything runs. + let (mut app, _) = outlined(); + assert!(retype_runs::start(&mut app, "type.retype", json!({"installed": 1}), false).is_err()); + assert!(crate::panels::retype::find_in_background(&mut app, &json!({"more": "yes"})).is_err()); + assert!(crate::panels::retype::find_in_background(&mut app, &json!({"installed": "yes"})).is_err()); + crate::menus::invoke(&mut app, "retype.find", json!({"more": 1})); + assert!(app.retype_runs.running.is_none() && !app.ui.retype.searched); + assert!(app.ui.status.contains("`more` must be true or false"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index b1cdf7cf95..53aa6f39cb 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -297,6 +297,84 @@ fn quitting_asks_to_stop_and_stop_undoes_the_run() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn a_startup_script_stopped_by_quitting_stays_in_the_status_bar() { + let mut app = app(); + let dir = folder("startup-quit"); + std::fs::write(dir.join("a.jsx"), "for (;;) {}").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.startup_script_running()); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + finish(&mut app); + script_runs::poll(&mut app); + let stopped = "The script was stopped and its changes were undone"; + assert_eq!(app.ui.status, stopped); + assert_eq!(app.ui.status_notes.as_ref().and_then(|(_, notes)| notes.first()).map(String::as_str), Some(stopped)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn quitting_between_a_startup_script_and_the_chosen_script_stops_the_chosen_script() { + let mut app = app(); + let dir = folder("startup-quit-between"); + // A first startup script that cannot start leaves a note for the round. + std::fs::write(dir.join("0.jsx"), [0xff, 0xfe, 0x00]).unwrap(); + std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_name().is_none() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits for the next frame"); + script_run::ask_to_close(&mut app); + // Frames drawn while the question is open do not start the chosen script. + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits for the answer"); + // A frame takes the answer before it would start the next run, then pumps the dialogs. + let id = open_id(&app, CLOSE_KIND); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + pump(&mut app); + script_runs::poll(&mut app); + let message = "The scripts waiting to run were not run"; + assert_eq!(app.ui.status, message); + let notes = app.ui.status_notes.clone().map(|(_, notes)| notes).unwrap_or_default(); + assert_eq!(notes.len(), 2, "{notes:?}"); + assert_eq!(notes[0], message); + assert!(notes[1].starts_with("0.jsx: "), "{notes:?}"); + assert_eq!(objects(&app), 0, "the chosen script did not run"); + // A later round stopped the same way, with no notes of its own, does not show the earlier round's. + std::fs::remove_file(dir.join("0.jsx")).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_name().is_none() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_running() && app.session.script_name().is_none()); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + script_runs::poll(&mut app); + assert_eq!(app.ui.status, message); + assert_eq!(app.ui.status_notes, None); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_stop_names_the_files_the_run_left_written() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 33674ec957..300e0dbb32 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -25,10 +25,9 @@ fn ctx() -> egui::Context { CTX.with(Clone::clone) } -/// A fresh folder for test `name`, holding an empty `Scripts` folder. -fn folder(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vc-scripts-menu-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); +/// A fresh folder for test `name`, holding an empty `Scripts` folder, removed when the test ends. +fn folder(name: &str) -> vectorcraft_testkit::TempDir { + let dir = vectorcraft_testkit::TempDir::new(&format!("scripts-menu-{name}")); std::fs::create_dir_all(dir.join("Scripts")).unwrap(); dir } @@ -460,3 +459,300 @@ fn a_slow_first_read_says_so_until_its_listing_comes() { assert_eq!(shape(&scripts_menu::items_at(started + 10.0 * scripts_menu::SLOW_SECS)), format!("first, -, {FIXED}")); let _ = std::fs::remove_dir_all(dir); } + +/// The names of the runs the Script Console started, in order. +fn started(app: &VectorcraftApp) -> Vec { + let lines = app.session.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding `a.jsx` that draws one rectangle. +fn startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + std::fs::write(startup.join("a.jsx"), "vc.run('shape.rectangle', {x:40,y:0,width:10,height:10});").unwrap(); + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn with_run_startup_scripts_on_a_listed_script_runs_after_the_startup_scripts() { + let dir = folder("startup"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + let draw = write(&dir, "Draw Two.jsx", DRAW); + read(&app); + // Off by default: the listed script runs alone. + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(started(&app), ["Draw Two.jsx"]); + assert_eq!(objects(&app), 2); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap(); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(started(&app), ["Draw Two.jsx", "a.jsx", "Draw Two.jsx"], "the startup script runs first"); + assert_eq!(objects(&app), 5); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "an undo step for each run"); + assert_eq!(app.ui.status, "Ran Draw Two.jsx"); + // A script that left the folder runs neither itself nor the startup scripts. + std::fs::remove_file(&draw).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": draw })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(!app.session.script_running()); + assert_eq!(started(&app).len(), 3); + scripts_menu::finish(); +} + +#[test] +fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scripts() { + let dir = folder("startup-other"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running(), "off by default, nothing runs at launch"); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx"]); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "a.jsx", "chosen"]); + assert_eq!(objects(&app), 4); +} + +#[test] +fn with_run_startup_scripts_on_a_chosen_script_still_replies_as_script_run() { + let dir = folder("startup-reply"); + let mut app = app(&dir); + app.session.prefs.show_external_script_warning = false; + let off = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(off, json!({"running": true, "name": "chosen"})); + let empty = dir.join("Startup Scripts"); + std::fs::create_dir_all(&empty).unwrap(); + app.session.attach_startup_scripts_dir(empty); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + // An empty folder: the chosen script starts at once, named as its run is, by a #script line too. + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!((&r["running"], &r["name"], &r["startup"]["queued"]), (&json!(true), &json!("chosen"), &json!(1)), "{r}"); + let named = format!("#script \"Named\"\n{DRAW}"); + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": named })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(r["name"], "Named", "{r}"); + // A chosen script that cannot start gives its error, as script.run does. + let alone = app.run("script.run", json!({"source": "vc.log(("})).unwrap_err(); + let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log((" })).unwrap().unwrap_err(); + assert_eq!(e, alone); + // A startup script runs first: the chosen script is queued after it. + startup_folder(&mut app, &dir); + let r = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + finish(&mut app); + assert_eq!((&r["running"], &r["queued"], &r["startup"]["queued"]), (&json!(true), &json!(true), &json!(2)), "{r}"); + assert_eq!(started(&app).last().map(String::as_str), Some("chosen")); +} + +#[test] +fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs() { + let dir = folder("startup-stop"); + let mut app = app(&dir); + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + std::fs::write(startup.join("a.jsx"), "for (;;) {}").unwrap(); + app.session.attach_startup_scripts_dir(startup); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_request_stop()); + app.status("before"); + for _ in 0..10_000 { + if app.ui.status != "before" { + break; + } + script_runs::poll(&mut app); + } + let stopped = "The script was stopped and its changes were undone".to_string(); + assert_eq!(app.ui.status, stopped); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "chosen"]); + // The stopped startup script stays in sight when the chosen script ends, with its message in the hover. + assert_eq!(app.ui.status, stopped); + assert_eq!(app.ui.status_notes, Some((stopped.clone(), vec![stopped, "Ran chosen".to_string()]))); +} + +#[test] +fn a_last_startup_script_that_cannot_start_shows_in_the_status_bar_when_the_runs_end() { + let dir = folder("startup-last-fails"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + std::fs::write(dir.join("Startup Scripts").join("b.jsx"), big).unwrap(); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "b.jsx"]); + assert_eq!(app.ui.status, format!("b.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); +} + +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding only `0.jsx`, too large to run. +fn oversized_startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + std::fs::write(startup.join("0.jsx"), big).unwrap(); + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn a_launch_whose_only_startup_script_cannot_start_shows_it_in_the_status_bar() { + let dir = folder("startup-launch-too-large"); + let mut app = app(&dir); + oversized_startup_folder(&mut app, &dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + script_runs::run_at_launch(&mut app); + let shown = format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE); + assert_eq!(app.ui.status, shown); + assert!(!app.session.script_running()); + script_runs::poll(&mut app); + assert_eq!(app.ui.status, shown); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_menu_run_after_a_first_startup_script_that_cannot_start_shows_it_and_runs_the_chosen_script() { + let dir = folder("startup-menu-too-large"); + let mut app = app(&dir); + oversized_startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + let reply = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + assert_eq!(reply["running"], true, "{reply}"); + assert_eq!(reply["queued"], true, "{reply}"); + let shown = format!("0.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE); + assert_eq!(app.ui.status, shown); + finish(&mut app); + assert_eq!(started(&app), ["0.jsx", "chosen"]); + assert_eq!(objects(&app), 2); + // The failure stays in sight when the chosen script ends, with its message in the hover. + assert_eq!(app.ui.status, shown); + assert_eq!(app.ui.status_notes, Some((shown.clone(), vec![shown, "Ran chosen".to_string()]))); +} + +#[test] +fn with_run_startup_scripts_on_other_script_with_a_missing_file_fails_before_the_startup_scripts() { + let dir = folder("startup-missing"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let missing = dir.join("gone.jsx").to_string_lossy().into_owned(); + let alone = app.run("script.run", json!({ "path": missing })).unwrap_err(); + app.session.prefs.show_external_script_warning = false; + let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": missing })).unwrap().unwrap_err(); + assert_eq!(e, alone, "the error script.run gives"); + assert!(!app.session.script_running()); + assert!(started(&app).is_empty(), "no startup script ran"); + // The warning opens first; its Run button shows the error. + app.session.prefs.show_external_script_warning = true; + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": missing })).unwrap().unwrap(); + assert!(super::script_dialogs::is_open::(&app)); + assert!(super::script_dialogs::confirm(&mut app, crate::dialogs::script_run::KIND)); + assert_eq!(app.ui.status, alone, "the error script.run gives, after the warning"); + assert!(!app.session.script_running()); + assert!(started(&app).is_empty(), "no startup script ran after the warning"); +} + +#[test] +fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launch_and_a_missing_one_does_not() { + let dir = folder("startup-unreadable"); + let mut app = app(&dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let startup = dir.join("Startup Scripts"); + app.session.attach_startup_scripts_dir(startup.clone()); + app.status("before"); + script_runs::run_at_launch(&mut app); + assert_eq!(app.ui.status, "before", "a missing folder runs nothing and says nothing"); + // A file where the folder should be cannot be listed. + std::fs::write(&startup, "not a folder").unwrap(); + script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running()); + // The message names the folder without its path, which automation replies would show. + assert_eq!(app.ui.status, "The Startup Scripts folder cannot be read"); +} + +#[test] +fn a_menu_run_with_a_startup_scripts_folder_that_cannot_be_read_says_so_and_runs_the_chosen_script() { + let dir = folder("startup-menu-unreadable"); + let mut app = app(&dir); + let startup = dir.join("Startup Scripts"); + std::fs::write(&startup, "not a folder").unwrap(); + app.session.attach_startup_scripts_dir(startup); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + let note = script_runs::STARTUP_UNREADABLE.to_string(); + assert_eq!(app.ui.status, note); + finish(&mut app); + assert_eq!(started(&app), ["chosen"]); + assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); + assert_eq!(app.ui.status_notes, Some((note.clone(), vec![note, "Ran chosen".to_string()]))); +} + +/// `dir`'s `Startup Scripts` folder, attached to `app`, holding one more entry than a listing reads +/// and no script. +fn overfull_startup_folder(app: &mut VectorcraftApp, dir: &std::path::Path) { + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + for n in 0..=vectorcraft_engine::script::folder::Limits::default().entries { + std::fs::write(startup.join(format!("{n}.txt")), "").unwrap(); + } + app.session.attach_startup_scripts_dir(startup); +} + +#[test] +fn a_startup_scripts_folder_not_read_in_full_shows_in_the_status_bar_at_launch_and_after_a_menu_run() { + let dir = folder("startup-truncated"); + let mut app = app(&dir); + overfull_startup_folder(&mut app, &dir); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let note = "The Startup Scripts folder was not read in full"; + app.status("before"); + script_runs::run_at_launch(&mut app); + assert_eq!(app.ui.status, note); + assert!(!app.session.script_running()); + app.status("before"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + assert_eq!(app.ui.status, note); + finish(&mut app); + assert_eq!(started(&app), ["chosen"]); + assert_eq!(app.ui.status, note, "the note stays in sight when the chosen script ends"); + assert_eq!(app.ui.status_notes, Some((note.to_string(), vec![note.to_string(), "Ran chosen".to_string()]))); +} + +#[test] +fn startup_scripts_that_cannot_start_and_a_folder_not_read_in_full_all_stay_in_the_status_bar() { + let dir = folder("startup-notes"); + let mut app = app(&dir); + app.status("before"); + let reply = json!({ + "failed": [{"name": "0.jsx", "error": "too large"}, {"name": "1.jsx", "error": "cannot be read"}], + "truncated": true, + "unreadable": false, + }); + script_runs::reply_notes(&mut app, &reply); + let notes = vec!["0.jsx: too large".to_string(), "1.jsx: cannot be read".to_string(), script_runs::STARTUP_TRUNCATED.to_string()]; + assert_eq!(app.ui.status, "0.jsx: too large", "the first note shows"); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes)), "the hover lists every note"); + // A reply with nothing left out keeps the message. + script_runs::reply_notes(&mut app, &json!({"failed": [], "truncated": false, "unreadable": false})); + assert_eq!(app.ui.status, "0.jsx: too large"); +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9eb203aebb..0e371fb351 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -481,7 +481,8 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]), the Circle tool's ([`crate::dialogs::circle_options::open`]) and the +/// Curvature Circle tool's ([`crate::dialogs::curvature_circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -522,6 +523,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(crate::dialogs::circle_options::open(app)), + // The Curvature Circle tool: how near a path pulls the pointer, the radius label, where + // the circle's anchors go and whether a circular arc gives its own radius. + vectorcraft_tools::curvature_circle::ID => crate::dialogs::curvature_circle_options::open(app), // The Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/crates/ui-egui/src/type_editing.rs b/crates/ui-egui/src/type_editing.rs index 346a5854bf..8ee26749a2 100644 --- a/crates/ui-egui/src/type_editing.rs +++ b/crates/ui-egui/src/type_editing.rs @@ -289,7 +289,7 @@ pub(crate) struct TypeEditor<'a> { impl<'a> TypeEditor<'a> { /// A part for the tool's caret at `caret`, the instance of [`TypeEditorCommand`]'s scope while it has the keys. fn new(app: &'a mut VectorcraftApp, caret: Rect, ctx: egui::Context) -> Self { - TypeEditor { common: Common::new(), app, caret, ctx }.label("Type").command_scope(TYPE_EDITOR_SCOPE) + TypeEditor { common: Common::new(), app, caret, ctx }.label(tl!("Type")).command_scope(TYPE_EDITOR_SCOPE) } /// Applies one input of the editor part to the engine tool; a Paste types `pasted`, the text the paste delivered, diff --git a/crates/ui-egui/tests/control_bar_corners.rs b/crates/ui-egui/tests/control_bar_corners.rs index f11ca7b51e..df1b1a00fd 100644 --- a/crates/ui-egui/tests/control_bar_corners.rs +++ b/crates/ui-egui/tests/control_bar_corners.rs @@ -262,15 +262,15 @@ fn corner_radius_respects_anchor_group_and_narrow_control_bar_space() { let (mut app, id) = ordinary_corner(); let mut wide = Frames::new(1800.0); let shown = wide.settled(&mut app); - assert!(shown.radius_field().is_some() && shown.has_text("Corner Radius:")); + assert!(shown.radius_field().is_some() && shown.has_text("Corners")); app.run("window.control.options", json!({"group": "anchors", "visible": false})).unwrap(); let hidden = wide.settled(&mut app); assert!(hidden.radius_field().is_none()); - assert!(!hidden.has_text("Corner Radius:")); + assert!(!hidden.has_text("Corners")); app.run("window.control.options", json!({"group": "anchors", "visible": true})).unwrap(); - // The label and the field are one row, so a narrow bar leaves out both or neither. + // The Corners link and the field are one row, so a narrow bar leaves out both or neither. let narrow = Frames::new(400.0).settled(&mut app); - assert_eq!(narrow.radius_field().is_some(), narrow.has_text("Corner Radius:"), "the label and the field leave together"); + assert_eq!(narrow.radius_field().is_some(), narrow.has_text("Corners"), "the link and the field leave together"); app.run("select.set", json!({"ids": [id.0]})).unwrap(); app.select_tool("selection"); assert!(wide.settled(&mut app).radius_field().is_none(), "ordinary whole-path Selection has no anchor controls"); diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index b77050f00f..5bb94e3d37 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -217,6 +217,45 @@ fn a_launch_that_stopped_while_two_plug_ins_loaded_offers_to_disable_both() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn startup_scripts_wait_for_the_choice_and_disable_and_continue_leaves_out_the_one_that_was_running() { + let _f = fresh(); + let dir = tmp_dir("startup"); + let scripts = dir.join("Startup Scripts"); + std::fs::create_dir_all(&scripts).unwrap(); + let a = scripts.join("a.jsx"); + std::fs::write(&a, "vc.log('a');").unwrap(); + std::fs::write(scripts.join("b.jsx"), "vc.log('b');").unwrap(); + let launch_dir = dir.join("Launch"); + std::fs::create_dir_all(&launch_dir).unwrap(); + let item = json!({"format": "vectorcraft-launch", "version": 1, "item": {"file": a.display().to_string(), "name": "a.jsx"}}); + std::fs::write(launch_dir.join("launch-1-dead.json"), item.to_string()).unwrap(); + let stopped = ui::begin_launch(Some(&launch_dir), false); + let mut session = Session::new(); + session.attach_startup_scripts_dir(scripts); + session.prefs.run_startup_scripts = true; + let mut app = VectorcraftApp::new(session, Services::default()); + ui::after_start(&mut app, stopped); + let ctx = window(); + asking_frames(&mut app, &ctx); + assert!(ui::choosing(&app)); + vectorcraft_ui_egui::script_runs::run_at_launch(&mut app); + assert!(!app.session.script_running(), "nothing runs while Safe Mode waits for the choice"); + confirm(&mut app, &ctx); + assert!(!safe_mode::active() && !ui::choosing(&app)); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + vectorcraft_ui_egui::script_runs::poll(&mut app); + } + let lines = app.session.script_console().to_json(); + let started: Vec<&str> = lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").filter_map(|l| l["name"].as_str()).collect(); + assert_eq!(started, ["b.jsx"], "the startup scripts run once Safe Mode ends, without the disabled one"); + done(&launch_dir); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() { let _f = fresh(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f3b8a18d85..4b03fb52f7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -110,7 +110,7 @@ the two can still win that race. | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | -| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | +| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a section with `{field: "compression", value: {…}}` (the options it leaves out keep the dialog's values, in Save PDF and in the preset editor, and in an object inside a section such as `compression.color`; a value that isn't an object, null included, is an error), the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). The dialog's Show in Browser button (`file.export.svg.browser`) writes the SVG of the current choices for one page to a temporary folder and opens it in the default browser, leaving the dialog open; a request through `engine.execute` is refused because it opens another app. With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | diff --git a/docs/gaps.md b/docs/gaps.md index 8b19b60ddc..19493e46da 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -67,6 +67,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12: Document Info › Selection Only (`ui.docInfo.selectionOnly`) counts objects in the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | | 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | @@ -530,13 +531,15 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, and `type.retype` takes near matches within a tolerance and words outlined as one compound path; glyphs fused into one contour, near matches in the panel's list, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, installed fonts not yet loaded included, and `type.retype` takes near matches within a tolerance and words outlined as one compound path, in installed fonts not yet loaded too; glyphs fused into one contour, near matches in the panel's list and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). ## G12 Preferences and panels that don't act yet +- **Implemented and tested (2026-11-21):** Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`; kept in memory for the session, not stored) asks `document.info` for the selection: object counts cover the selected nodes and their descendants, and with no artwork selected it shows `(No artwork selected)` instead of the document's counts, while artboards the Artboard tool has selected still show under Document. With the item off, counts stay for the whole document. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. + - **Implemented (2026-11-20):** History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. - **Implemented and tested (2026-11-21):** OpenType panel feature rows have an item context menu. A secondary click keeps the text selection and offers Turn Off when the feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step; a checkbox click stays a toggle. The Stylistic Sets button and the East Asian menu items are unchanged. Headless regression coverage: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. @@ -1008,6 +1011,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12: Document Info › Selection Only (`ui.docInfo.selectionOnly`) counts objects in the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | | 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 0de3513eac..6f567df149 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores -`precision`. A save writes -a temporary file and renames it over the old one, so a failed save never damages the file; only the images the -document uses are written, and document keys written by a newer version are kept. +`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete +content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it. +A failure during that copy reports the locations of the new content and any saved original. +Only the images the document uses are written, and document keys written by a newer version are kept. +On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails, +the save reports an error stating that the file was written. An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON. @@ -2721,9 +2724,17 @@ value, assignment target or property they are first given to, with `get ` or `se Symbol key's description in brackets; `bound ` before the target's name for `bind`; `anonymous` for `Function`; and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). A function's `length` can be redefined. The built-in functions get their names the first time a run reads -ECMAScript 2015, and keep them in later `.jsx` runs of an engine that `#targetengine` keeps. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and +ECMAScript 2015, and keep them in later `.jsx` runs of an engine that `#targetengine` keeps. A `.js` script also has +generator functions (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): +`function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which +passes `next`, `throw` and `return` on to the iterator it delegates to. Calling a generator function returns a +generator object whose `next`, `return` and `throw` run its body to the next `yield`; `return` runs the body's +`finally` blocks, and resuming a generator while its body runs throws a `TypeError`. Each resumption takes fuel and +counts against the call depth. A generator function called in an engine that `#targetengine` kept from a `.jsx` run +throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. A `.js` file +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`yield` is a name like any other. A `.js` file also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or `null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&` @@ -2809,12 +2820,14 @@ other files through `$`: the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, - `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer + `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an - object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself + object that is hidden or locked itself takes `hidden`, `locked` and `opacity` (VectorCraft's own rule). Position, + size and stacking-order changes also require a selectable object. Other targets excluded by selection filtering, + including guide paths while Lock Guides is on, throw `Cannot select`. `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such @@ -2858,9 +2871,9 @@ other files through `$`: the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or - with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + a list of at most 10,000, `null` or `[]`. Any other value, `undefined` included, throws a `TypeError`, and an + object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock + Guides is on, a path made into a guide cannot be selected this way or with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, @@ -2874,6 +2887,14 @@ other files through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) + with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each + `Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page + item) and `remove()`; they run the `object.tag.*` commands. VectorCraft's own rules: a collection lists the tags in + their order on the object, and `Document.tags` lists every page item's tags in `pageItems` order and throws an error + on `add()`; `add()` gives a tag with an empty name and value; `getByName` gives the first tag with the name; + `name` and `value` take strings of at most 65,536 bytes, and an object has at most 64 tags. A tag that was deleted + throws `Stale tag`, and one whose page item was deleted throws `Stale page item`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -2896,15 +2917,23 @@ In a `.js` script, `Promise` follows ECMA-262 11th edition section 25.6 `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. `Promise.any` is not provided. These are VectorCraft's own rules: +- `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available. The property is configurable, + non-enumerable and non-writable. Promise instances also report `[object Promise]` in engines without Symbols. - The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. A promise still pending when no job is left stays pending, and the run ends. +- In the host API, `Realm::run` and `Realm::start` end a paused or waiting run before compiling the new source. + The earlier run's globals remain available; its remaining code and queued jobs do not run. - The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. -- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one - item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the +- `all`, `allSettled` and `race` read their input through `Symbol.iterator`, including user-defined iterables and + overridden array iterators. In a kept engine with no `Symbol.iterator`, they walk arrays, `arguments` objects and + strings. String iterators keep surrogate pairs together. A noniterable object, including one + with only a `length`, rejects the promise they return with a `TypeError`. When processing a yielded value throws, + the combinator calls the iterator's `return` method if present; the original exception remains the rejection reason + even when `return` throws. An iterator whose step threw or finished is not closed. The promises `then` and the statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. - A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was @@ -3367,18 +3396,18 @@ VectorCraft writes files by these rules of its own: `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. -`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file, error?}`, with `code` the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is -matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script +matched as given, or after its links are followed when no grant holds it as given; under automation read roots, a path outside them is matched as given only. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well -formed. A script +formed. Preferences › General › Script File Access shows the error `script.grants` gives. A script cannot run either command. ```json @@ -3476,6 +3505,69 @@ leaves out the listed scripts outside the read roots. vectorcraft-cli run --cmd script.listInstalled --params '{}' ``` +### Startup scripts + +With Preferences › General › Run Startup Scripts on (`runStartupScripts`, off by default), the `.jsx` files of the +`Startup Scripts` folder next to the preferences run when VectorCraft starts, and again before each script chosen from +File › Scripts, whether a listed script or Other Script…. The folder is `~/Library/Application +Support/VectorCraft/Startup Scripts` on macOS, `%APPDATA%\VectorCraft\Startup Scripts` on Windows, and +`$XDG_CONFIG_HOME/vectorcraft/Startup Scripts` or `~/.config/vectorcraft/Startup Scripts` on Linux and BSD. +VectorCraft does not make the folder. The scripting guide +https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf +(page 11) describes startup scripts as `.jsx` files that run when the application starts and each time a script is +run. + +The rest of this section is VectorCraft's own rules: + +- Only the folder's own `.jsx` files run, never its subfolders. Links, names that start with a dot, files Windows marks + hidden or system, names longer than 255 bytes and other file types are left out. A listing stops at 2,048 folder + entries or 250 ms and holds at most 512 scripts. When it stops at a limit, leaves out scripts past 512 or skips an + entry it cannot read, the status bar says that the folder was not read in full. A folder that is missing runs + nothing. At launch and before a chosen script, when the folder is there and cannot be read, or a file is where the + folder should be, the status bar says that the folder cannot be read. +- These two notes, the names of startup scripts that could not start, and the message of each startup script that + failed or was stopped stay in the status bar after the last run ends: the status bar shows the first of them, and + its hover lists them all, then the last run's message. +- The scripts run one at a time, sorted by name without regard to case, then by name. Each runs as `script.run` runs a + file, with the same limits, and each that changes a document adds its own Run Script undo step. The chosen script + runs after the last of them. +- A startup script that cannot be read, is larger than 8 MiB, throws, runs out of instructions or is stopped is named + in the Script Console and the status bar, and the next one runs. The app opens and the chosen script runs either way. +- In Safe Mode nothing in the folder runs. After a launch that stopped, the startup scripts run once the person + chooses Disable and Continue or Start Normally. While a startup script runs, the launch marker names it, so a launch + that stops during one offers to disable that script. A disabled startup script does not run, and the reply names it + in `disabled`. +- Running the startup scripts is itself a `script.*` command, which a script cannot run, so a startup script cannot + start another round of them. `script.run` called from automation runs alone. +- The web build has no Startup Scripts folder, and neither has a run with `VECTORCRAFT_NO_PREFS` set. + `vectorcraft-cli` uses the same folder and runs it only through `script.startup.run`. + +`script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s +parameters for a script that runs after the startup scripts. A `then` that `script.run` would refuse, such as a +missing file, one larger than 8 MiB, or source that fails to compile, ends the request with `script.run`'s error +before any startup script runs. Compilation does not execute the chosen script. The chosen script runs the source +read before startup scripts begin, including when a startup script removes the installed file. +Included files are read again when the chosen run starts, so edits to them during startup affect that run. +A failed chosen-script compilation clears the previous script report. In the app, each queue pump processes at +most one startup entry and keeps later entries in order, including after a startup entry fails. +`maxFuel` limits each startup script's instructions +(from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, +`safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], +disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In the app the runs are queued and the +reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming +the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the +next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the +status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from +the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a +read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, +or its error when the chosen script cannot start, and add `startup` holding the `script.startup.run` reply. While a +startup script runs before the chosen script, that reply is `{running: true, queued: true}`, and a chosen script that +then cannot start is named in the status bar. + +```sh +vectorcraft-cli run --cmd script.startup.run --params '{"reason": "launch"}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage @@ -6367,9 +6459,13 @@ and several can be open at once. `window.swatchLibrary {library}`, `window.graph `{open, panel, name, count}`; `library: null` closes every panel of that kind. The panel id is `library::` (`library:swatches:pastels`, `library:graphicStyles:hand-drawn`, `library:swatches:loaded/C:/Palettes/Brand.ase`), and the panel commands take it like any other panel's: -`window.panel.float {panel, onto?, x?, y?, width?, height?}` groups, moves or resizes it. Supplied -geometry also updates an existing native panel window. Positions are relative to the main window's -content origin; omitted coordinates and dimensions keep the native window's current values. +`window.panel.float {panel, onto}` makes it a tab of the floating group holding `onto`, and +`window.panel.float {panel, x?, y?, width?, height?}` moves or resizes it; `onto` takes no geometry. +Positions are relative to the main window's content origin. When the panel is alone in a native panel +window, or `column: true` (or `group: true` on a tab group that fills the window) names the whole window, +supplied geometry updates that window and omitted coordinates and dimensions keep its current values. +A panel that shares a native window with other panels floats into a new window instead, which takes the +supplied geometry, and the shared window keeps the other panels, its place and its size. `window.panel.dock {panel}` docks it, `window.panel.close {panel}` closes it. `window.swatchLibrary.other {path}`, `window.graphicStyleLibrary.other {path}`, `window.symbolLibrary.other {path}` and `window.brushLibrary.other {path}` load a file and open it the same @@ -7194,8 +7290,20 @@ range is an error and changes nothing. The help page [Create image maps for web graphics](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/create-image-maps-for-web-graphics.html) describes the same 1 to 30 range; the default of 10 is VectorCraft's own value. +An object's tags are name and value pairs that scripts keep on it (`PageItem.tags`). `object.tags {id}` lists them in +order → `{tags: [{tag, name, value}]}`, where `tag` tells each one apart from the object's other tags. +`object.tag.add {id, name?, value?}` adds one after the others → `{tag}`, `object.tag.set {id, tag, name?, value?}` +changes its name or value → `{changed}`, `object.tag.remove {id, tag}` deletes it, and `object.tag.removeAll {ids?}` +deletes every tag of the objects in `ids` or the selection → `{changed: objects}`; each edit is one undo step, and an +edit that changes nothing adds none. Names may be empty or repeated. An object has at most 64 tags, each name and +value at most 65,536 bytes; a layer or a ruler guide has none, and a bad value (a null name or value included) is an error that changes nothing, as is +an add in a document whose ids have reached the top of their range (a damaged or hand-made file). The +native file keeps the tags and their `tag` ids, and opening one keeps the first 64 tags of each object whose name and +value are within the limit, giving a new id to a tag whose id is missing, out of range or repeated. Copies keep their source's tags. Other file formats do not write them. + ```json {"name":"run_command","arguments":{"command":"attributes.set","params":{"ids":[12],"url":"https://example.com","imageMap":"rectangle"}}} +{"name":"run_command","arguments":{"command":"object.tag.add","params":{"id":12,"name":"size","value":"XL"}}} {"name":"run_command","arguments":{"command":"path.setFillRule","params":{"rule":"evenOdd"}}} {"name":"invoke_menu","arguments":{"command":"ui.attributesPanelOptions","params":{"count":20}}} ``` @@ -7771,13 +7879,16 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog ## Curvature circle -`shape.curvatureCircle {id, subpath?, segment, t, convex?}` draws the circle that touches path `id` at `t` (0 to 1) on -segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there (its circle of curvature), -as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with -`convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two -ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a -circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. The -result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. +`shape.curvatureCircle {id, subpath?, segment, t, convex?, constantRadius?, anchors?}` draws the circle that touches +path `id` at `t` (0 to 1) on segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there +(its circle of curvature), as a live ellipse with the current paint, and selects it. The circle goes on the side the +path bends toward; with `convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc +of 90° or less (its two ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for +an arc of θ) gives a circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the +circle itself. With `constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at +`t` instead. The circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` (`"standard"` when left +out) the circle is a plain path with an anchor where it touches the path and one every 90° from there. The result is +`{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle @@ -7787,8 +7898,10 @@ marked smooth), when the circle would reach past the canvas (4,000,000 pt from t origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The -pointer snaps to the nearest path that is not a guide within 5 screen points, or within Smart Guides › Snapping -Tolerance when that is larger, and the tool shows the circle that matches the path there as a dashed outline (solid +pointer snaps to the nearest path that is not a guide within the tool's Snap Tolerance (`snapTolerance` below, 5 +screen points by default), or within Smart Guides › Snapping Tolerance when that is larger; with Snap with Smart +Guides Off turned off, the reach while Smart Guides are off is no more than Selection & Anchor Display › Tolerance. +The tool shows the circle that matches the path there as a dashed outline (solid once it is more than 50,000 screen points around), a small cross at its center, a line from the center to the point it touches and, with Measurement Labels on, its radius by the pointer, followed by an asterisk for an arc's own radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; @@ -7799,6 +7912,21 @@ selection made outside the tool leaves none of them selected, another tool is ch active, or an edit, Undo or Redo is made outside the tool. Selecting one of them again does not put it back out of reach. +Curvature Circle Tool Options (`tool.options {tool: "curvatureCircle"}`, or a double-click on the tool, dialog +`curvatureCircleOptions`) sets the tool's options, which `tool.setOption {tool: "curvatureCircle", values}` also sets +and the preferences keep. The range, the default and the rule for Snap with Smart Guides Off are VectorCraft's own. +Every switch is on by default, and the tool draws as it did before the options existed until one is changed: + +- `snapTolerance` (Snap Tolerance, 1 to 40 screen points, 5 by default) is how near a path pulls the pointer. Smart + Guides › Snapping Tolerance applies when it is larger. +- `snapWithoutGuides` (Snap with Smart Guides Off) off makes the pointer reach no further than Selection & Anchor + Display › Tolerance while Smart Guides are off. When that tolerance is as large as the reach above, turning the + switch off does not change the reach. +- `annotateRadius` (Annotate Radius) off hides the radius label. The label also needs Measurement Labels on. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "touch"`. +- `constantRadius` (Use the Radius of Circular Arcs) off draws with `constantRadius: false`, and the label has no + asterisk. + ```json {"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} ``` @@ -7890,6 +8018,22 @@ toolbar its controls wrap onto more rows. `ui.inspect` gives `quickPenToolbar` ( the pin and whether it shows are not saved. These commands run in the desktop app; the headless host does not run them, so they need `--connect`. +With no path being drawn (after Escape or Enter, or before the first click), the tool edits the selected paths, as +[Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) +describes. A drag on one of their anchors moves that anchor, and a drag that starts on one of several selected anchors +moves them all; a drag on a segment moves that segment's two ends. The tool selects what it moves +(`select.anchors` or `select.segments` with `mode: "set"`) and moves it with `path.moveAnchors {dx, dy, interpolate: +true}`, one undo step per drag: a segment with one moved end is turned and scaled to its new ends, so beside a corner +anchor a line stays a line and an arc stays an arc through the same angle; at a smooth anchor the handles stay in line +and the segments bend to meet, so an arc there need not stay circular. A dragged anchor +snaps to Smart Guides; a dragged segment does not. Escape during the drag takes it back. A click on an anchor selects +it alone and Shift-click adds it to the selected anchors or takes it out (`select.anchors` with `"set"` or +`"toggle"`). A click on an end of an open path still goes on drawing from it, a drag there moves the end, and a click +on a segment starts a new path. With the Quick Pen chosen, the canvas context menu (right-click) has Delete, which +removes the selected anchors, or the selected objects (`edit.clear {}`). While a path is being drawn, a press on it +adds a piece as before. Which presses select, which move, and the drag snapping only an anchor are VectorCraft's own +rules. + `path.quickPen {start?: [x, y], id?, subpath?, keep?, pieces?, closed?}` draws such a path and selects it, as one undo step, and answers `{id}`. With `start`, it makes a new path with the current paint (a black stroke when the paint has neither fill nor stroke). With `id`, it draws on the open subpath `subpath` (0 when left out) of that path: its @@ -8295,6 +8439,17 @@ and those shape tools: hidden widgets are not drawn, and those tools do not answ on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. +In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with +Direct Selection, while a corner is selected or one live rectangle or polygon is selected) opens the Corners pop-up for the picked corners of every selected path: +the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors +hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the +rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the +paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no +undo step. Editing a path's anchors (for example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. +With Relative rounding, a radius is +compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius +shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one +`object.setLiveShape` with `items`, one undo step, and the corners that were not picked keep their radius and kind. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"id":12,"corners":[1],"radius":16}}} @@ -9753,7 +9908,8 @@ light one, by the wedge colors as pasted: a wedge linked to a swatch merged with color first. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists -them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the +them (with `allArtboards: true`, the colors as Paste on All Artboards brings them, without the background colors of +copied artboards), and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the pasted swatch comes in renamed) or one answer per name. When a merged swatch turns a pie's wedge from light to dark or back, the legend labels in that pie's wedges take the contrast a redraw gives them (white on a dark wedge, black on a light one), unless the legend labels have a fill of their own. Pasting back into the document the objects came from @@ -11246,7 +11402,8 @@ kept and do not change the file. An unknown method or an amount outside 0 to 100 file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table (`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` -previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. +previews one slice, and a `slice` that is not a whole number from 1 up is an error; `image: true` adds the file; +`warnings` holds the export's warnings. Delete Color is `colorTable.deleted: ["#rrggbb"…]`, by `source`. The deleted colors leave the table and the file, and their pixels take the nearest color left, with the current reduction's color distance and dither; the preview and the @@ -11291,6 +11448,30 @@ are written as lowercase `#rrggbb`. A `#rrggbbaa` spelling names no table color. right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off. +Save Color Table is `document.exportForWeb.saveColorTable {path?, slice?, …settings}`. It writes +the GIF or PNG-8 color table the preview shows as a color table file (`.act`) in the layout the file format +specification gives (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 entries of three bytes (red, +green, blue) in file order, with zero bytes after the colors used, then the number of colors used and the index of the +transparent entry, two bytes each with the most significant byte first. The file is always 772 bytes, and the index is +65535 when the table has no transparent entry. A color shifted by hand is written as its new color. Without `slice` +the file holds the whole image's table, also when `slices` is `selected` and no slice is selected; a `slice` is looked +up among the slices `slices` names. `.act` is added to +a `path` without an extension, and without `path` the file comes back as `dataBase64`. The reply is `{path, colors, +transparentIndex, bytes, warnings}` (`transparentIndex` is null when there is none). An empty `path`, JPEG and PNG-24 +are errors, and the +document and the settings do not change. Load Color Table is `webExport.loadColorTable {path | dataBase64, +…settings}`. It reads a 768-byte file (256 colors, no transparent entry) or a 772-byte one (the number of colors used, +1 to 256, and the transparent entry's index; an index past the colors used names no entry) and returns +`{colors, transparentIndex, settings}`: the settings with the file's colors other than its transparent entry as +`colorTable.customPalette`, `colors` set to the number of colors the file uses (at least 2), the table's other edits +(`locked`, `transparent`, `deleted`, `shifted`, `webShift` and `sort`) cleared and `webSnap` set to 0, so every loaded +color is written as it is, in the file's order, and none is locked. A file whose only color is its +transparent entry loads that color. Another file size (base64 text included), a count of 0 or above 256, both or +neither of `path` and `dataBase64`, and JPEG or PNG-24 are errors; the command reads at most 773 bytes of a file and +remembers nothing. The Save for Web dialog's color table menu does not list Save Color Table… or Load Color +Table… yet; both commands run through the engine and MCP. The help page describes both entries +(https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404). + ```json {"name":"run_command","arguments":{"command":"document.exportForWeb.preview","params":{"format":"png8","colorTable":{"deleted":["#ff0000"],"customPalette":["#0000ff","#00ff00","#ff0000"]}}}} ``` @@ -11800,6 +11981,18 @@ PDF/X-4 always embeds one), a TrimBox on every page (the artboard), `/Trapped` T document has none) and dates; type is outlined or embedded; editing data, passwords and, in PDF/X-1a and PDF/X-3, PDF layers are refused. +The built-in CMYK working spaces `VectorCraft Coated CMYK (FOGRA51)` and `VectorCraft Uncoated CMYK (FOGRA52)` are +VectorCraft's own press models, computed when first used from the FOGRA51 and FOGRA52 characterization data that Fogra +publishes (); the data files ship unmodified in +`crates/color/data/`. An output intent with one of them, and with `output.outputConditionId` blank, has the +`/OutputConditionIdentifier` `FOGRA51` or `FOGRA52` and, unless `output.registry` names another, the `/RegistryName` +`http://www.color.org` (), with the profile embedded. Their total ink limit +(300%) and black generation are VectorCraft's own values. + +```json +{"name":"run_command","arguments":{"command":"document.exportPdf","params":{"path":"/tmp/press.pdf","preset":"PDF/X-4:2010","output":{"outputIntent":"VectorCraft Coated CMYK (FOGRA51)"}}}} +``` + - **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB destination or output intent is refused. Transparency is flattened before writing. @@ -12068,6 +12261,23 @@ lines. The rest are VectorCraft's own rules: Maximum word spacing moves out to `wordGap` when `wordGap` lies outside it. The paragraphs keep their own Justification… values, which apply again when Block is off. Each character's leading is its size plus `lineGap`. A gap given with no area type in the selection, and no point type that it turns into area type, is an error. +- A leading change on the frame's text sets `lineGap` to the new leading less the size of the first character changed, + within -1,296 to 1,296 pt, in the change's own undo step. That covers `text.setStyle {leading}` and + `text.setRangeStyle {leading}` (the Character panel's and the Properties panel's Leading field and its list), + `type.step {attribute: "leading"}` (the Type tool's Alt+arrow leading steps), `charStyle.apply` with a style that sets + a leading (or with `clearOverrides` when the Normal style sets one), `charStyle.edit` and `charStyle.setAttrs` when + the new definition gives its users another leading, and `addon.type.textTweaker {attribute: "leading"}`. Text + Tweaker's ramp sets the gap from its first changed character, and every other character then takes its size plus + that gap, so the ramp does not vary the leading. `"auto"` takes the first character's Auto leading. Every line then + spreads or tightens by the change to that character's leading. The Eyedropper (`appearance.copyFrom`) copies a whole + character style, so it leaves `lineGap` as it is. In a shaped frame where the moved lines take another size, the gap + is worked out again from the new size, up to four times, and the leading set can then differ by the last change in + that size. When the changed characters share one size and the gap is within its range, the Leading field shows the + leading set. Otherwise each character takes its own size plus the gap, and the field is blank where those differ. + `keepLineGap: true` on `text.setStyle` and `text.setRangeStyle` leaves `lineGap` as it is, and the Character panel's + Reset Panel sends it, so a reset to Auto leading keeps the frame's Line Gap. Point type, type on a path and area type + with Block off keep their own leading. If Block cannot fit a frame, editing a character style keeps each run's + manual leading override. When Block can fit the frame, its generated leading follows the edited style. - The sizes are written into the characters, so every export and the Character panel see them. After every edit to the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at @@ -12206,7 +12416,9 @@ comparison per contour and one more; past them, the glyphs not yet ranked or com selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes -in proportion are indexed. +in proportion are indexed. These limits apply to each set of up to 96 fonts compared and to each installed font read +(see Retype installed fonts). When Retype finds fonts past the first 96, every shape is matched again with all the fonts +found, and the limits start again for that match. ```json {"name":"run_command","arguments":{"command":"type.retype","params":{"tolerance":0.02}}} @@ -13370,7 +13582,7 @@ on an open path that are not drawn because they fall before the path's start can ## Retype tracking -`type.retype {fonts?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app +`type.retype {fonts?, tolerance?, installed?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app has. A line of three or more exactly matched glyphs (none a near match, see `tolerance`) gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype tries the value rounded to a whole number first when it is within 0.05 of one, then the value as measured. The font's advances and pair kerning are left out of the measure, and word spaces are counted after the tracking. The tracking is @@ -13418,22 +13630,62 @@ the result's `texts` list holds an object's lines joined by `\n`, and each entry ## Retype panel -`type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path +`type.retypeFonts {count?, installed?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path and compound path, inside groups too, with the glyphs of up to 96 loaded fonts, those of the document's live type first, by the matching `type.retype` uses, and it counts only exact matches of whole shapes: it does not split a compound path into glyphs or take near matches. When two versions of a font are loaded, only the version its family and style name gives is compared, which is the version that choosing the font sets. The fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name. `count` is a whole number from 1 to 96 (default 10); any other value is an error. The reply is -`{fonts: [{family, style, matched}], shapes, more, truncated}`: `matched` is the number of shapes the font matches, -`shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and `truncated` is true when -shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as outlines because of -their paint still count. A font whose glyphs match the shapes only as combining marks is not listed. The -command does not change the document and records no undo step. With no path or compound -path selected it is an error. +`{fonts: [{family, style, matched}], shapes, more, truncated, installed}`: `matched` is the number of shapes the +font matches, `shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and +`truncated` is true when shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as +outlines because of their paint still count. A font whose glyphs match the shapes only as combining marks is not +listed. The command does not change the document and records no undo step. With no path or compound path selected it +is an error. `type.retypeFonts` also compares the installed fonts that are not +loaded yet, as described under Retype installed fonts, and reads every installed file within those limits, so one +search can read up to 2 GiB; the fonts that match are loaded and ranked with the others while the list holds fewer +than 96 fonts. A matching font that is shadowed by another version of the same family and style is loaded and not +listed, and does not take a place. `installed` is `{read, skipped}` as for `type.retype`; when the list is full, the +installed faces not compared count as skipped, and `more` does not count them. -Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to -96 fonts and lists the first ten. Find more font matches, at the end of the list when `more` is true, runs +## Retype installed fonts + +`type.retype {fonts?, tolerance?, installed?}` compares the shapes that no loaded font, document font or font in `fonts` matches +with the installed fonts that are not loaded yet. Every loaded font is compared first: the document's fonts, the fonts +in `fonts` and the fonts earlier searches loaded come first, and the loaded fonts past the first 96 are compared, 96 at +a time, with the shapes that are not plain and that the first 96 do not match. Both comparisons match as Retype does +with the first 96 fonts: with a `tolerance`, near matches count, and a compound path of several glyphs counts when every +glyph it splits into matches. The search of the installed fonts reads their files one at a time, smallest first, and +stops when every such shape matches the fonts it has read. It leaves out files larger than 256 MiB, and the files and +faces past 2 GiB read or 500,000 glyphs drawn in all. A file is read for the search and then released; a font whose +glyphs match a shape, or complete the glyphs of a split compound path with the fonts found before it, is loaded from +what the search read, without the family's other files. The fonts found are then matched with every selected shape, +the shapes that matched already included, as the first 96 fonts are. A plain shape (one contour of up to +four straight edges, such as a rectangle or a hyphen) does not start the search, and matches only a font the other +shapes found. With `installed: false` the installed fonts are not read; `installed` true, omitted or null reads them, +and any other value is an error. The result's `installed` is `{read, skipped}`: the installed faces compared, and the +faces the limits left out. These limits are VectorCraft's own. + +The fonts a search loads stay loaded for the rest of the session, also when Retype then finds nothing to set, and later +searches in every open document compare them ahead of the other loaded fonts. A request that is canceled (an MCP +cancel) stops the search between files and leaves the document as it was; the fonts loaded before the cancel stay +loaded. In the app, Type › Retype and Find Matching Fonts (the Retype panel's button, or `retype.find` run from a +menu or the command palette) search on a thread of their own: the +status bar shows "Finding matching fonts…", and a progress window with Cancel (also Esc) opens when the search takes +longer than 0.4 seconds. Cancel runs `retype.cancelSearch {}` → `{cancelled: n}`, after which Retype changes nothing +and the list stays as it was. When the search is done, Retype runs, or the panel lists the fonts, with the fonts the +search found, without reading the installed fonts again. If the document or its selection changed meanwhile, nothing changes and the status bar says to run it +again. `retype.find {installed: false}` lists the loaded fonts only. The control channel and scripts run the commands +at once. + +```json +{"name":"run_command","arguments":{"command":"type.retype","params":{"installed":false}}} +``` + +Window › Retype shows the Retype panel. Find Matching Fonts searches as `retype.find {}` does, reading the installed +fonts in the background (see Retype installed fonts); `retype.find {}` shows the panel, ranks up to 96 fonts and lists +the first ten, and `retype.find {installed: false}` compares the loaded fonts only. Find more font matches, at the end of the list when `more` is true, runs `retype.find {more: true}`, which adds the next five fonts that search found, whatever is selected now. Before any search, `retype.find {more: true}` runs a first search. With `more` false, omitted or null, `retype.find` runs a new search; any other value than true, false or null is an error. A search that fails is an error and leaves the list as @@ -13447,7 +13699,7 @@ of `type.retype` (2,048 shapes, 16 nested groups); the panel then says that some `size` is `small`, `medium` or `large`, and `text` is the samples' text (empty for a generic sample). The panel menu's Small, Medium and Large items and the sample field run `retype.preview {size?, text?}`. `text` holds at most 100 characters; any other value of either key is an error and changes nothing. Reset Retype Panel in the panel menu runs `retype.reset {}`, which clears the list and keeps the size -and text. `retype.find`, `retype.preview` and `retype.reset` return what `retype.list` returns. +and text; a search Find Matching Fonts started in the background stops and does not fill the list. `retype.find`, `retype.preview` and `retype.reset` return what `retype.list` returns. ```json {"name":"run_command","arguments":{"command":"type.retypeFonts","params":{"count":5}}} @@ -13883,7 +14135,10 @@ them again at startup (`plugin.remove` deletes them there). A window or process while it changes it, so installs, removals, grants and plug-in settings from two of them do not mix; when the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing: `plugin.install {path | dataBase64}` installs one, `plugin.list` / `plugin.info {id}` describe them (parameters, -schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one +schema, defaults). An object filter may also be a JavaScript plug-in: a `.vcplugin` manifest with `"runtime": "js"` and +`script`, the `.js` file beside it, which `plugin.install {path}`, `plugin.inspect {path}` and `plugin.reload` read +together (`runtime` and `script` in its entry); it runs in an interpreter of its own with no file, command or clock +access ([plugins.md](plugins.md#javascript-filters)). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one undo step; it may change, delete or add objects, and the result is selected; a run that changes no object and no kept data records no undo step and leaves the document unmodified) → `{plugin, ids, notice?, pluginName?}`. `notice` is the text the filter's output reports in its `notice` key, escaped and cut at 200 characters @@ -16270,10 +16525,11 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and -`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, -Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the -selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check`, +`addon.packaging.setFoldAngle` and `addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold +Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run +`addon.packaging.setRole` on the selection, Check Fold Lines runs `addon.packaging.check`, Set Fold Angle… opens the +options of `addon.packaging.setFoldAngle`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -16304,11 +16560,17 @@ the color it shows, no longer linked to the swatch, and stops overprinting. Text objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. -`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's -swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object -of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are -counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows -these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so. +`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected, foldLines, +foldAngle, ownAngles, storedAngles}`: each role's swatch, whether the document has it, and how many of the objects have +the role. It counts the selection, or every object of the document while nothing is selected and `ids` is left out +(`scope` says which). Locked and hidden objects are counted in every scope, and an object is counted once when both it +and its group are given. `foldLines` is how many of the Crease, Partial Cut and Perforation lines among them +`addon.packaging.setFoldAngle` can change, which leaves out locked and hidden lines; it is 0 while nothing is selected +and `ids` is left out, and while the selection holds only a layer and objects in it. `foldAngle` is the angle in degrees +those lines all fold at (see Fold angles), or null when they fold at different angles or there are none; `ownAngles` is +how many of them have an angle of their own, and `storedAngles` how many hold stored angle text, an angle or not, which +`reset: true` removes. The Fold Lines panel shows these counts; clicking a role gives the selected paths that role. With +nothing selected the panel says so. `addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or @@ -16369,17 +16631,47 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold angles + +A Crease or a Perforation folds 90° away from the printed side, so the print ends up outside, and a Partial Cut folds +90° toward it. A Crease, Partial Cut or Perforation line can have an angle of its own instead, from -180° to 180°: a +positive angle folds away from the printed side and a negative one toward it. The angle is stored in the line's data +under `vc-fold-angle` as a number of degrees, rounded to the millionth of a degree (a stored value with more places +folds at it rounded the same way). Native files keep it. SVG export leaves it out of the path's attributes; an SVG with +`preserveEditing` keeps it in the document the SVG carries. A value that is not a number from -180 to 180 counts as no +angle of its own. A cut line ignores it. A line keeps its own angle when `addon.packaging.setRole` gives it another +role, or `none`, so a line made a Partial Cut after it was given 45° still folds at 45°; `reset: true` takes the angle +away. In the Fold Preview window, a panel folded flat onto another (180°) is drawn behind that panel's printed side, and +at -180° in front of it. Panels folded flat onto each other stack as they do when the blank is folded about its largest +panel, whichever panel the window folds about. + +`addon.packaging.setFoldAngle` (`{angle?: -180..180, reset?: false, ids?}`) gives each Crease, Partial Cut and +Perforation line among the objects (the selection by default), through groups and clip groups, the angle, or with +`reset: true` takes the line's own angle away. Give exactly one of `angle` and `reset: true`. Locked and hidden objects +are skipped as `addon.packaging.setRole` skips them; cut lines and objects without a role are skipped and counted. The +command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside +the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. + +Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the +angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. +While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection +holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it, and the Reset button beside it takes their own angles away. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.setFoldAngle","params":{"angle":135}}} +``` + ### Fold Preview `addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it -to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from -the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of -panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, -whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of -hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything -else is an error. The command does not change the document. +to the base, each by its angle times `amount` (0 is flat, 1 is folded). A hinge's angle is the fold angle of the line +with the most length in it (see Fold angles), the one with the lowest id among lines of equal length. A hinge that closes +a loop of panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all +the way, whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no +chain of hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; +anything else is an error. The command does not change the document. Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document diff --git a/docs/plugins.md b/docs/plugins.md index 1e98bf058d..0775c0da43 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -21,6 +21,9 @@ There are four kinds of plug-in: paths and compound paths. File › Open lists their files, File › Open With lists the importers by name, and the host hands them the file's bytes. +An object filter may also be written in JavaScript, as a manifest and a `.js` file ([JavaScript +filters](#javascript-filters)). + This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the `plugin.*` commands in `crates/engine/src/cmd/plugin.rs`). @@ -28,14 +31,14 @@ in `crates/engine/src/cmd/plugin.rs`). | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, context?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `context` lists the [document information](#document-information) it reads; `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, context?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `context` lists the [document information](#document-information) it reads; `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `runtime: "js"` and `script` mark a [JavaScript filter](#javascript-filters); `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. An output that changes no object and none of the data it keeps with the document ([`documentData`](#output)) records no undo step and leaves the document unmodified. | -| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | +| `plugin.install` | `{"path": "/x/y.wasm"}` or a [JavaScript filter's](#javascript-filters) `.vcplugin` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | | `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). | | `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). | | `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. | -| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` files past the first 1,000, which were not tried. | +| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` and `*.vcplugin` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` and `*.vcplugin` files past the first 1,000, which were not tried. | Live effects are applied like any effect: `effect.apply {"effect": "plugin.", "params": {…}}`, edited with `effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance. @@ -1224,6 +1227,61 @@ and `wat::when_given` a plug-in whose output depends on whether its input or par in a live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host functions. +## JavaScript filters + +An object filter may also be written in JavaScript (ECMAScript 5.1, the language VectorCraft's scripts use). The +plug-in is two files in one folder: a manifest, `.vcplugin`, and the `.js` file it names in `script`. + +```json +{"id": "org.example.tint", "name": "Tint Blue", "kind": "filter", "runtime": "js", "script": "tint.js", + "params": {"blue": {"type": "number", "min": 0, "max": 1, "default": 1}}} +``` + +```js +function run(input, params) { + return {objects: input.objects.map(function (o) { + return {id: o.id, fills: [{type: "solid", color: {model: "rgb", r: 0, g: 0, b: params.blue}}]}; + })}; +} +``` + +The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to +128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so +existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind` +`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or +`commands`, so it has no `commandAllowlist`. + +`plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload` +install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other +than `"js"`, and refuses a manifest file over 64 KiB or a script over 8 MiB by its size before reading it; under +automation read roots the script must be inside them too. The host reads the two files into one JSON object, the +manifest with the script's text in `source`: `plugin.install {dataBase64}` takes that object, the `Plug-ins` folder keeps +it as the plug-in's file, and `hash` is its SHA-256, so a changed manifest or script needs a new approval. Installing +parses the script and runs none of it; a syntax error is an install error with its line and column. + +Each run gets a new interpreter with its own heap, so nothing one run defines or changes, the built-ins' prototypes +included, reaches the next. The script's top level runs, then `run(input, params)` is called with the parsed +[input](#input) and [parameters](#parameters), and what it returns is written as JSON and checked +as a module's [output](#output) is, before anything in the document changes. The global object holds the language's +built-ins and `vc`: + +| Member | What it is | +|---|---| +| `vc.input`, `vc.params` | The input and parameter JSON as text. | +| `vc.progress(done, total)` | As `vc_progress` ([host imports](#host-imports-api-level-2)); with `progress` only. | +| `vc.cancelled()` | `true` once the user cancelled or the time budget ran out; with `progress` only. | +| `vc.log(level, text)` | Writes a log line as `vc_log` does: `level` 0 (error) to 3 (debug), `true` when written and `false` when the run's log budget dropped it; with `progress` only. | + +The realm has no `$`, `File`, `Folder`, `app`, `#include` or other part of the script runner, no file, network or +command access, and no clock: `Date.now()` is `NaN`. A run gets a filter's instruction budget (one budget for the top +level and the call, plus the budget per byte of input) and wall-clock budget, checked between slices of 1,000,000 +instructions, where Cancel stops it too; its heap is at most the interpreter's default heap and the plug-in's memory cap (512 MiB), whichever is smaller, and +an input and parameters larger than an eighth of the heap fail the run with the memory-budget error for a selection +too large to hand over. A thrown error, a limit, a missing `run`, a result that is not an object JSON can write, or an +output larger than 64 MiB fails the run, and the document and undo history stay as they were. The error names the +plug-in, its script and, for an error in the script, the line and column, for example `plug-in exceeded its +instruction budget (org.example.tint, tint.js line 3, column 5)`. + ## Performance The interpreter costs roughly 10–100× native speed per instruction. Filters handle a selection in one call, so a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 022ff2bb6c..df69c18888 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,8 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; 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) +Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written. + +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; 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). > @@ -32,8 +34,18 @@ ## Feature submission evidence +When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions, and a compilation failure clears the previous script report. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. Included files are read again when the chosen run starts. Each app queue pump processes at most one startup entry and preserves the remaining order after a failure. `crates/engine/tests/script_startup.rs` covers both modes. + +`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. + +Scripts: `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available, with a configurable, non-enumerable, non-writable descriptor. Promise instances report `[object Promise]` in engines without Symbols. Test: `promise_prototype_has_a_configurable_string_tag` in `crates/js/src/promise_tests.rs`. + History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. +Character-style edits keep manual leading overrides when Dynamic Text's Block cannot fit the frame. When Block can fit the frame, its generated leading follows the edited style. A regression in `crates/engine/src/cmd/typecmd/block_tests.rs` covers a frame whose inset leaves no room. + +Script appearance and geometry setters reject objects on locked artboards. Assigning the current opacity remains allowed when it changes no graph styling. Position, size and stacking-order setters also reject objects excluded by selection filtering, including locked guide paths. `crates/engine/src/tests/script_dom.rs` covers refused edits, unchanged documents and undo history, and editing a guide after unlocking it. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. @@ -87,6 +99,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | +| 2026-11-21 | minor | G12: Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | @@ -332,7 +345,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -654,6 +667,7 @@ since 2026-10-01. - **Rotating ruler guides (part of #2418):** unlocked guides can be moved, modified and deleted ([user guide, Use guides](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=90)). A selected ruler guide rotates with the Rotate tool, Object › Transform › Rotate… (Copy included) and Transform Again, also with no object selected, in one undo step, and transforms with the selected objects under Scale, Reflect and Shear. Each guide transforms as the line Release Guides makes of it, about the center of that line and the objects' box together. By VectorCraft's own rule, a guide that ends up vertical or horizontal stays a ruler guide, and one at any other angle becomes a guide path along its line, which saves and opens as other guide paths do. `rotating_a_ruler_guide_makes_an_angled_guide`, `ruler_guides_turned_square_stay_ruler_guides`, `a_ruler_guide_rotates_with_the_selected_art` in `crates/engine/src/tests/menucmds.rs`; `the_rotate_tool_turns_a_selected_ruler_guide_alone` in `crates/tools/src/xform/transform.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. +- **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step; beside a moved corner anchor a line stays a line and an arc an arc, and at a moved smooth anchor the handles stay in line and the segments bend to meet), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `a_release_past_the_drag_distance_moves_the_anchor`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. - **Recolor with Preset asks for a library first:** Edit › Edit Colors › Recolor with Preset (1, 2 and 3 Color Job, Color Library) opens a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens (, "Quickly reduce colors using a preset"). A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch, so editing the swatch recolors the art. Tests `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. @@ -1036,6 +1050,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export As: GIF and PNG-8 Options offer the same Transparency Dither and Amount as Save for Web, disabled while Transparency is off, and `document.export` takes `transparencyDither` and `transparencyDitherAmount` for GIF and PNG-8 with the same values, refusing an unknown method or an amount that is not a whole number from 0 to 100; other formats do not read the keys, and the warnings name them. Using Save for Web's keys in the other export is VectorCraft's own rule. `crates/engine/src/cmd/fileio/tests_palette.rs` (`palette_exports_take_the_transparency_dither`), `crates/ui-egui/src/dialogs/tests_raster_formats.rs` (`palette_options_send_the_transparency_dither`, `palette_options_name_the_transparency_dither_controls`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. + - Save for Web: the Save Color Table command writes the GIF or PNG-8 table the preview shows to an `.act` file, and the Load Color Table command reads one back as the table's fixed Custom palette, so the image is written with the loaded colors; reloaded colors come back as plain, unlocked entries ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Both run through the engine and MCP; the dialog's color table menu does not list them yet. The file follows the published color table layout (https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/): 256 RGB entries in file order, then the number of colors and the transparent entry. These rules are VectorCraft's own: Save always writes the 772-byte form, with zero bytes after the colors used and 65535 when there is no transparent entry; Load takes the 768-byte and 772-byte forms, leaves the transparent entry out of the palette, sets Colors to the file's count, clears the table's other edits and its sort, and sets Web Snap to 0 (`document.exportForWeb.saveColorTable`, `webExport.loadColorTable`). Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). @@ -1055,6 +1070,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. @@ -1073,10 +1089,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` starts with a line holding the run's name in square brackets, such as `[main.jsx]`, then writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `localizedName`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: `localizedName` gives the same decoded name as `displayName`, without looking up a name the system shows in another language; a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants (it fails when the grants file is there but cannot be read) and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that `script.grants` cannot read shows that error in the section when Preferences opens, a grants file that is not well formed or is over 4 MiB makes Revoke show its error, and the file is left as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/tests/safe_mode.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Plug-in run notices: a filter or plug-in command's output may report a `notice`, which needs no permission; once the output is applied, `plugin.run` and the command return it and the status bar shows it as `Plug-in “name”: notice`, escaped, cut at 200 characters and never translated, and a run that fails or is refused shows none. VectorCraft's own API and limits. Tests: `objects::tests::notice_is_escaped_capped_and_checked` in `vectorcraft-plugins`, `a_filter_s_notice_is_returned_once_its_output_is_applied` and `a_plugin_command_returns_its_run_s_notice` in `vectorcraft-engine`, `plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. @@ -1111,15 +1129,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. It reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Classes and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,267 of 1,287 runs of 668 tests pass. Of the 20 others, 16 do not parse because the tests also use classes, and 4 expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. @@ -1550,6 +1569,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). @@ -1864,7 +1884,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: reshaping or scaling the path fits the text again; one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off, threading the type or Release Type on a Path keeps the drawn sizes; SVG, EPS, legacy `.ai` and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). - Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, a leading change (the Character and Properties panels, the Type tool's Alt+arrow leading steps, a character style, Text Tweaker) sets Line Gap to the new leading less the size of the first character changed, limited to -1,296 to 1,296 pt, Reset Panel keeps Line Gap, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). Dynamic Text on point type (Type › Dynamic Text, the Contextual Task Bar; [Adjust formatting and resize text](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/adjust-formatting-and-resize-text-with-dynamic-text.html) applies it to existing text) turns it into area type with Block on. VectorCraft's own rules: the frame is as wide as the widest line with its indents, so that line keeps its size and place across the page, and it grows in depth to hold every fitted line (`crates/engine/src/cmd/typecmd/block_tests.rs`). Type › Dynamic Text Presets › Circle, Arch and Bow (`type.dynamicTextPreset`) put point type or type on a path on a circular, upward-curving or downward-curving path with Dynamic Text on, with the text's position against the path (above, center, below) and its direction ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). VectorCraft's own rules: the circle is as wide as the text and the text starts at its bottom; Arch and Bow are a 120° arc whose chord is as wide as the text; above, center and below are Align to Path's Descender, Center and Ascender (`crates/engine/src/tests/dynamic_text.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. @@ -2056,7 +2076,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images overprint:** Overprint Fill (`object.setOverprint {fill: true}`) on a colorized grayscale or 1-bit image makes its color print over the inks below instead of knocking them out. Raster art has an overprint setting in the [scripting reference](https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/). `attributes.info` reports it, native files keep it, and Overprint Preview, Separations Preview and printed separations show it; they show an image knocking out when it has a visible effect of its own other than a warp or a geometry effect (a drop shadow, a glow, a raster effect or a color adjustment), or a fill or stroke with an opacity above 0 that draws a shape with Convert to Shape or Outline Object and does not overprint. Printed separations also show an image knocking out when its pixels do not take its color (a preview of its file), and separate those pixels as they are. PDF and EPS export leave raster effects out and still overprint such an image. PDF export draws the image with an overprinting graphics state and writes a gray or process color as an image of only the process inks it puts down (ISO 32000-1 §8.6.7). EPS export turns overprinting on for it and writes a gray or process color in only the process inks it puts down (one DeviceN image at Level 3, one Separation image per ink at Level 2). A legacy `.ai` file writes it with the image mask's fill overprint, and reading one takes the fill overprint in force at the image mask. White follows the rule for white fills: with Discard White Overprint on, PDF export, EPS export, the previews and printed separations show a white color knocking out, but a tint above 0% of a spot swatch whose color is white keeps overprinting, as it does for fills and strokes in PDF export, the previews and printed separations ([White overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html)). Taking the color off with a fill of None also turns its overprint off. Edit › Edit Colors › Overprint Black and Print Ink Fixes' Remove White Overprint reach a colorized image's color as its fill. Evidence: engine `tests::colorize::overprint_fill_makes_a_colorized_images_color_overprint`, `tests::colorize::overprint_black_and_print_fixes_reach_a_colorized_images_color`, `tests::colorize::flattening_without_preserve_overprints_drops_a_colorized_images_overprint`, `tests::colorize::flattening_without_preserve_overprints_clears_an_uncolored_images_overprint`, doc `overprint::tests::a_white_colorized_image_knocks_out_under_discard_white`, `overprint::tests::a_white_spot_ink_keeps_overprinting_under_discard_white`, `overprint::tests::a_colorized_image_darkens_unless_its_rows_draw_an_effect`, `overprint::tests::a_colorized_image_darkens_past_a_row_with_no_opacity`, `overprint::tests::a_colorized_image_with_a_node_effect_keeps_knocking_out`, `overprint::tests::overprint_black_takes_a_black_colorized_image`, `overprint::tests::clearing_overprints_clears_the_flag_of_an_image_without_a_color`, render `tests::colorize::an_overprinting_colorized_image_keeps_the_ink_below_in_the_previews`, pdf `tests::colorize::an_overprinting_colorized_image_sets_overprint`, `tests::colorize::separations_hide_an_overprinting_image_on_plates_without_its_ink`, `tests::colorize::separations_show_an_overprinting_image_whose_pixels_refuse_its_color`, `tests::colorize::a_white_spot_ink_image_overprints_with_discard_white_overprint`, eps `tests::an_overprinting_colorized_image_writes_only_its_process_inks`, `tests::a_white_spot_ink_colorized_image_overprints_with_discard_white_overprint`, `tests::a_plate_leaves_out_an_overprinting_image_without_its_ink`, `tests::an_overprinting_colorized_image_at_the_page_limit_keeps_all_its_inks_or_none`, `legacy_ai::tests::a_colorized_image_mask_takes_the_fill_overprint_in_force`, doc `live::tests::mesh_warp_image_pieces_keep_an_overprinting_color`, effects `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`. - **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. - - **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. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. 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. + - **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 at or below the one asked for, and the C row keeps the chroma asked for. At lightness 0 and 100 % the color is exactly black and white. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. 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. - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **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. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged. @@ -2105,6 +2125,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. + - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), which ships unmodified: the measured paper, solids and overprints, a tone curve fitted to each ink's ramp, and a smoothed Lab correction lattice fitted to all 1,617 patches. The models reproduce the patches within a mean ΔE2000 of 0.04 (largest 0.37), and patches left out of the fit within 0.15 to 0.17 (largest 1.67). A PDF/X output intent made with one embeds the profile; with the condition identifier left blank it names `FOGRA51` or `FOGRA52`, in the `http://www.color.org` registry unless the settings give a registry, and an identifier the settings give is written as given. The 300% ink limit and black generation are VectorCraft's own values. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. @@ -2156,6 +2177,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, gradient stops at an opacity of 0 that mix only with other stops at an opacity of 0 or only over stretches with no width, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. A stop at an opacity of 0 next to a stop above it stays listed, since the stretch between them is drawn in its color. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients`, `spot_color_objects_skip_clear_fills_and_strokes`, `spot_color_objects_skip_spot_stops_only_in_clear_stretches` and `drawn_stops_follow_the_sampled_stretches` (vectorcraft-engine). Document Info's Brushes, Spot Color Objects, Pattern Objects and Gradient Objects categories leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0, their characters' paints and colorized images included. With Selection Only an object selected inside such a group or layer is left out too, and Objects still counts every object as before. This is VectorCraft's own rule. Test: `cmd::docinfo::tests::info_skips_paints_on_hidden_and_clear_objects_and_their_members` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. + Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`) is kept in memory for the session, not stored. With it on, `document.info` counts the selected objects and their descendants; with it off, the counts stay for the whole document. With no artwork selected it shows `(No artwork selected)` instead of those counts; artboards the Artboard tool has selected still show under Document. Tests: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state` (vectorcraft-ui-egui). Document Info's Document category lists the document's transparency settings, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes: File › Document Setup's grid size, grid colors, Simulate Colored Paper and flattener preset (`document.info`'s `document.transparency`). While the Artboard tool is the current tool, it also lists the width, height and position of each artboard that tool has selected, as the same page describes for the selected artboard (`document.selectedArtboards`). Listing every selected artboard, measuring the position at the top-left corner from the ruler origin of the tool's active artboard, and naming two custom grid colors by their values are VectorCraft's own rules. The panel shows the values in the interface language, and the report keeps them in English. Tests: `cmd::docinfo::tests::info_lists_the_transparency_settings` and `info_lists_the_artboards_the_artboard_tool_selected` (vectorcraft-engine), `panels::doc_info::tests::document_shows_transparency_and_the_artboard_tools_selection` (vectorcraft-ui-egui). Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui). Document Info shows the values it makes in the interface language too: the Units, the Raster Effects resolution, each font's file, substitution and embedding permission (or that it is built in or missing), each image's size and linked file, each Repeat object's kind with its instances, rows and columns in the language's plural forms, and gradients named by their kind. Font, face, file, swatch and other names stay as they are, a gradient swatch named like a kind included, and `document.info`, Save… and Package's report keep the English values (`document.unitId`, `fontDetails`, `imageObjects`, `gradientObjects` `kinds`). Showing these values in the interface language is VectorCraft's own rule. Tests: `panels::doc_info::tests::values_follow_interface_language_and_keep_names`, `repeat_value_uses_locale_plural_forms_and_drawn_count`, `i18n::tests::document_info_values_are_in_complete_catalogs` (vectorcraft-ui-egui), `cmd::docinfo::tests::info_exposes_structured_font_details_without_changing_english_rows`, `info_exposes_ordered_images_and_unit_id` and `gradient_kinds_tell_kinds_from_swatch_names` (vectorcraft-engine). @@ -2756,6 +2778,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **The warning of a preview applied when a command ends a drag:** a preview that Real-time Drawing off left unapplied, and that Undo, Clear History or another command applies before it runs, keeps its warning: the command's result carries it as `previewWarning`, and as `warning` when the command has none of its own, and the status bar shows it, as releasing the drag shows it. Typing kept as its own step when a tool's drag begins, or when Cmd lends the Selection tool, shows its applied preview's warning in the status bar too. Regressions: `settling_a_deferred_preview_keeps_its_warning` and `settling_typing_for_a_tool_shows_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `settled_warnings_join_the_result` in `crates/engine/src/session/execute.rs`. Scores and hours unchanged. - **Typing kept when a dialog or a panel previews, with Real-time Drawing off:** a dialog's Preview, a panel's live slider, the Effect Gallery's preview, the font menus' preview, a paint for the characters the Type tool selected and an inline graphic inserted while typing first apply the typing that Real-time Drawing off left unapplied, as an undo step of its own, and the status bar shows that typing's preview warning. The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic then act on the characters the Type tool selected in the typed text. When the typing can't be kept, the status bar shows the error and the dialog's preview does not start. Regressions: `settling_typing_for_a_dialog_returns_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `ending_deferred_typing_for_another_edit_keeps_the_typing` in `crates/engine/src/tests/textedit.rs`, `inserting_while_deferred_typing_keeps_the_typing` in `crates/engine/src/tests/inline.rs`, `settled_typing_tests` in `crates/ui-egui/src/dialogs/form.rs`, `stack_preview_keeps_typing_in_progress` in `crates/ui-egui/src/dialogs/effect_gallery.rs`. Scores and hours unchanged. +- **JavaScript filter plug-ins (G17, #2193):** an object filter may be a `.vcplugin` manifest with `"runtime": "js"` and the `.js` file its `script` names, installed with `plugin.install {path}` or from the plug-in folder. Each run gets a new interpreter with the filter's instruction, time and memory budgets and no file, command or clock access; `run(input, params)` returns the output a module would, checked the same way, and the document changes as one undo step. A manifest without `script`, an unsafe script name or a script over 8 MiB is refused before the script is read. Regressions: `crates/plugins/src/js.rs`, `crates/plugins/src/registry.rs`, `crates/engine/tests/plugin_js.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Painted effects refuse gradient stop plates without a spot link (G17):** a gradient stop with process `plates` in a painted live effect's fill or stroke must link to a spot swatch of the document itself; a stop with no link, a `null` link or only the gradient's own `swatch` refuses the whole result, and so does a link to a process swatch or Registration, also when a cached result's swatch stops being a spot swatch. `lastError` names the stop's `plates`. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/effect.rs` (`cached_painted_plates_refuse_after_spot_becomes_process`). Scores and hours unchanged. @@ -3044,7 +3067,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Type Tools add-on: Text Tweaker (2026-11-03) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. ## Type Tools add-on: Release Type on a Path (2026-11-05) @@ -3195,7 +3218,7 @@ The public page orders Retype's matching fonts by how close each is to the text' ## Retype panel (2026-11-18) -The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches, installed fonts not yet loaded and images remain. +The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches and images remain; installed fonts not yet loaded are compared too (see Retype installed fonts). ## Retype tracking (2026-11-19) @@ -3205,6 +3228,10 @@ The identify-fonts page has the Retype panel list ten matching fonts ordered by #4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. +## Retype installed fonts (2026-11-20) + +The identify-fonts page names the fonts on the device as one of the sources Retype suggests fonts from ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). `type.retype` now compares the shapes no loaded font matches with the installed fonts that are not loaded yet, and `type.retypeFonts` (the Retype panel's list) ranks those fonts with the loaded ones. Each file is read for the search and released, smallest first; only a font whose glyphs match a shape is loaded. `type.retype` matches the installed fonts as it matches the loaded ones: with its `tolerance`, near matches count, and a compound path of several glyphs is split for them too. The search leaves out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn, a cancel stops it between files, a plain shape (one contour of up to four straight edges) does not start it, and `installed: false` turns it off. In the app, Type › Retype and Find Matching Fonts run the search on a thread of their own, with a progress window and Cancel (`retype.cancelSearch`), and change nothing when the document or its selection changed meanwhile. These limits and rules are VectorCraft's own. Tested with installed copies of a bundled font in a folder of their own (found and loaded, no match, plain shapes, stopping once every shape matches, a near match and a split compound path, the three limits, a cancel before and between files, the panel's ranking, a search made away from its command) in `crates/engine/src/cmd/retype_installed_tests.rs`, `crates/engine/src/cmd/retype_fonts_tests.rs`, `crates/text/src/fontdb/installed.rs` and `crates/text/src/retype.rs`, and in the app (the background search, Cancel, a changed selection, the panel's list) in `crates/ui-egui/src/tests/retype_runs.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). @@ -3272,6 +3299,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | +| 2026-11-21 | minor | G12: Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 1524c1ed0e..1587d7f8f1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -60,7 +60,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 142666cec2..ae4692aba0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -210,7 +210,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`). Not yet: Ctrl+scroll for the arc size | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | @@ -498,6 +498,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | +| Control bar and Properties panel: Corners link and pop-up for the picked corners (part of #1232) | done | the link opens the corner kind, the radius (blank while the picked corners differ) and the Relative or Absolute rounding; each change sets the picked corners of every selected path in one `object.setLiveShape {items}`, one undo step | | Control bar: numeric Corner Radius for eligible selected ordinary and live corners (part of #7238, request 3 only) | done | Anchor Points visibility group; common/mixed values, general document units and multi-object edits through `object.setLiveShape`, one Undo. A partial selection containing no eligible corners contributes no target. Corner kind and relative mode are retained; existing corner-widget selection, widget visibility and maximum-radius behavior are unchanged. Requests 1/2 remain open. | | Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | @@ -523,7 +524,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | -| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches, installed fonts not yet loaded and text in images are missing (#4934) | +| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | | Comments, Version History panels | missing | cloud features (out of scope) | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test |