diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/Cargo.lock b/Cargo.lock index 55f4b2f6e7..d10a030ce5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2900,6 +2900,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -9642,6 +9643,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" diff --git a/ROADMAP.md b/ROADMAP.md index f74399f93a..8b29a40471 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. + - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index bc000f0bd6..d4d2659b3e 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -23,7 +23,10 @@ vectorcraft-text = { workspace = true } # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } craft-nightly = { workspace = true } -eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } +# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only +# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the +# shared app setup. +eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } serde_json = { workspace = true } diff --git a/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 7c40d9d133..fe7ef7a6be 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -21,11 +21,12 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; +use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; -use crate::node::{Node, NodeId, NodeKind}; +use crate::node::{LiveShape, Node, NodeId, NodeKind}; use crate::text::TextObject; // ===================================================================================== @@ -1032,6 +1033,9 @@ enum Shape { /// Paths and compound paths; `members`: the subpath count of each member when both keys are /// compound paths. Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec, Vec)> }, + /// Two live rectangles: each step is a live rectangle whose size, transform and corner radii + /// lie between the keys', so their rounded corners stay circular arcs. + LiveRect(Box<(LiveRectParts, LiveRectParts)>), /// Text, symbols and images: their transforms interpolate. Placed, /// Anything else: a copy of the nearer key moved and scaled into the interpolated box. @@ -1046,6 +1050,43 @@ pub struct Lerp { shape: Shape, } +/// A live rectangle's size, transform, corner kinds and corner radii in document units. +#[derive(Clone, Debug)] +struct LiveRectParts { + w: f64, + h: f64, + radii: [f64; 4], + kinds: [CornerKind; 4], + xf: Affine, +} + +/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws. +fn live_rect(s: &LiveShape) -> Option { + let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None }; + let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative); + let corners = vectorcraft_geom::corners::path_corners(&base); + let mut drawn = [0.0; 4]; + for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) { + if let Some(d) = drawn.get_mut(c.index) { + *d = r; + } + } + Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf }) +} + +/// The parts of `a` and `b` when steps between them can be live rectangles: both are live +/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear +/// left in their transforms, so each step only moves and resizes and its corners stay circular. +fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> { + let (x, y) = (live_rect(a)?, live_rect(b)?); + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + // A rotation or a reflection: unit columns at right angles. + let rigid = + |c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9; + (x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y)) +} + /// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has. fn collapsed(n: &Node, c: Point) -> Node { let mut x = n.clone(); @@ -1083,6 +1124,12 @@ impl Lerp { | (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. }) | (NodeKind::Image(_), NodeKind::Image(_)) | (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed, + // A clicked start point asks for anchors to be paired; the path route does that. + (NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. }) + if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) => + { + Shape::LiveRect(Box::new(parts)) + } _ => match (node_path(a), node_path(b)) { (Some((pa, ra, ma)), Some((pb, rb, mb))) => { Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) } @@ -1145,6 +1192,28 @@ impl Lerp { } } } + Shape::LiveRect(parts) => { + let (x, y) = &**parts; + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + let live = LiveShape::Rectangle { + w: lerp_f64(x.w, y.w, t), + h: lerp_f64(x.h, y.h, t), + radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)), + kinds: x.kinds, + radii_relative: false, + xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]), + }; + let rule = match &base.kind { + NodeKind::Path { rule, .. } => *rule, + _ => FillRule::default(), + }; + let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default()); + if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind { + *r = rule; + *l = Some(Box::new(live)); + } + n + } Shape::Placed => { let mut n = base.clone(); match (&mut n.kind, &a.kind, &b.kind) { @@ -2321,6 +2390,110 @@ mod tests { assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0)); } + /// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`. + fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node { + let live = + LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) }; + let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut n.kind { + *l = Some(Box::new(live)); + } + n + } + + /// The step's live radii, after checking that every curve of its outline is a circular arc of + /// that radius about the matching corner center. + fn round_step_radii(step: &Node) -> [f64; 4] { + let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") }; + let r = radii[0]; + let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default(); + let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y)); + let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count(); + assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}"); + for seg in path.segments() { + if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg { + for u in [0.0, 0.25, 0.5, 0.75, 1.0] { + let p = c.eval(u); + let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min); + assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}"); + } + } + } + *radii + } + + /// Steps between live rectangles are live rectangles whose corner radii lie between the keys'. + #[test] + fn steps_between_rounded_rectangles_keep_round_corners() { + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 20.0).abs() < 1e-9, "{r}"); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for t in [0.25, 0.5, 0.75] { + for r in round_step_radii(&blend.at(t)) { + assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}"); + } + } + // A radius too large for its rectangle counts as the radius it draws. + let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 10.0).abs() < 1e-9, "{r}"); + } + // Keys turned differently keep the anchor-by-anchor route. + let mut turned = rounded(300.0, 200.0, 60.0, 30.0); + turned.transform(Affine::rotate(0.5), false); + assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. })); + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::rotate(30.0_f64.to_radians()), false); + b.transform(Affine::rotate(390.0_f64.to_radians()), false); + let blend = Lerp::new(&a, &b, (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let step = blend.at(0.5); + let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") }; + let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") }; + assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]); + for starts in [(Some(0), None), (None, Some(0))] { + assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. })); + } + b.transform(Affine::scale_non_uniform(-1.0, 1.0), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + for scale in [1.0, 1e-200] { + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false); + b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + } + // Keys whose corner kinds differ keep the anchor-by-anchor route. + let mut kinds = [CornerKind::Round; 4]; + kinds[2] = CornerKind::InvertedRound; + let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) }; + let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut inverted.kind { + *l = Some(Box::new(live)); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None)); + assert!(matches!(blend.shape, Shape::Path { .. })); + // The last step is the inverted key's outline. + assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds())); + // Each step keeps the fill rule of the key it is nearer. + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + if let NodeKind::Path { rule, .. } = &mut a.kind { + *rule = FillRule::EvenOdd; + } + let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let rule = |n: &Node| match &n.kind { + NodeKind::Path { rule, .. } => *rule, + _ => panic!("a path step: {n:?}"), + }; + assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd); + assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero); + } + /// A step between two distorted images has its corners between the keys' corners. #[test] fn steps_between_distorted_images_have_corners_between_theirs() { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5d849cfed2..60a7aaba29 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -5,6 +5,7 @@ //! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"` //! the objects inside them (see `appearance`). +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; @@ -115,7 +116,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +impl Session { + /// Can the Appearance panel reorder shared effects on the exact subjects it displays? + /// A generated graph design or a selection normalized to different objects has no matching row. + pub fn can_reorder_selected_effects(&self) -> bool { + let Ok(st) = self.doc() else { return false }; + let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false }; + let selected: HashSet<_> = st.selection.subjects().iter().copied().collect(); + roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id)) + } +} + +/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the +/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing. +fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option>> { + let mut seen = HashSet::with_capacity(ids.len()); + let mut appearances: Vec<&vectorcraft_doc::Appearance> = + ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::>()?; + let first = *appearances.get(anchor)?; + if source == ItemTarget::Top { + return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]); + } + let item = source.effects_item(first, "effect.move").ok()??; + appearances.swap(0, anchor); + let shared = SharedStack::of(&appearances); + let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::>>()?; + slots.swap(0, anchor); + Some(slots) +} + /// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s. fn move_effect(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.move"; @@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; let roots = edit_targets(s, p, C)?; - // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { - return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); - } + let reference = design_reference(s, p, C)?; + let d = &s.doc()?.doc; + let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) { + // An omitted item and a numbered item can use different anchors and still name the same row. + let shared = (!copy && reference.is_none()) + .then(|| { + shared_reorder_slots(d, &roots, src, src.anchor(s, &roots)) + .filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source)) + }) + .flatten(); + Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?) + } else { + None + }; // Where the effect landed in each object it moved in, in the order of `ids`. let mut landed = vec![]; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { let mut done = vec![]; - for id in &roots { + for (k, id) in roots.iter().enumerate() { let Some(n) = d.node_mut(*id) else { continue }; - let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?); + let (si, di) = match &slots { + Some(slots) => (slots[k], slots[k]), + None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?), + }; let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue }; // Taken out from the top down, so the lower positions stay valid; put back in order. let mut taken: Vec = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index b44a26e645..5724498e14 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Blend"], Some("Cmd+Alt+B"), - "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", + "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", has_doc, blend_make ), diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e2ffb44d0c..33b38e567b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -980,6 +980,8 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["View"], "Show Corner Widget"), (&["View"], "Show Live Paint Gaps"), (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Show Curvature Comb"), + (&["View"], "Hide Curvature Comb"), (&["View"], "Guides"), (&["View"], "Smart Guides"), (&["View"], "Perspective Grid"), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 9cf80039db..ee2f3fcc5d 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -63,6 +63,24 @@ pub fn specs() -> Vec { always, engine_drop ), + cmd!( + query "script.palettes", + "List Script Palettes", + [], + None, + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run; a hidden palette lists its controls as they were when it was hidden, until show() shows it again → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + always, + palettes + ), + cmd!( + query "script.palette.event", + "Script Palette Event", + [], + None, + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + always, + palette_event + ), cmd!( query "script.console", "Script Console", @@ -268,6 +286,36 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result { Ok(json!({"dropped": true, "name": name})) } +fn palettes(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.script_palettes().iter().map(script::palettes::palette_json).collect(); + Ok(json!({ + "palettes": list, + "waiting": s.script_palette_events_waiting(), + "limit": script::palettes::MAX_PALETTES, + "waitingLimit": script::palettes::MAX_WAITING, + })) +} + +fn palette_event(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.palette.event"; + let Some(id) = p.get("palette").and_then(Value::as_u64) else { + return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it")); + }; + let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; + let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; + let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo + // group or a drag in another document, which a run cannot start in. + if !s.script_frames && s.palette_run_blocked() { + return Err(EngineError::Other(script::OPEN_EDIT.to_string())); + } + let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; + if s.script_frames { + return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); + } + s.script_palette_run_waiting() +} + fn console_lines(s: &mut Session, _: &Value) -> Result { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 7f817726cc..8fe914a87f 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -151,6 +151,13 @@ impl AutomationRoots { Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) } + /// Whether these roots grant everything `other` grants: each root of `other` lies inside one of + /// these roots of the same kind. + pub(crate) fn contains(&self, other: &Self) -> bool { + let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved))); + within(&self.read, &other.read) && within(&self.write, &other.write) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -283,6 +290,42 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } + /// Whether this scope allows everything `other` allows: its roots are none, or each root of + /// `other` lies inside one of its roots of the same kind, and its script gate is none or the + /// same gate. + fn covers(&self, other: &Self) -> bool { + let gate = match (&self.1, &other.1) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (Some(_), None) => false, + }; + gate && self.roots_cover(other) + } + + /// Whether this scope's roots are none, or each root of `other` lies inside one of its roots + /// of the same kind. + fn roots_cover(&self, other: &Self) -> bool { + match (self.roots(), other.roots()) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b), + (Some(_), None) => false, + } + } + + /// Whether this scope allows everything the calling thread's scope allows + /// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so + /// work run in the calling thread's scope reaches the same files this scope reaches. + pub(crate) fn matches_current(&self) -> bool { + let current = Self::capture(); + self.covers(¤t) && current.roots_cover(self) + } + + /// Whether this scope and `other` allow the same: each covers the other, and reads are exempt + /// from the gate in both or in neither. + pub fn same(&self, other: &Self) -> bool { + self.2 == other.2 && self.covers(other) && other.covers(self) + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e1e7f5a5..31cfe000de 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; @@ -399,6 +400,9 @@ pub struct Session { pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run + /// ([`script::palettes`]). + pub(crate) script_palettes: script::palettes::Palettes, /// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and /// is not turned on when the run fails. pub(crate) overprint_after_run: bool, diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 0356db27d1..9224ab6030 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -222,13 +222,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { return Err(HostError::Type("doScript's dialogs must be true or false".into())); } - let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + // A palette's handler that a palette's `update()` runs plays the actions of the run that showed + // the palette, as the handler's own run would. + let handler = h.palette_actions.borrow(); + let actions = handler.as_deref().unwrap_or(&h.actions); + let found: Vec<&Playable> = actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); let p = match found.as_slice() { - [p] => *p, - [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [p] => (*p).clone(), + [] if !actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), }; + drop(handler); if p.steps.is_empty() { return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); } diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 3067361727..86b3030f9a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -222,6 +222,9 @@ pub(crate) struct Dialogs { approved: Cell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, + /// An answer could not reach the script, so a dialog still open when the run ends is listed + /// with the answer `"error"`. + answer_failed: Cell, records: RefCell>, record_bytes: Cell, count: Cell, @@ -247,6 +250,7 @@ impl Dialogs { on_yes: Cell::new(None), approved: Cell::new(None), failed: RefCell::default(), + answer_failed: Cell::new(false), records: RefCell::default(), record_bytes: Cell::new(0), count: Cell::new(0), @@ -295,6 +299,7 @@ impl Dialogs { self.window_waiting.set(false); if let Err(e) = realm.answer(event.data()) { *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); } Ok(()) } @@ -447,24 +452,32 @@ impl Dialogs { } /// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most - /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. + /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. The report lists the dialog + /// with the answer, or with `"error"` when the answer could not reach the script. pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool { let fits = match &answer { DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES, _ => true, }; let mut waiting = self.waiting.borrow_mut(); - let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; - self.record(d, answer.json()); - *waiting = None; + if !waiting.as_ref().is_some_and(|d| d.kind == answer.kind() && fits) { + return false; + } + let Some(d) = waiting.take() else { return false }; + drop(waiting); let on_yes = self.on_yes.take(); // A confirm the app opened returns `undefined` to the call that opened it. let data = if on_yes.is_some() { Data::Undefined } else { answer.data() }; if answer == DialogAnswer::Confirm(true) { self.approved.set(on_yes); } - if let Err(e) = realm.answer(data) { - *self.failed.borrow_mut() = Some(e); + match realm.answer(data) { + Ok(()) => self.record(&d, answer.json()), + Err(e) => { + self.record(&d, json!("error")); + *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); + } } true } @@ -493,15 +506,17 @@ impl Dialogs { self.approved.take() } - /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or + /// `"error"` when an answer could not reach the script. pub(crate) fn stopped(&self) { self.on_yes.set(None); + let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") }; if let Some(d) = self.waiting.borrow_mut().take() { - self.record(&d, json!("stop")); + self.record(&d, answer.clone()); } self.window_waiting.set(false); if let Some(showing) = self.window.borrow_mut().take() { - self.end_record(&showing, json!("stop")); + self.end_record(&showing, answer); } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0c6e087f0b..392e8c7700 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -559,23 +559,92 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. +/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or +/// layer that keeps other objects, or a compound path or group that clips one and would be left +/// with no visible path or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; + let d = &st.doc; if h.session.borrow().menu.guides_locked - && let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + && let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) { return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); } - let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - let locks = st.doc.locked_artboards(); + let refused: Vec = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let mut next: Vec<_> = d.layers.iter().collect(); + let mut nodes = Vec::new(); + while let Some(n) = next.pop() { + nodes.push(n); + next.extend(n.children().into_iter().flatten()); + } + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + for n in nodes.iter().rev() { + if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + } + // Type is laid out only inside a mask that loses a path; no other outline decides a refusal. + let mut in_mask = std::collections::HashSet::new(); + for n in &nodes { + if n.clips() + && let Some(mask) = n.children().and_then(|k| k.first()) + && affected.contains(&mask.id) + { + let mut stack = vec![mask]; + while let Some(m) = stack.pop() { + if in_mask.insert(m.id) { + stack.extend(m.children().into_iter().flatten()); + } + } + } + } + let mut geometry = std::collections::HashSet::new(); + let mut masks = Vec::new(); + for n in nodes.into_iter().rev() { + let kids = n.children().map_or(&[][..], Vec::as_slice); + // Clear removes compound paths emptied of direct members, but keeps empty groups. + if matches!(n.kind, NodeKind::Compound { .. }) + && !kids.is_empty() + && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) + { + going.insert(n.id); + } + // A clip outline takes in visible paths and the glyphs of visible type, as + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no + // outline. A list marker is a glyph too, so whitespace-only type is laid out as well. + let shape = n.visible + && match &n.kind { + NodeKind::Path { .. } => true, + NodeKind::Text(t) => { + in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + } + _ => false, + }; + // A clipping group's outline is its first member's alone. + let inner = + if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) }; + if n.visible && ((shape && !going.contains(&n.id)) || inner) { + geometry.insert(n.id); + } + if n.clips() + && let Some(mask) = kids.first() + && affected.contains(&mask.id) + && !geometry.contains(&mask.id) + && kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + && masks.len() < 20 + { + masks.push(mask.id.0); + } + } + Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -585,6 +654,12 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -1410,7 +1485,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// [`see_points`] for each path whose points the run has read, after each command, so that a /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the -/// object model's own, and their points stay valid. A document that is the one the run last looked +/// object model's own, and their points stay valid; the other Global Edit members, which take the +/// object model's edit too, are looked at as well. A document that is the one the run last looked /// at is skipped, as are its paths. The look is charged by the objects it looks at. pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> { let (keys, looked_at): (Vec<(u64, u64)>, u64) = { @@ -1420,7 +1496,8 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr let mut keys = Vec::new(); let mut looked_at = 0u64; docs.retain(|uid, before| { - let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + let state = s.documents().iter().find(|d| d.uid == *uid); + let after = state.map(|st| &st.doc); if after.is_some_and(|after| Arc::ptr_eq(before, after)) { return true; } @@ -1430,16 +1507,28 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr return false; } // Editing a path in an Objects on Path group can move the other paths in the group, so - // the outermost such group is looked at in place of the path. + // the outermost such group is looked at in place of the path. While Global Edit is on, + // an edit of the selected member (also one made by moving a group that holds it) is + // given to the other members, so each of them, or the outermost Objects on Path group + // holding it, is looked at too. Subtrees the command left as they were are skipped. // Each node is paired with the node of the same id under the same parent now, so that no // node is searched for through the whole document. let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { Some(item) => { - let group = before - .ancestry(item.id) - .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))); - let id = group.unwrap_or(item.id); - node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))).into_iter().collect() + let root = |id: NodeId| { + before + .ancestry(id) + .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))) + .unwrap_or(id) + }; + let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten(); + let mut roots = std::collections::HashSet::new(); + std::iter::once(item.id) + .chain(members) + .map(root) + .filter(|id| roots.insert(*id)) + .filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id))))) + .collect() } None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at), }; @@ -1481,6 +1570,8 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr false } }); + keys.sort_unstable(); + keys.dedup(); (keys, looked_at) }; if looked_at > 0 { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 85c01d6a74..11db9b859e 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -220,6 +220,9 @@ pub(crate) struct Setup { pub script: Option, /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. pub source: String, + /// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's + /// handler, the one of the script that showed the palette. + pub own: Option, /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). pub data_dir: Option, /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source @@ -309,7 +312,7 @@ impl Disk { let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); let web = cfg!(target_arch = "wasm32"); let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); - let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes())); let script = script.map(|p| (p, own.clone())); let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); @@ -381,6 +384,11 @@ impl Disk { } } + /// The SHA-256 the run's grants are for ([`Setup::own`]). + pub(crate) fn own(&self) -> &str { + &self.own + } + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. fn saw(&mut self, hash: String) -> bool { if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a33e6c732b..d5dbbc1bb8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,6 +48,11 @@ //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. //! +//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and +//! whose events run as runs of their own in that engine, one at a time once no run is going. A run +//! of that engine whose own code calls `update()` handles the waiting events inside the run +//! instead. A palette closes with its engine. +//! //! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run //! only after the run's changes are kept, for the frontend to send once the person approves them //! ([`printing`]). @@ -58,10 +63,12 @@ pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod palettes; pub mod printing; pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use palettes::{ScriptPalette, Waiting}; pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; @@ -111,6 +118,9 @@ pub const MAX_LOG_LINES: usize = 10_000; pub const MAX_LOG_BYTES: usize = 4 << 20; /// The most bytes of `args` given to one run, as JSON. pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app +/// draws the window (VectorCraft's own value, about one frame). +const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); /// The `vc.run` calls one slice makes before the interface draws again. const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. @@ -848,6 +858,8 @@ struct Host { started: Option, /// The time since [`Host::started`] at which a `$.sleep` ends. wake_at: Cell>, + /// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice. + drawn_at: Cell>, /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). can_wait: Rc>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). @@ -856,6 +868,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The named engine the run is in; `None` for a new realm. + engine: Option, + /// The script file the run was read from; `None` for a script given as text. + file: Option, + /// For the run of a palette's handler, the palette's id and the event, until the palette takes + /// it ([`palettes`]). + palette_event: RefCell>, /// The run's state of the script object model (`app`). dom: dom::State, /// While a slice runs: the documents the interface has open ([`World::docs`] of the run's @@ -863,6 +882,10 @@ struct Host { interface_docs: RefCell>, /// The actions `app.doScript` can play. actions: Vec, + /// While a palette's `update()` gives a waiting event to its palette, the actions of the run + /// that showed that palette, which `app.doScript` plays in place of [`Host::actions`]. A + /// palette's `paletteTake` sets them and its `palettePending` clears them. + palette_actions: RefCell>>, /// The index of each open document's active artboard as the run starts, by document uid. The /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, @@ -1098,6 +1121,24 @@ impl Host { Ok(()) } + /// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is + /// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. → + /// whether it does, and the palette's controls are to be given now. Without a clock (the web + /// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run + /// ends for another reason. + fn update_drawn(&self) -> bool { + if !self.framed { + return false; + } + let Some(now) = self.elapsed() else { return false }; + if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) { + return false; + } + self.drawn_at.set(Some(now)); + self.pause.set(true); + true + } + /// The time left of a `$.sleep`, or none when the run is not asleep. fn asleep(&self) -> Option { let wake = self.wake_at.get()?; @@ -1977,6 +2018,7 @@ impl Session { match gone { Some(engine) => { drop(engine); + self.keep_engines_palettes(); Ok(()) } None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), @@ -2264,6 +2306,7 @@ impl Session { lost }); drop(lost); + self.keep_engines_palettes(); // The job's working copy went with it, with the documents the run opened. self.plugin_events_script_ended(false); raise_ids(self); @@ -2285,6 +2328,10 @@ impl Session { /// 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<()> { + #[cfg(test)] + if SETTLE_FAILS.with(Cell::get) { + return Err(EngineError::Other("the open edit could not be settled".into())); + } self.finish_tool_edit_later()?; if self.active().is_some() { cmd::settle_interaction(self)?; @@ -2297,6 +2344,7 @@ impl Session { /// Begins a run of `request`. → the run's name. pub(crate) fn script_start(&mut self, request: Request) -> Result { + let palette_event = self.script_palettes.starting.take(); self.settle_for_script()?; // In a build where a fault ends the program, every unsaved document has a copy first. if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { @@ -2418,6 +2466,7 @@ impl Session { script: request.file.clone(), // The text with its included files, so a changed included file asks again. source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + own: palette_event.as_ref().and_then(|q| q.grants.clone()), data_dir: self.script_data_dir.clone(), engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { let m = m.borrow(); @@ -2435,13 +2484,18 @@ impl Session { kept_maps, started: clock(), wake_at: Cell::new(None), + drawn_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + engine: engine.clone(), + file: request.file.clone(), + palette_event: RefCell::new(palette_event), dom: dom::State::new(self.documents(), heap_bytes), interface_docs: RefCell::new(Vec::new()), actions: request.actions, + palette_actions: RefCell::new(None), active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, run_docs: RefCell::new( @@ -2518,6 +2572,7 @@ impl Session { // error drops a kept one. let keep = !fresh && e.kind != RunErrorKind::Internal; self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); + self.keep_engines_palettes(); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -2666,6 +2721,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.keep_engines_palettes(); self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); @@ -2812,7 +2868,7 @@ impl Session { } } -const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; @@ -3007,6 +3063,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result realm.refresh_script_ui().and_then(|()| { + dom::flush(host).map_err(end_flush_error)?; + Ok(Progress::Done(v)) + }), + // A failed run keeps its globals, so its palettes show what it left too; a refresh + // that fails as well (the fuel is spent, a stop) leaves them as they were, and the + // run's error keeps its place. + Err(e) if named && e.kind != RunErrorKind::Internal => { + realm.refresh_script_ui_after_error(); + Err(e) + } + r => r, + } }) }); if let Some(started) = started { @@ -3099,6 +3178,8 @@ thread_local! { pub(crate) static TEST_RESULT_BYTES: Cell> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: makes settling the open edits before a run fail. + pub(crate) static SETTLE_FAILS: Cell = const { Cell::new(false) }; /// Tests: makes the next command a member runs past the script fence panic before it runs. pub(crate) static PANIC_WHILE_UNFENCED: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs new file mode 100644 index 0000000000..a63a712918 --- /dev/null +++ b/crates/engine/src/script/palettes.rs @@ -0,0 +1,536 @@ +//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a +//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and +//! changes while the person goes on working. +//! +//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script +//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once. +//! Each click, change or close the person gives a palette waits here, and then runs as a run of its +//! own in the palette's engine, which takes the mutation lease like any other run: one event at a +//! time, oldest first, each starting only once no run is going. A new click, change or close replaces +//! the most recent waiting event of the same kind for the same control or palette only when that +//! event has the same file access scope. Otherwise the new event waits at the end of the line. A click or +//! close replaces an event only after its palette's last waiting change. A palette's `update()` in +//! a run of the palette's engine takes the events that wait for that engine's palettes and runs their +//! handlers in that run instead ([`Palettes::take_for`]). +//! +//! A palette closes when its script calls `close()` or the person closes it, unless `onClose` +//! returns `false`; when its engine is dropped or ends with an internal error; and with the session. +//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that +//! handler's run like any failed run, with its report, and leaves the palette open. +//! +//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`]. + +use std::collections::VecDeque; + +use serde_json::{Map, Value, json}; + +use super::actions::Playable; +use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::{EngineError, Result, Session}; + +/// The most palettes a session keeps, shown or hidden. +pub const MAX_PALETTES: usize = 16; +/// The most events that wait for a run, for every palette together. +pub const MAX_WAITING: usize = 64; + +/// A palette a run showed. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptPalette { + /// Its number in the session, which no other palette of the session has had. + pub id: u64, + /// The named engine its handlers run in. + pub engine: String, + /// The script file of the run that first showed it, whose folder its handlers read in; `None` + /// for a script given as text. + pub file: Option, + /// Its controls, as the last `show()`, `add()` or handler left them. + pub dialog: ScriptUiDialog, + pub visible: bool, + /// The SHA-256 the file grants of the script that first showed it are kept for, which its + /// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the + /// showing run's alone, as for any later run of the script. + pub(crate) grants: String, +} + +/// What became of an event given to a palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waiting { + /// It waits at the end of the line. + Added, + /// It took the place of a waiting event for the same control. + Merged, +} + +/// An event given to a palette, waiting for its run or handed to it. +#[derive(Clone, Debug)] +pub(crate) struct Queued { + pub(crate) palette: u64, + pub(crate) event: UiEvent, + /// The id of the control of a click or a change ([`super::scriptui::UiNode::id`]), by which the + /// event finds its control again when a run adds or removes controls before it; `None` for a + /// close. + pub(crate) element: Option, + /// For a list's change, the list's items as the palette showed them when the event was given and + /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list + /// still has. + pub(crate) list: Option<(Vec, f64)>, + /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which + /// the run takes as its own ([`super::files::Setup::own`]). + pub(crate) grants: Option, + /// The file access scope of the request that gave the event, which its run keeps, narrowed to + /// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]). + pub(crate) scope: crate::file_access::ScopeHandle, + /// The number of the request that gave the event last: an event that takes the place of a + /// waiting one takes a new number. + pub(crate) ticket: u64, +} + +/// The palettes of a session, and the events that wait for a run. +#[derive(Debug, Default)] +pub(crate) struct Palettes { + list: Vec, + /// The actions `app.doScript` plays in each palette's handlers, by palette id: those of the + /// run that first showed the palette. + actions: Vec<(u64, Vec)>, + waiting: VecDeque, + last_id: u64, + /// The number the last event given took ([`Queued::ticket`]). + last_ticket: u64, + /// The number of the event whose run started last. + started_ticket: Option, + /// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its + /// run takes inside it (`update()`). + taken_inline: Option>, + /// The event the run that starts next handles ([`Session::script_palette_start`]). + pub(crate) starting: Option, +} + +/// Does `event`, for the control whose id is `element`, share the waiting `q`'s place in line: a +/// click on the same control, a change of it, or a close? +fn same_place(q: &Queued, event: &UiEvent, element: Option) -> bool { + let same_kind = matches!( + (&q.event, event), + (UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close) + ); + same_kind && q.element == element +} + +/// The control of a click or a change. +fn control_of(event: &mut UiEvent) -> Option<&mut usize> { + match event { + UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c), + UiEvent::Close => None, + } +} + +impl Palettes { + fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> { + self.list.iter_mut().find(|p| p.id == id && p.engine == engine) + } + + /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`, whose + /// handlers take the showing run's `actions`. → its id. + pub(crate) fn show( + &mut self, + id: Option, + engine: &str, + (file, grants, actions): (Option, String, &[Playable]), + dialog: ScriptUiDialog, + ) -> std::result::Result { + if let Some(p) = id.and_then(|id| self.find(id, engine)) { + p.dialog = dialog; + p.visible = true; + return Ok(p.id); + } + if self.list.len() >= MAX_PALETTES { + return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first")); + } + self.last_id += 1; + self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants }); + if !actions.is_empty() { + self.actions.push((self.last_id, actions.to_vec())); + } + Ok(self.last_id) + } + + /// The palette's controls as a handler or `add()` left them. → false when it is closed. + pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.dialog = dialog; + true + } + + /// `hide()`. → false when it is closed. + pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.visible = false; + self.waiting.retain(|q| q.palette != id); + true + } + + /// `close()`, once `onClose` allowed it. → false when it was closed already. + pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { + let before = self.list.len(); + self.list.retain(|p| !(p.id == id && p.engine == engine)); + let closed = self.list.len() != before; + if closed { + self.waiting.retain(|q| q.palette != id); + self.actions.retain(|(p, _)| *p != id); + } + closed + } + + /// Closes the palettes of the engines `keep` does not keep, with their waiting events. + fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) { + self.list.retain(|p| keep(&p.engine)); + let open: Vec = self.list.iter().map(|p| p.id).collect(); + self.waiting.retain(|q| open.contains(&q.palette)); + self.actions.retain(|(p, _)| open.contains(p)); + } + + /// Puts `event` for the shown palette `id` in line, once it is checked against the palette. + fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result { + let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) }; + if !p.visible { + return Err(format!("the script palette {id} is hidden")); + } + let mut event = scriptui::check_event(&p.dialog, event)?; + let list = match &event { + UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), + _ => None, + }; + let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); + let scope = crate::file_access::ScopeHandle::capture(); + // Only the most recent event for the same place can merge, in the same file access scope. + // A click or close merges only after its palette's last waiting change, and a change only + // after its palette's last waiting click or close. + let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close); + let after = self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..)) == closing).map_or(0, |at| at + 1); + let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element)); + let ticket = self.last_ticket.wrapping_add(1); + if let Some(slot) = at.filter(|q| q.scope.same(&scope)) { + slot.event = event; + slot.list = list; + slot.ticket = ticket; + self.last_ticket = ticket; + return Ok(Waiting::Merged); + } + if self.waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); + } + self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket }); + self.last_ticket = ticket; + Ok(Waiting::Added) + } + + /// The oldest waiting event whose palette is still shown, given to its control in the palette + /// as the runs since left it, and that palette. An event whose control the palette + /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for + /// example because a handler disabled or hid it, is dropped. + fn next(&mut self) -> Option<(ScriptPalette, Queued)> { + while let Some(q) = self.waiting.pop_front() { + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + None + } + + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other + /// engines' palettes keep their places in line. Events whose file access scopes do not cover + /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest + /// first, preserving the order within each scope. + fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { + loop { + let at = self.oldest_for(engine)?; + let q = self.waiting.remove(at)?; + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + } + + /// The taken event `q` given to its control in its palette, and that palette, or `None` when it + /// is dropped ([`Palettes::next`]). + fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; + if let Some(c) = control_of(&mut q.event) { + *c = p.dialog.index_of(q.element?)?; + } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?; + } else { + q.event = scriptui::check_event(&p.dialog, q.event).ok()?; + } + Some((p.clone(), q)) + } + + /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` + /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]), with + /// the actions its handlers play: those of the run that first showed its palette. + pub(crate) fn take_for(&mut self, engine: &str) -> Option<(Queued, Vec)> { + let q = self.next_of(engine).map(|(_, q)| q)?; + if let Some(taken) = self.taken_inline.as_mut() { + taken.push(q.ticket); + } + let actions = self.actions.iter().find(|(id, _)| *id == q.palette).map(|(_, a)| a.clone()).unwrap_or_default(); + Some((q, actions)) + } + + /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] + /// would then check and take. + pub(crate) fn waits_for(&self, engine: &str) -> bool { + self.oldest_for(engine).is_some() + } + + /// The place of the oldest event for a palette of `engine`, when a palette's `update()` in a + /// run of that engine may take it ([`Palettes::next_of`]): the run reaches the same files the + /// event's scope reaches, so the handler runs with neither more nor less access than in a run + /// of its own. Any other event waits for a run of its own. + fn oldest_for(&self, engine: &str) -> Option { + self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + } +} + +/// `name` in a `#targetengine` line, quoted with a quote it does not hold. +fn engine_line(name: &str) -> String { + let quote = if name.contains('"') { '\'' } else { '"' }; + format!("#targetengine {quote}{name}{quote}") +} + +/// The source of a palette's handler run: its engine, and the call that hands the event to the +/// palette, which takes it from the run's host. +fn handler_source(engine: &str) -> String { + format!("{}\nthis[{:?}]();\n", engine_line(engine), vectorcraft_js::scriptui::PALETTE_EVENT_GLOBAL) +} + +/// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s +/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's +/// number, or a list's item index or null). +pub(crate) fn parse_event( + dialog: &ScriptUiDialog, + event: &str, + control: Option<&Value>, + value: Option<&Value>, +) -> std::result::Result { + if event == "close" { + if control.is_some() || value.is_some() { + return Err("a close takes no `control` and no `value`".into()); + } + return Ok(UiEvent::Close); + } + let id = match control { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?, + _ => return Err("`control` must be a control's index, name or text".into()), + }; + let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + let event = match (event, value) { + ("click", None) => UiEvent::Click(id), + ("click", Some(_)) => return Err("a click takes no `value`".into()), + ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + ("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), + ("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)), + ("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()), + _ => return Err("`event` must be click, change or close".into()), + }; + scriptui::check_event(dialog, event) +} + +/// A palette as `script.palettes` lists it. +pub(crate) fn palette_json(p: &ScriptPalette) -> Value { + let controls: Vec = p + .dialog + .nodes + .iter() + .enumerate() + .skip(1) + .map(|(i, n)| { + let mut c = Map::new(); + c.insert("index".into(), json!(i)); + c.insert("kind".into(), json!(kind_id(n.kind))); + c.insert("name".into(), json!(n.name)); + c.insert("text".into(), json!(n.text)); + c.insert("enabled".into(), json!(n.enabled)); + c.insert("visible".into(), json!(n.visible)); + match n.kind { + UiKind::CheckBox | UiKind::RadioButton => { + c.insert("value".into(), json!(n.checked)); + } + UiKind::Slider | UiKind::ProgressBar => { + c.insert("value".into(), json!(n.value)); + } + UiKind::DropDownList | UiKind::ListBox => { + c.insert("items".into(), json!(n.items)); + c.insert("selection".into(), json!(n.selection)); + } + _ => {} + } + Value::Object(c) + }) + .collect(); + json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls}) +} + +fn kind_id(kind: UiKind) -> &'static str { + match kind { + UiKind::Dialog => "palette", + UiKind::Group => "group", + UiKind::Panel => "panel", + UiKind::StaticText => "statictext", + UiKind::EditText => "edittext", + UiKind::Button => "button", + UiKind::CheckBox => "checkbox", + UiKind::RadioButton => "radiobutton", + UiKind::DropDownList => "dropdownlist", + UiKind::ListBox => "listbox", + UiKind::Slider => "slider", + UiKind::ProgressBar => "progressbar", + } +} + +impl Session { + /// The palettes the named engines' runs showed and have not closed, shown or hidden, in the + /// order they were first shown. + pub fn script_palettes(&self) -> &[ScriptPalette] { + &self.script_palettes.list + } + + /// How many palette events wait for a run. + pub fn script_palette_events_waiting(&self) -> usize { + self.script_palettes.waiting.len() + } + + /// The changes that wait for a run, as (palette id, the id of the control they change). + pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { + self.script_palettes + .waiting + .iter() + .filter(|q| matches!(q.event, UiEvent::Change(..))) + .filter_map(|q| q.element.map(|e| (q.palette, e))) + .collect() + } + + /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event + /// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag + /// in a document other than the active one. A drag in the active document is not counted, + /// since starting the run settles it. + pub fn script_palette_can_start(&self) -> bool { + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked() + } + + /// Whether an open edit keeps a palette event's run from starting: an undo group, the + /// session's or a document's, or a drag in a document other than the active one (starting the + /// run settles a drag in the active one). + pub(crate) fn palette_run_blocked(&self) -> bool { + let active = self.active().map(|d| d.uid); + self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active) + } + + /// Whether an undo group is open, the session's or a document's, which a run cannot start in. + pub(crate) fn undo_group_open(&self) -> bool { + self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some()) + } + + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going + /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it + /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. + pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result { + self.script_palettes.wait(id, event) + } + + /// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a + /// run is going or no event waits; otherwise the run's name, or the error that ended it before + /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. + pub fn script_palette_start(&mut self) -> Option> { + if self.script_running() || self.script_palettes.waiting.is_empty() { + return None; + } + // An event waits while a drag or an undo group is open, which a run cannot start in. + if let Err(e) = self.settle_for_script() { + return Some(Err(e)); + } + let (palette, mut queued) = self.script_palettes.next()?; + self.script_palettes.started_ticket = Some(queued.ticket); + queued.grants = Some(palette.grants.clone()); + let title = palette.dialog.title(); + let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; + let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let actions = self.script_palettes.actions.iter().find(|(id, _)| *id == palette.id).map(|(_, a)| a.clone()).unwrap_or_default(); + let request = super::Request { + name, + name_given: true, + file: palette.file.clone(), + checked_real: None, + source: handler_source(&palette.engine), + args: Map::new(), + fuel: super::DEFAULT_FUEL, + locale, + answers: Vec::new(), + module: false, + actions, + }; + // The run takes the scope of the request that gave the event, within the scope in force now. + let scope = queued.scope.clone().within_current(); + self.script_palettes.starting = Some(queued); + let r = scope.run(|| self.script_start(request)); + self.script_palettes.starting = None; + Some(r) + } + + /// Closes the palettes whose engine the session no longer keeps. + pub(crate) fn keep_engines_palettes(&mut self) { + let names: Vec = self.script_engines().into_iter().map(|(name, ..)| name).collect(); + self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e)); + } + + /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, + /// in their order in line. → the report of the event just given, wherever it waited, or an + /// error when it was dropped without a run. An event whose run could not begin, for example + /// because the recovery copies could not be saved, ends this, and the events after it keep + /// waiting: with its error, or with the given event's result when that one has run. An open + /// edit that cannot be settled ends this with its error, and the given event no longer waits. + pub(crate) fn script_palette_run_waiting(&mut self) -> Result { + let want = self.script_palettes.last_ticket; + let mut mine = None; + loop { + if !self.script_running() + && !self.script_palettes.waiting.is_empty() + && let Err(e) = self.settle_for_script() + { + // A caller that gives the event again then does not give it twice. + self.script_palettes.waiting.retain(|q| q.ticket != want); + return mine.unwrap_or(Err(e)); + } + let Some(started) = self.script_palette_start() else { break }; + // A later event whose run cannot begin leaves the given event's result as it is. + if let Err(e) = started { + return mine.unwrap_or(Err(e)); + } + self.script_palettes.taken_inline = Some(Vec::new()); + let r = self.script_run_to_end(); + // A run of the same engine can take the event while it runs (`update()`): its report + // is then the event's. + let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want)); + if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) { + mine = Some(r); + } + } + mine.unwrap_or_else(|| { + Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into())) + }) + } +} diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 4226196239..04216386bc 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -1,6 +1,9 @@ //! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run //! gives when it shows one, checked and laid out here before the app draws it, and the events the -//! person or `script.run`'s `answers` give back. +//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described +//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions +//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here +//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other. //! //! A description lists the dialog first and each control after the container that holds it. It is //! refused with an error thrown at `show()` when a control's container comes after it or is not a @@ -36,6 +39,7 @@ use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; use super::Host; +use super::palettes::Queued; /// The largest size or place, in pixels, of a dialog or a control in it. pub const MAX_EXTENT: f32 = 8192.0; @@ -143,6 +147,9 @@ pub struct UiNode { /// list from one that holds the same texts again. pub items_revision: u64, pub selection: Option, + /// How many times a list's items were added or removed, which a palette's waiting change of + /// the list is checked against. + pub revision: f64, pub multiline: bool, pub readonly: bool, pub rect: UiRect, @@ -208,6 +215,12 @@ impl ScriptUiDialog { }; by(true).or_else(|| by(false)) } + + /// The index in [`Self::nodes`] of the control whose id ([`UiNode::id`]) is `id`, if the dialog + /// has one. + pub fn index_of(&self, id: u64) -> Option { + self.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0) + } } /// A value a control takes in a change. @@ -516,6 +529,7 @@ pub fn parse(d: &Data) -> Result { items, items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64), selection, + revision: number(field(f, "revision")).unwrap_or(0.0), multiline: flag("multiline"), readonly: flag("readonly"), rect: UiRect::default(), @@ -709,7 +723,132 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result /// Adds `Window` to the realm, for the run `link` holds. pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { - realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) + realm.define_script_ui(vec![ + ("open".into(), function(link, open)), + ("wait".into(), function(link, wait)), + ("end".into(), function(link, end)), + ("palette".into(), function(link, palette)), + ("paletteShow".into(), function(link, palette_show)), + ("paletteUpdate".into(), function(link, palette_update)), + ("paletteHide".into(), function(link, palette_hide)), + ("paletteClose".into(), function(link, palette_close)), + ("paletteEvent".into(), function(link, palette_event)), + ("paletteTake".into(), function(link, palette_take)), + ("palettePending".into(), function(link, palette_pending)), + ("paletteDraw".into(), function(link, palette_draw)), + ]) +} + +/// The error of `new Window("palette")` in a run without a named engine. +pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script"; + +/// The named engine of the run, for a palette. +fn palette_engine(host: &Host) -> Result<&str, HostError> { + host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into())) +} + +/// A palette's id as a script holds it: a whole number from 1, or none. +fn palette_id(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64), + _ => None, + } +} + +/// `new Window("palette")`: refused in a run without a named engine. +fn palette(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Undefined) +} + +/// A palette's `show()`, with its description and its id (none the first time). → its id. +fn palette_show(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + let id = palette_id(args.get(1)); + let grants = host.disk.borrow().own().to_string(); + let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants, &host.actions), dialog); + shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) +} + +/// The palette `id`'s controls as a handler, `add()` or `update()` left them. +fn palette_update(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + if let Some(id) = palette_id(args.get(1)) { + host.session.borrow_mut().script_palettes.update(id, &engine, dialog); + } + Ok(Data::Undefined) +} + +/// A palette's `update()` in the script's own code asks whether the app draws the palette now +/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's +/// controls through `paletteUpdate`. +fn palette_draw(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Bool(host.update_drawn())) +} + +/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine, +/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. Until the next +/// `palettePending`, `app.doScript` plays the actions of the run that showed the event's palette. +fn palette_take(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let taken = host.session.borrow_mut().script_palettes.take_for(&engine); + let (data, actions) = match taken { + Some((queued, actions)) => (event_data(queued), Some(actions)), + None => (Data::Null, None), + }; + *host.palette_actions.borrow_mut() = actions; + Ok(data) +} + +/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks +/// before it gives the palettes' controls and takes the event with `paletteTake`, and once more +/// after the event's handlers end. `app.doScript` then plays the run's own actions again. +fn palette_pending(host: &Host, _: &[Data]) -> Result { + *host.palette_actions.borrow_mut() = None; + let engine = palette_engine(host)?.to_string(); + Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine))) +} + +fn palette_hide(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.hide(id, &engine); + } + Ok(Data::Undefined) +} + +fn palette_close(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.close(id, &engine); + } + Ok(Data::Undefined) +} + +/// The event a palette handler's run is for, once: `{palette, event, id, value, element, items}`, +/// as `show()` takes a dialog's event with the palette's id added, the id of a click's or a +/// change's control (`element`, [`UiNode::id`]), which the run finds the control by, and for a +/// list's change the items the palette showed; `null` for any other run, and after the first call. +fn palette_event(host: &Host, _: &[Data]) -> Result { + let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; + Ok(event_data(queued)) +} + +/// The waiting event `queued` as a script takes it ([`palette_event`]). +fn event_data(queued: Queued) -> Data { + let Data::Object(mut fields) = queued.event.data() else { return Data::Null }; + fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if let Some(element) = queued.element { + fields.push(("element".into(), Data::Number(element as f64))); + } + if let Some((items, revision)) = queued.list { + fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); + fields.push(("revision".into(), Data::Number(revision))); + } + Data::Object(fields) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1a3a285725..367334a008 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -198,6 +198,7 @@ impl Session { script_high_water: Default::default(), script_style_trail: Default::default(), script_in_run: false, + script_palettes: Default::default(), overprint_after_run: false, script_unfenced: None, script_printers: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e880f436f6..0e6269d511 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -195,6 +195,7 @@ mod script_folder; mod script_include; mod script_io; mod script_modules; +mod script_palettes; mod script_print; mod script_raster_capture; mod script_run; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index b967e6e3ed..8cb96c6a8a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() { assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects"); } +#[test] +fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + for (id, item) in [(a, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect})); + } + } + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone()); + let before = appearances(&s); + for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] { + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + let moved = run(&mut s, "effect.move", params); + assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor"); + assert_eq!(moved["index"], json!(0)); + for (appearance, item) in appearances(&s).iter().zip([1, 2]) { + let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["distort.roughen", "distort.twist"]); + assert!(appearance.effects_at(Some(0)).unwrap().is_empty()); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(appearances(&s), before); + } + + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + for destination in [0, 2] { + assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err()); + assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list"); + } + + run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"})); + let before = appearances(&s); + assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row"); +} + /// `effect.move`'s reply names where the effect landed in the object whose row the active item is /// (the first selected object), also when that object paints above the others. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index a5a082058e..d1b5197012 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -171,6 +171,38 @@ fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Divide refuses a cutting line with more segments than its planar map takes, instead of +/// dividing the square without the line, and leaves the document and the undo history as they were. +#[test] +fn divide_refuses_cutting_lines_past_the_segment_cap() { + let mut s = session(); + let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap()); + // A zigzag across the square with one segment more than the cap, the square's four sides aside. + let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3; + s.edit("zigzag", |d, sel| { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((-10.0, 40.0)); + for i in 1..=segments { + let x = -10.0 + 120.0 * i as f64 / segments as f64; + bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 })); + } + // Unfilled, so the zigzag stays open and cuts. + let n = d.node_mut(cutter).unwrap(); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + sel.set([cutter, base]); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select fewer paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..0ebb346fe7 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -200,6 +200,30 @@ fn prompt_cancel_returns_null() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true])); } +/// A prompt's answer that the engine's nearly full heap cannot hold ends the run, and the report +/// lists the prompt with the answer `"error"`, not the text that did not reach the script. +#[test] +fn a_prompt_answer_that_cannot_reach_the_script_is_listed_as_an_error() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = one_doc(); + let filled = headless( + &mut s, + "#targetengine full\nvar head = null, c = 'x';\nwhile (c.length < 4096) c += c;\nfor (var i = 0; ; i++) head = {s: c + i, n: head};", + json!([]), + ); + framed(&mut s, "#targetengine full\nvar a = prompt('Name', '');"); + let waited = pump(&mut s).is_none(); + let answered = s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES)))); + let ended = pump(&mut s); + let report = s.script_report(); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert!(filled.unwrap_err().to_string().contains("Heap")); + assert!(waited && answered); + assert!(ended.unwrap().is_err(), "the answer did not fit in the heap"); + assert_eq!(report.unwrap()["dialogs"][0]["answer"], "error"); +} + #[test] fn dialog_loop_stops_or_exhausts() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 8f71d64e62..a982c82575 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3684,6 +3684,377 @@ fn scoped_remove_all_refuses_a_clipping_compound_path() { assert_eq!(undo_steps(&s), steps); } +/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths. +const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + +/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the +/// group keeps other art, and deletes nothing, as the scoped collections do. +#[test] +fn document_path_items_remove_all_refuses_a_clipping_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + // The script catches the error and counts the paths before the run ends, so the run's own + // rollback cannot hide a deletion. + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&a.0.to_string()), "{out:?}"); + assert!(!e.contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping +/// other art, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&compound.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would +/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still +/// clips, and the document's `pathItems.removeAll()` deletes every path. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would +/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does +/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer +/// mask too. +#[test] +fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap(); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + for (g, first) in [(nested, b), (outer, mask)] { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != first); + *clip = true; + } + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// A numbered paragraph whose text is a single space still draws its number, which clips, so the +/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() { + use vectorcraft_doc::text::{NumberStyle, ParaList}; + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + let mut styles = tx.paragraph_styles(); + styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic))); + tx.set_paragraph_styles(styles); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a +/// clipping group whose paths would leave only such type makes the document's +/// `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes +/// the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + assert!(d.node(empty).unwrap().children().unwrap().is_empty()); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!( + out[0], + json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0)) + ); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() { + for compound in [false, true] { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap(); + let sibling = s.active().unwrap().doc.parent_of(b).unwrap(); + let layer = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(layer).unwrap().clips()); + assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a)); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + if compound { + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(sibling).is_none()); + assert!(!d.node(layer).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } else { + assert_eq!( + out[0], + json!(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", + a.0 + )) + ); + assert_eq!(out[1], json!(3)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + } +} + /// A path that leaves a compound path for a layer is drawn as it was: it takes the compound /// path's paint and pixel alignment, as Release Compound Path gives them. #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 49795b667e..1078f7078e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1624,6 +1624,71 @@ fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_change assert_eq!(art(&s), before); } +/// Global Edit gives an edit of one member to the others, so a point read of another member before +/// the edit is stale afterwards, even when an undo puts the member back. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() { + let (mut s, a, _) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the edit"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + +/// Moving a group that holds the selected Global Edit member moves the other members too, so a +/// point read of another member before the move is stale afterwards. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + app.activeDocument.groupItems[0].translate(10, 0);\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the move"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + app.activeDocument.groupItems[0].translate(10, 0); app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs new file mode 100644 index 0000000000..cf873ec324 --- /dev/null +++ b/crates/engine/src/tests/script_palettes.rs @@ -0,0 +1,1018 @@ +//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run +//! and run one at a time after it, the events that take a waiting one's place, `close()` and the +//! close box, the engine's end, and the limits. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; +use crate::script::scriptui::PALETTE_NEEDS_ENGINE; +use crate::script::{DialogAnswer, SETTLE_FAILS, TEST_ELAPSED, UiEvent, Waiting}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "p.js"})) +} + +/// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() || s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Runs `source` in the app to its end. +fn run_in_app(s: &mut Session, source: &str) -> Value { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + pump(s).expect("the run ended").unwrap() +} + +/// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and +/// adds a rectangle, and a field (control 2). +const TOOLS: &str = "#targetengine tools\n\ + var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + var field = p.add('edittext', undefined, ''); \ + go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ + field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; + +fn only_palette(s: &Session) -> u64 { + let list = s.script_palettes(); + assert_eq!(list.len(), 1, "{list:?}"); + list[0].id +} + +#[test] +fn show_returns_at_once_and_the_palette_stays_after_the_run() { + let mut s = one_doc(); + let r = run(&mut s, TOOLS).unwrap(); + assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); + let id = only_palette(&s); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["engine"], "tools"); + assert_eq!(listed["palettes"][0]["title"], "Tools"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); + assert_eq!(changed["log"], json!(["change abc"])); +} + +#[test] +fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["done"]), "update() in the handler does not throw"); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); +} + +#[test] +fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ + for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); + for _ in 0..100 { + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + if value(&s) > 0.0 { + break; + } + } + let first = value(&s); + assert!(first > 0.0); + TEST_ELAPSED.set(Some(Duration::from_millis(16))); + assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); + let second = value(&s); + assert!(second > first, "the palette shows the second update()"); + assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); + assert!(value(&s) > second); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["canceled"]), "{report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ + var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ + stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ + other.onClick = function () { log.push('other'); }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_in_a_handler_does_not_pause_the_run() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); + assert_eq!(report["log"], json!(["done"])); + TEST_ELAPSED.set(None); +} + +#[test] +fn many_update_calls_within_one_interval_give_the_controls_once() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + let report = run_in_app( + &mut s, + "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ + var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ + p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", + ); + let calls = report["hostCalls"].as_u64().unwrap(); + assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); + let bar = s.script_palettes()[0].dialog.nodes[2].value; + assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); + TEST_ELAPSED.set(None); +} + +#[test] +fn a_later_run_in_the_engine_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); + assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); +} + +#[test] +fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { + let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("picked")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let data = base.join("picked/data.txt"); + std::fs::write(&data, "hello").unwrap(); + let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); + let main = base.join("main/main.jsx"); + let source = format!( + "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ + var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ + b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" + ); + std::fs::write(&main, source).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + break; + } + assert!(s.script_pump().is_none(), "the run waits at its file dialog"); + } + let picked = data.to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["hello"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn update_takes_eligible_events_past_deferred_events_in_scope_order() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine eligible\nvar p = new Window('palette'); var stopped = false; \ + var a = p.add('button', undefined, 'A'); var b = p.add('button', undefined, 'B'); \ + var c = p.add('button', undefined, 'C'); var cancel = p.add('button', undefined, 'Cancel'); \ + a.onClick = function () { vc.log('a'); }; b.onClick = function () { vc.log('b'); }; \ + c.onClick = function () { vc.log('c'); }; cancel.onClick = function () { stopped = true; vc.log('cancel'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for control in 1..=4 { + let queued = if control % 2 == 1 { + crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(control))) + } else { + crate::file_access::unconfined(|| s.script_palette_event(id, UiEvent::Click(control))) + }; + assert_eq!(queued, Ok(Waiting::Added)); + } + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine eligible\nwhile (!stopped) p.update(); vc.log('stopped');")); + assert_eq!(report["log"], json!(["b", "cancel", "stopped"])); + assert_eq!(s.script_palette_events_waiting(), 2); + for expected in ["a", "c"] { + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([expected])); + }); + } + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_change_does_not_take_the_place_of_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + crate::file_access::unconfined(|| { + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, change("y")), Ok(Waiting::Added), "the confined change keeps its own place"); + }); + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine merge\np.update();")); + assert_eq!(report["log"], json!(["click", "change y"]), "the click stays before the later change of its scope"); + assert_eq!(s.script_palette_events_waiting(), 1); +} + +#[test] +fn a_change_does_not_merge_past_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + t.onChange = function () { vc.log('change ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::unconfined(|| s.script_palette_event(id, change("y"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("z"))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + crate::file_access::unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + assert_eq!(logs, [json!(["change x"]), json!(["change y"]), json!(["change z"])]); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_does_not_take_a_place_ahead_of_a_change_that_waits_after_it() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine ahead\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Text("y".into()))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added), "the click waits after the change"); + let report = run_in_app(&mut s, "#targetengine ahead\np.update();"); + assert_eq!(report["log"], json!(["click ", "change y", "click y"])); +} + +#[test] +fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { + use crate::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(1), UiEvent::Close] { + for confined_change in [false, true] { + let mut s = one_doc(); + run_in_app(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('close'); return false; }};")); + let id = only_palette(&s); + unconfined(|| assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added))); + let change = UiEvent::Change(2, crate::script::UiValue::Text("typed".into())); + let queued = if confined_change { + confine(Some(&roots), || s.script_palette_event(id, change)) + } else { + unconfined(|| s.script_palette_event(id, change)) + }; + assert_eq!(queued, Ok(Waiting::Added)); + unconfined(|| { + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Merged)); + }); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + let expected = if matches!(closing, UiEvent::Close) { + [json!(["close"]), json!(["change typed"]), json!(["close"])] + } else { + [json!(["click 1"]), json!(["change typed"]), json!(["click 2"])] + }; + assert_eq!(logs, expected); + } + } +} + +#[test] +fn update_takes_only_events_whose_roots_grant_what_the_run_s_roots_grant() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine contain\nvar p = new Window('palette'); var b = p.add('button', undefined, 'B'); \ + b.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let id = only_palette(&s); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let inner = base.join(format!("vc-script-palette-contain-{}", std::process::id())); + std::fs::create_dir_all(&inner).unwrap(); + let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&same), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["clicked", "after"]), "the same roots made again: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0); + // A run whose roots lie inside the event's roots would run the handler with less access than + // the event was given: the event waits for a run of its own. + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&narrow), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["after"]), "roots inside the event's roots: {report}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::confine(Some(&wide), || { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["clicked"])); + }); + let _ = std::fs::remove_dir(inner); +} + +#[test] +fn a_handler_keeps_the_file_access_scope_of_the_request_that_gave_its_event() { + let base = std::env::temp_dir().join(format!("vc-script-palette-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("other")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + std::fs::write(base.join("main/data.txt"), "hello").unwrap(); + let main = base.join("main/main.jsx"); + let path = serde_json::to_string(&base.join("main/data.txt").to_string_lossy()).unwrap(); + std::fs::write( + &main, + format!( + "#targetengine scope\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Read'); var stop = false; \ + b.onClick = function () {{ stop = true; vc.log(new File({path}).exists); }}; p.show();" + ), + ) + .unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("other")], &[]).unwrap().unwrap(); + // A confined request gives the click; the frame that starts its run later is not confined. + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + // An update() in a later unconfined run of the engine leaves the confined click waiting. + let r = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine scope\np.update(); vc.log(stop);")); + assert_eq!(r["log"], json!([false]), "{r}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!([false]), "the handler reads inside the roots only"); + // A click the person gives, as the desktop app's pass gives it, goes to an update() at once. + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let r = run_in_app(&mut s, "#targetengine scope\nstop = false; for (var k = 0; k < 1000 && !stop; k++) p.update(); vc.log(stop);"); + assert_eq!(r["log"].as_array().and_then(|l| l.last()), Some(&json!(true)), "the handler ran in the update() loop: {r}"); + }); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); +} + +#[test] +fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); + assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); +} + +#[test] +fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); + let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; + assert_eq!(run(&mut s, added).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); +} + +#[test] +fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_palette_click_during_another_run_runs_after_it() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); + assert!(pump(&mut s).is_none(), "the run waits at its confirm"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); + assert_eq!(s.script_palette_events_waiting(), 1); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn closing_a_palette_id_in_another_engine_keeps_that_palette_s_waiting_events() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nvar q = new Window('palette', 'Other'); q.add('button', undefined, 'B'); q.show();"); + let tools = s.script_palettes().iter().find(|p| p.engine == "tools").expect("the tools palette").id; + assert_eq!(s.script_palette_event(tools, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(!s.script_palettes.close(tools, "other"), "the other engine has no palette with that id"); + assert_eq!(s.script_palette_events_waiting(), 1, "the tools palette's click still waits"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn double_clicks_while_queued_run_once() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged)); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); + assert_eq!(s.script_palette_events_waiting(), 2); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + let mut logs = vec![]; + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); +} + +#[test] +fn a_list_change_takes_a_whole_float_as_its_item_index() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); + assert_eq!(picked["log"], json!(["b"])); + for value in [json!(0.5), json!(-1)] { + let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); + assert!(given.is_err(), "{value}"); + } +} + +#[test] +fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("undo group is open"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + s.script_copy_first = true; + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("recovery copy"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); + s.script_copy_first = false; + assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_error_and_does_not_wait() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + SETTLE_FAILS.with(|f| f.set(true)); + let r = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})); + let waiting = s.script_palette_events_waiting(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = r.unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(waiting, 0, "the refused click does not wait to run later"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); +} + +#[test] +fn a_waiting_event_whose_open_edit_cannot_be_settled_gives_the_app_that_error_and_keeps_waiting() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = started.expect("the start gives the app its error").unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click waits for a later start"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); +} + +/// A palette in the engine `acts` whose button plays the action `Box` of the set `Set`, shown by +/// a run given that action, which draws a rectangle; and how many objects the document holds. +fn acts_palette(s: &mut Session, handler: &str) -> (u64, fn(&Session) -> usize) { + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = format!( + "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () {{ {handler} }}; p.show();" + ); + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + fn objects(s: &Session) -> usize { + s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() + } + (only_palette(s), objects) +} + +#[test] +fn a_handler_that_update_runs_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "app.doScript('Box', 'Set'); vc.log('played');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + // A later run of the engine, given no actions, takes the click in its update(). + let log = + run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"].clone(); + assert_eq!(log, json!(["played", "there is no action set “Set”"]), "the run's own call plays the run's own actions"); + assert_eq!(objects(&s), before + 1, "the handler's action drew its rectangle"); +} + +#[test] +fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "throw new Error('broken');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let log = run( + &mut s, + "#targetengine acts\ntry { p.update(); } catch (e) { vc.log(e.message); } \ + try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }", + ) + .unwrap()["log"] + .clone(); + assert_eq!(log, json!(["broken", "there is no action set “Set”"])); + assert_eq!(objects(&s), before); +} + +#[test] +fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { + let mut s = one_doc(); + let (id, _) = acts_palette(&mut s, "started = true; for (;;) {}"); + // The getter records what it plays only once the handler has started, so a read before the + // click is taken does not count. + run( + &mut s, + "#targetengine acts\nvar started = false; var after = []; Object.defineProperty(p, 'text', {get: function () { \ + var played; try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } \ + if (started) { after.push(played); } return 'P'; }});", + ) + .unwrap(); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(run(&mut s, "#targetengine acts\nstarted = false; after = []; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(after.join(' '));").unwrap()["log"].clone(); + let after = log[0].as_str().unwrap_or_default(); + assert!(!after.is_empty(), "the palette is refreshed after the handler hit its limit: {log}"); + assert!(after.split(' ').all(|p| p == "own"), "the refresh after the limit plays the run's own actions, not the palette's: {log}"); +} + +#[test] +fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { app.doScript('Box', 'Set'); vc.log('played'); }; p.show();"; + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + let id = only_palette(&s); + let objects = |s: &Session| s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + let before = objects(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["played"])); + assert_eq!(objects(&s), before + 1, "the action drew its rectangle"); +} + +#[test] +fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("b")), Ok(Waiting::Added), "the text typed after the click waits after it"); + assert_eq!(s.script_palette_event(id, text("c")), Ok(Waiting::Merged), "changes with no click between them still merge"); + let log = s.script_palette_run_waiting().unwrap()["log"].clone(); + assert_eq!(log, json!(["change c"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_point_change_a_palette_getter_makes_after_the_run_is_kept() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine points\nvar armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, 4]; } return 'P'; }}); \ + p.show();", + ) + .unwrap(); + let before = format!("{:?}", s.documents()[0].doc.layers); + run(&mut s, "#targetengine points\narmed = true;").unwrap(); + assert_ne!(format!("{:?}", s.documents()[0].doc.layers), before, "the getter's point change was written"); + let anchor = run(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor);").unwrap()["log"].clone(); + assert_eq!(anchor, json!([[3, 4]])); +} + +#[test] +fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine fields\nvar p = new Window('palette'); var one = p.add('edittext', undefined, ''); \ + var two = p.add('edittext', undefined, ''); one.onChange = function () { vc.log('change ' + one.text); }; \ + two.onChange = function () { vc.log('other ' + two.text); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let text = |c: usize, t: &str| UiEvent::Change(c, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text(1, "a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text(2, "q")), Ok(Waiting::Added)); + // The new change takes the place of the first field's change, ahead of the second field's. + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": "z"})).unwrap(); + assert_eq!(changed["log"], json!(["change z"]), "the report is the given change's, not the last run's"); + assert_eq!(s.script_palette_events_waiting(), 0, "the second field's change ran too"); + let texts = run(&mut s, "#targetengine fields\nvc.log(one.text + ' ' + two.text);").unwrap()["log"].clone(); + assert_eq!(texts, json!(["z q"])); +} + +#[test] +fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { + let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let first = base.join("first.jsx"); + std::fs::write( + &first, + "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", + ) + .unwrap(); + let second = base.join("second.jsx"); + std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); + let mut s = one_doc(); + for file in [&first, &second] { + s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); + } + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("handler"), "{e}"); + let report = s.script_report().unwrap(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_palette_from_a_script_without_a_named_engine_is_refused() { + let mut s = one_doc(); + for source in ["", "#targetengine main\n"] { + let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); + assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); + } + assert!(s.script_palettes().is_empty()); +} + +#[test] +fn close_fires_on_close_and_frees_the_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); + let id = only_palette(&s); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert_eq!(closed["log"], json!(["closing"])); + assert!(s.script_palettes().is_empty(), "the close box freed the palette"); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); + + run(&mut s, TOOLS).unwrap(); + let r = + run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); + run(&mut s, "#targetengine tools\np.close();").unwrap(); + assert!(s.script_palettes().is_empty(), "close() freed the palette"); +} + +#[test] +fn update_on_a_removed_group_throws_an_error_the_script_catches_and_keeps_the_engine() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var g = p.add('group'); p.show(); p.remove(g); \ + try { g.update(); } catch (e) { vc.log(e.message); } vc.log('after');", + ) + .unwrap(); + assert_eq!(r["log"], json!(["update: the control was removed from its dialog", "after"]), "{r}"); + assert_eq!(s.script_palettes().len(), 1, "the engine and its palette stay"); +} + +#[test] +fn a_palette_still_takes_events_after_the_script_replaces_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} Window = function () {{}};")).unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + run(&mut s, "#targetengine tools\nWindow = 5;").unwrap(); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert!(closed["ok"].as_bool().unwrap_or(false), "{closed}"); + assert!(s.script_palettes().is_empty(), "the close box reached the palette"); +} + +#[test] +fn closing_a_palette_whose_visible_is_read_only_still_closes_it() { + let mut s = one_doc(); + let r = run( + &mut s, + &format!( + "{TOOLS} Object.defineProperty(p, 'visible', {{value: true, writable: false}}); try {{ p.close(); }} catch (e) {{ vc.log(e.name); }}" + ), + ) + .unwrap(); + assert!(s.script_palettes().is_empty(), "the host closed the palette: {r}"); +} + +#[test] +fn dropping_the_engine_closes_its_palettes() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); + let id = s.script_palettes()[0].id; + s.script_palette_event(id, UiEvent::Click(1)).unwrap(); + s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); + let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); + assert_eq!(left, ["other"]); + assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); + assert!(s.script_palette_start().is_none()); +} + +#[test] +fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { + let mut s = one_doc(); + let before = s.documents()[0].history.undo.len(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let art = format!("{:?}", s.documents()[0].doc.layers); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("broken"), "{e}"); + assert_eq!(format!("{:?}", s.documents()[0].doc.layers), art, "the failed handler's rectangle was rolled back"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler adds no undo step"); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_dialog_in_a_handler_throws_in_the_app() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ + try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(only_palette(&s), id, "the palette stays open"); +} + +#[test] +fn palettes_and_waiting_events_have_limits() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", + ) + .unwrap(); + assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); + s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); + assert!(s.script_palettes().is_empty()); + + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + for c in 1..=MAX_WAITING { + assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); + } + let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); + assert!(e.contains("this one was not kept"), "{e}"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b833c5d07f..1b959de54d 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -62,9 +62,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit › /// Copy does. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), - ("Window.", "alert confirm length prompt prototype"), - ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"), + ("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"), + ("Window.", "__vcPaletteEvent alert confirm length prompt prototype"), + ("%vcPaletteEvent.", "length"), + ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show update"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 09f7531ff1..26a4dd9522 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -22,4 +22,4 @@ mod pixels; pub(crate) use filters::Stream; #[cfg(test)] -pub(crate) use ops::measured; +pub(crate) use ops::{max_data, measured, with_data_limit}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index cada27219a..7f3d37e043 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,4 +1,4 @@ -use super::ops::MAX_DATA; +use super::ops::max_data; use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; use craft_stream_codecs::CcittParams; @@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { out.extend(std::iter::repeat_n(b, 257 - usize::from(n))); } } - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } } @@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { /// zlib data inflated, and how many bytes of `raw` it took. fn flate(raw: &[u8]) -> Res<(Vec, usize)> { let mut z = flate2::Decompress::new(true); - let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA)); + let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data())); loop { let before = (z.total_in(), z.total_out()); if out.capacity() - out.len() < 64 * 1024 { @@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { } let input = raw.get(z.total_in() as usize..).unwrap_or_default(); let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } match status { @@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { let mut out = vec![]; let used = lzw_into(raw, &mut |bytes| { out.extend_from_slice(bytes); - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } Ok(()) @@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an -/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. +/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused. fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); - let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); + let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX); if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c27dc3c3c6..8e8036a373 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -6,7 +6,38 @@ use super::{ }; /// Most bytes one filter or image reads. -pub(super) const MAX_DATA: usize = 1 << 28; +const MAX_DATA: usize = 1 << 28; + +#[cfg(test)] +thread_local! { + /// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it). + static DATA_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_DATA) }; +} + +/// The most bytes one filter or image reads: [`MAX_DATA`]. +#[cfg(not(test))] +pub(super) const fn max_data() -> usize { + MAX_DATA +} + +/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread. +#[cfg(test)] +pub(crate) fn max_data() -> usize { + DATA_LIMIT.get() +} + +/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_data_limit(limit: usize, f: impl FnOnce() -> R) -> R { + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + DATA_LIMIT.set(self.0); + } + } + let _restore = Restore(DATA_LIMIT.replace(limit)); + f() +} /// Decoded bytes the measuring of an image's data left out charges one operation for. A program's /// budget grows by 64 operations for each byte of it, so the data of one image compressed up to @@ -410,7 +441,7 @@ impl Interp<'_> { Stream::Buf { data, pos: 0, rgb } } p @ Obj::Array { .. } => { - let raw = self.gather(&p, MAX_DATA)?; + let raw = self.gather(&p, max_data())?; let (data, _, rgb) = decode(&spec, &raw)?; self.charge_decoded(data.len())?; Stream::Buf { data, pos: 0, rgb } @@ -600,7 +631,7 @@ impl Interp<'_> { if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { return Ok(None); } - let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) }; self.alloc(kept)?; // The compressed data: what the filters before the last one decode, or the file itself. let compressed = if head.is_empty() { @@ -618,7 +649,7 @@ impl Interp<'_> { }; let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); // Past the image's data and as much again the data is not an image's: it stops there. - let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let most = row.saturating_mul(s.h).saturating_add(max_data()); let mut sink = |mut chunk: &[u8]| -> Res { while !chunk.is_empty() { let (r, off) = (seen / row.max(1), seen % row.max(1)); @@ -829,7 +860,7 @@ impl Interp<'_> { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); // What is read: an image past the pixel cap is reduced from the samples read. - charged = total.min(MAX_DATA); + charged = total.min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) @@ -838,7 +869,7 @@ impl Interp<'_> { stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h).min(MAX_DATA); + charged = row.saturating_mul(image.h).min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) @@ -1020,7 +1051,7 @@ impl Interp<'_> { // skipped), while one within the pixel cap whose samples are still too much data // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane // is refused). - let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else { if step > 1 { return Ok(self.leave_out(&s)); } diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 8d883a0bff..396afc7d69 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -17,6 +17,39 @@ use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; /// Most operations one file may run, whatever its length. const MAX_OPS: u64 = 50_000_000; + +#[cfg(test)] +thread_local! { + /// The most operations one file may run on this thread, whatever its length ([`MAX_OPS`] unless + /// a test lowered it). + static OPS_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_OPS) }; +} + +/// The most operations one file may run, whatever its length: [`MAX_OPS`]. +#[cfg(not(test))] +const fn max_ops() -> u64 { + MAX_OPS +} + +/// The most operations one file may run, whatever its length: [`OPS_LIMIT`] of this thread. +#[cfg(test)] +pub(crate) fn max_ops() -> u64 { + OPS_LIMIT.get() +} + +/// Runs `f` with [`max_ops`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_ops_limit(limit: u64, f: impl FnOnce() -> R) -> R { + struct Restore(u64); + impl Drop for Restore { + fn drop(&mut self) { + OPS_LIMIT.set(self.0); + } + } + let _restore = Restore(OPS_LIMIT.replace(limit)); + f() +} + /// More operations a file may run for each byte of its program: a large file that draws a lot /// runs proportionally more, and stays bounded by its length. const OPS_PER_BYTE: u64 = 64; @@ -228,7 +261,7 @@ impl<'a> Interp<'a> { resources, depth: 0, ops: 0, - max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)), + max_ops: max_ops().saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)), allocated: 0, seed: 1, saves: vec![], diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 63793ff690..e77aa421c5 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,9 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; -use crate::import::data::measured; +use crate::import::data::{max_data, measured, with_data_limit}; use crate::import::graphics::{GState, Out, tilings_compared}; -use crate::import::interp::Interp; +use crate::import::interp::{Interp, max_ops, with_ops_limit}; use crate::import::obj::Obj; use crate::import::{Dsc, import}; use crate::{EpsOptions, Level, Preview, Raster}; @@ -1282,11 +1282,16 @@ fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { } /// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and -/// how many decoded bytes the measuring of images' data left out decoded. +/// how many decoded bytes the measuring of images' data left out decoded. The reading thread +/// reads with this thread's data and operation limits ([`with_data_limit`], [`with_ops_limit`]). fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok()); + let (data, ops) = (max_data(), max_ops()); + std::thread::spawn(move || { + let read = with_ops_limit(ops, || with_data_limit(data, || import(&ps))); + tx.send((read, tilings_compared(), measured())).ok() + }); let (read, compared, measured) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); (read.unwrap(), compared, measured) diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 2324de4eb4..897c126302 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -686,11 +686,15 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader /// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is -/// measured without keeping it. +/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses +/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run +/// lengths, without decoding it). #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 2 * LIMIT; let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; - let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + let zeros = crate::ps::deflate(&vec![0u8; DECODED]); // Predicted rows aren't decoded a row at a time: such an image is left out. let mut flate = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); @@ -699,7 +703,7 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // The same through LZW, which counts the codes up to its end-of-data code. let mut lzw = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); - lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true)); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true)); lzw.extend(format!("\n{after}").as_bytes()); // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in @@ -707,24 +711,29 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // run's length and stays off by one. let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); run_length.extend([2, 200, 200, 200]); - run_length.extend([129u8, 200].repeat((300 << 20) / 128)); + run_length.extend([129u8, 200].repeat(DECODED / 128)); run_length.push(128); run_length.extend(format!("\n{after}").as_bytes()); - for program in [ - format!( - "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ - 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" - ) - .into_bytes(), - flate, - lzw, - run_length, + for (program, measured) in [ + ( + format!( + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + 0, + ), + (flate, DECODED as u64), + (lzw, DECODED as u64), + (run_length, 0), ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); file.extend(&program); file.extend(b"\nshowpage\n%%EOF\n"); - let r = import(&file).unwrap(); + let before = crate::import::data::measured(); + let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap(); + assert_eq!(crate::import::data::measured() - before, measured, "{text}"); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); let o = super::tests::objects(&r.document); assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); @@ -733,18 +742,24 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { } /// Measuring the data of an image too large to hold decompresses it, and that is charged to the -/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed -/// zeros is left out and measured again each time a loop runs the stream from its start, runs out -/// of the budget after it measured the data in full more than once and at most five times. +/// operation budget: a program kept in a reusable stream, whose image over compressed zeros is +/// left out and measured again each time a loop runs the stream from its start, runs out of the +/// budget after it measured the data in full more than once and at most five times. The reader +/// holds 1 MiB here, the zeros decompress to 4 MiB, and the budget a file has whatever its length +/// pays for measuring them twice. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 4 * LIMIT; let mut program = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); - program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); + program.extend(crate::ps::deflate(&vec![0u8; DECODED])); let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); - let measured = - super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); - assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured"); + let body = format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"); + let measured = super::interp::with_ops_limit(DECODED as u64 / 8, || { + crate::import::data::with_data_limit(LIMIT, || super::tests::runs_out_of_budget_measuring(&body)) + }); + assert!((DECODED as u64 + 1..=5 * DECODED as u64).contains(&measured), "{measured} bytes measured"); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 0a56d6101c..ac6f721b85 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -219,12 +219,333 @@ pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) } +/// One tooth of a curvature comb: it starts on the curve at `at` and ends at `tip`, along the +/// curve's normal on the side away from its center of curvature, `scale` times the curvature long. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CombTooth { + pub at: Point, + pub tip: Point, + /// The first tooth of the comb, the first after a point or segment that has no tooth, or the + /// first after the curve turns back on itself (a cusp between two teeth): a line through the + /// tips starts again here. + pub start: bool, + /// The index of the segment the tooth sits on. + pub segment: usize, +} + +/// The most teeth a curvature comb draws in all. +pub const MAX_COMB_TEETH: usize = 20_000; + +/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` +/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment +/// gives teeth of no length, its ends included. A point of a curved segment where it has no +/// direction (a handle drawn back onto its anchor) gives no tooth, and neither does a segment +/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When +/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when +/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec { + let n = sp.segment_count(); + if n == 0 || !scale.is_finite() || max_teeth < 2 { + return vec![]; + } + let per = if samples.max(2).saturating_mul(n) <= max_teeth { samples.max(2) } else { 2 }; + let stride = (per * n).div_ceil(max_teeth).max(1); + let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); + let mut start = true; + // The direction of the last curved tooth, carried across segments so that a cusp at an + // anchor also starts a new line through the tips. + let mut previous_direction: Option = None; + for seg in (0..n).step_by(stride) { + if stride > 1 { + start = true; + previous_direction = None; + } + let c = sp.segment(seg); + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + start = true; + previous_direction = None; + continue; + } + let (d1, d2) = (c.deriv(), c.deriv().deriv()); + // The control polygon's length sets what counts as no speed. + let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let chord = c.p3 - c.p0; + let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; + for i in 0..per { + if teeth.len() >= max_teeth { + return teeth; + } + let t = i as f64 / (per - 1) as f64; + if line { + // A line stored with its handles on its anchors has no speed at its ends, but a + // direction and no curvature all along. + let at = c.eval(t); + previous_direction = None; + if !at.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip: at, start, segment: seg }); + start = false; + continue; + } + let (v, a) = (d1.eval(t).to_vec2(), d2.eval(t).to_vec2()); + let speed = v.hypot(); + if speed <= CUSP_SHARE * size || !speed.is_finite() { + start = true; + previous_direction = None; + continue; + } + let k = v.cross(a) / (speed * speed * speed); + let direction = v / speed; + start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + previous_direction = Some(direction); + let normal = Vec2::new(-direction.y, direction.x); + let at = c.eval(t); + let tip = at - normal * (k * scale); + if !at.is_finite() || !tip.is_finite() { + start = true; + previous_direction = None; + continue; + } + teeth.push(CombTooth { at, tip, start, segment: seg }); + start = false; + } + } + teeth +} + +/// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where +/// it starts: `sp` is closed, only segments with no length lie between its last tooth and its +/// first across the seam, the two sit on the same point, and the curve does not turn back on itself at its +/// first anchor. A comb that skips segments to keep to its budget does not close across the ones +/// it skipped at the end. +pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { + let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { + return false; + }; + let n = sp.segment_count(); + if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { + return false; + } + // Only segments with no length may lie between the last tooth and the first across the seam. + let no_length = |i: usize| start_direction(sp.segment(i)) == Vec2::ZERO; + if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { + return false; + } + match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { + (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; use crate::{Anchor, shapes}; use kurbo::Rect; + fn tooth_len(t: &CombTooth) -> f64 { + t.at.distance(t.tip) + } + + /// A circle's comb points away from the center, each tooth `scale` times the cubic's own + /// curvature at its point ([`curvature_circle_with`] without arcs), all within 3% of + /// `scale / r` (the usual cubic of a quarter turn strays that little from its circle). + #[test] + fn the_comb_of_a_circle_has_teeth_of_one_length() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + let teeth = curvature_comb(sp, 9, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9 * sp.segment_count()); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "one unbroken comb"); + let center = Point::new(150.0, 150.0); + for (i, t) in teeth.iter().enumerate() { + let (seg, at) = (i / 9, (i % 9) as f64 / 8.0); + let r = curvature_circle_with(sp.segment(seg), at, false, false).unwrap().radius; + assert!((tooth_len(t) * r - 1000.0).abs() < 1e-6, "{t:?} {r}"); + assert!((tooth_len(t) - 10.0).abs() < 0.3, "{t:?}"); + assert!(t.tip.distance(center) > t.at.distance(center), "outward: {t:?}"); + } + } + + /// A straight line has teeth of no length, its two ends included. + #[test] + fn the_comb_of_a_line_is_flat() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 40.0), Point::new(200.0, 0.0)], false); + let teeth = curvature_comb(&sp, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 10); + assert!(teeth.iter().all(|t| tooth_len(t) < 1e-9), "{teeth:?}"); + assert_eq!(teeth[4].at, Point::new(100.0, 40.0), "the corner has a tooth on each side"); + } + + /// Two quarter circles of radius 100 and 50 that meet in one direction: the teeth double in + /// length at the anchor they share. + #[test] + fn the_comb_jumps_where_the_curvature_does() { + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan(); + let a0 = Anchor { h_out: Point::new(100.0 * k, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { + h_in: Point::new(100.0, 100.0 - 100.0 * k), + h_out: Point::new(100.0, 100.0 + 50.0 * k), + ..Anchor::corner(Point::new(100.0, 100.0)) + }; + let a2 = Anchor { h_in: Point::new(50.0 + 50.0 * k, 150.0), ..Anchor::corner(Point::new(50.0, 150.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + let (before, after) = (tooth_len(&teeth[2]), tooth_len(&teeth[3])); + assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); + assert!((before - 10.0).abs() < 0.3, "{before}"); + assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "a smooth anchor keeps one unbroken comb"); + } + + /// Two segments that meet at a cusp on their shared anchor: the first segment ends heading + /// down and the second starts heading up, so the line through the tips starts again there. + #[test] + fn the_comb_breaks_at_a_cusp_on_an_anchor() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); + } + + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a + /// cusp elsewhere, and stays open when the first anchor is the cusp. + #[test] + fn the_comb_closes_unless_its_first_anchor_is_a_cusp() { + let closed = |h_in: Point| { + let a0 = Anchor { h_in, h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), h_out: Point::new(200.0, 50.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + SubPath::new(vec![a0, a1, a2], true) + }; + let smooth = closed(Point::new(0.0, 50.0)); + let teeth = curvature_comb(&smooth, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 2, "the cusp at the second anchor breaks the comb"); + assert!(comb_closes(&smooth, &teeth)); + let cusp = closed(Point::new(0.0, -50.0)); + assert!(!comb_closes(&cusp, &curvature_comb(&cusp, 3, 1000.0, MAX_COMB_TEETH))); + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let sp = &circle.subpaths[0]; + assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); + } + + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no + /// tooth where the curve has no direction; a scale that is not finite gives no comb. + #[test] + fn the_comb_skips_points_with_no_direction() { + let p = Point::new(10.0, 10.0); + assert!(curvature_comb(&SubPath::polyline(&[p, p], false), 4, 1000.0, MAX_COMB_TEETH).is_empty()); + let curve = SubPath::new( + vec![Anchor { h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }, Anchor::corner(Point::new(100.0, 100.0))], + false, + ); + let teeth = curvature_comb(&curve, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the end whose handle sits on its anchor has no tooth: {teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, false]); + let back = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor { h_in: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(100.0, 100.0)) }], + false, + ); + let teeth = curvature_comb(&back, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the start, whose handle sits on its anchor, has no tooth: {teeth:?}"); + assert!(teeth[0].start, "the comb starts after the point with no tooth"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(curvature_comb(&curve, 5, f64::NAN, MAX_COMB_TEETH).is_empty()); + } + + /// A cusp between samples starts a new line through the comb's tips after the cusp. + #[test] + fn the_comb_breaks_at_a_cusp_between_samples() { + let bp = kurbo::BezPath::from_svg("M0 0 C100 100 0 100 100 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + let teeth = curvature_comb(sp, 6, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6, "the cusp falls between teeth"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + } + + /// A tooth whose tip overflows is skipped, and the next finite tooth starts a new envelope. + #[test] + fn the_comb_breaks_after_a_nonfinite_tip() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(-1.0, 1.0), Point::new(-1.0, 1.0), Point::new(-1.0 / 3.0, -1.0 / 3.0)), + Anchor::with_handles(Point::new(1.0, 1.0), Point::new(1.0 / 3.0, -1.0 / 3.0), Point::new(1.0, 1.0)), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, f64::MAX, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the middle tooth overflows"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, true, false]); + assert!(teeth[1].at.x < 0.0 && teeth[2].at.x > 0.0, "the gap is inside the segment"); + } + + /// A speed whose cube underflows gives no tooth, and the first finite tooth starts the comb. + #[test] + fn the_comb_skips_a_tip_when_speed_cubed_underflows() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::ORIGIN, Point::ORIGIN, Point::new(1e-109, 0.0)), + Anchor::with_handles(Point::ORIGIN, Point::new(1e-101, 1e-101), Point::ORIGIN), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the first tooth has a nonfinite tip"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(teeth[0].start && teeth[0].at.x > 0.0, "the comb starts after the skipped tooth"); + } + + /// A subpath with more segments than the budget allows keeps to it, with teeth spread to its + /// far end rather than stopping part way. + #[test] + fn the_comb_is_capped_and_spread() { + let points: Vec = (0..30_001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let sp = SubPath::polyline(&points, false); + let teeth = curvature_comb(&sp, 16, 1.0, 1000); + assert!(teeth.len() <= 1000 && teeth.len() >= 900, "{}", teeth.len()); + assert!(teeth.last().is_some_and(|t| t.at.x > 29_000.0), "{:?}", teeth.last()); + assert_eq!(teeth.iter().filter(|t| t.start).count() * 2, teeth.len(), "each sampled segment starts a new line through the tips"); + let few = curvature_comb(&sp, 16, 1.0, 100_000); + assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); + } + + /// A capped comb that skips the last segment does not close, even when the last segment it + /// samples ends on the first anchor: the line through the tips would cross the skipped loop. + #[test] + fn a_capped_comb_does_not_close_across_a_skipped_segment() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(-50.0, -50.0), Point::new(50.0, 50.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(80.0, 40.0), Point::new(120.0, 20.0)), + Anchor::with_handles(Point::new(100.0, 100.0), Point::new(140.0, 80.0), Point::new(60.0, 140.0)), + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(30.0, 120.0), Point::new(-60.0, 60.0)), + ], + true, + ); + let teeth = curvature_comb(&sp, 16, 1000.0, 4); + let (first, last) = (&teeth[0], &teeth[teeth.len() - 1]); + assert!(last.segment < 3, "the closing segment is skipped: {teeth:?}"); + assert!(first.at.distance(last.at) < 1e-9, "the last sampled tooth sits on the first anchor"); + assert!(!comb_closes(&sp, &teeth), "the comb does not close across the skipped last segment"); + assert!(comb_closes(&sp, &curvature_comb(&sp, 16, 1000.0, MAX_COMB_TEETH)), "the full comb closes"); + let mut anchors: Vec = sp.anchors.iter().copied().collect(); + anchors[0].h_in = anchors[0].p; + anchors.insert(0, Anchor { h_in: Point::new(-50.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }); + let seam = SubPath::new(anchors, true); + let full = curvature_comb(&seam, 16, 1000.0, MAX_COMB_TEETH); + assert_eq!(full.first().map(|t| t.segment), Some(1), "the segment of no length at the seam has no teeth"); + assert!(comb_closes(&seam, &full), "the comb closes across a segment of no length"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test] diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index fea760b548..2624f0a1a9 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; -use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape}; +use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape}; use crate::path::{FillRule, PathData}; @@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> { /// Distance from `p` to the nearest point on the path outline. pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 { - path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt() } /// Is `p` within `tol` of the path's stroke of width `width`? pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { - let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol); - quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol + let radius = width / 2.0 + tol; + if !path.bounding_box().inflate(radius, radius).contains(p) { + return false; + } + if !radius.is_finite() { + return distance_to_outline(path, p) <= radius; + } + + // Keep candidates whose squared distance could underflow near a zero radius. + let search_radius = radius.max(f64::MIN_POSITIVE.sqrt()); + path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius) +} + +// A Bézier stays inside the bounds of its control points. A line projection is +// already cheap, so only check the bounds before running a curve solver. +fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool { + let bounds = match segment { + PathSeg::Line(_) => return false, + PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2), + PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3), + }; + outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1) +} + +fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool { + // Leave room for rounding in the curve evaluation and the distance comparison. + let scale = p.abs().max(low.abs()).max(high.abs()).max(radius); + let padded = radius + 8.0 * f64::EPSILON * scale; + p < low - padded || p > high + padded +} + +fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 { + #[cfg(test)] + OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1)); + segment.nearest(p, 1e-9).distance_sq +} + +#[cfg(test)] +thread_local! { + static OUTLINE_NEAREST_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for @@ -185,6 +223,53 @@ mod tests { assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0))); } + #[test] + fn stroke_hit_skips_distant_curves_without_changing_results() { + let mut path = BezPath::new(); + for i in 0..96 { + let x = f64::from(i) * 16.0; + path.move_to((x, 0.0)); + path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0)); + } + path.move_to((512.0, 0.0)); + path.quad_to((513.0, 4.0), (514.0, 0.0)); + + for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] { + assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit); + assert!(path.bounding_box().contains(point)); + OUTLINE_NEAREST_CALLS.with(|count| count.set(0)); + assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit); + assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls); + } + + assert_stroke_hits_at_cutoff(); + } + + fn assert_stroke_hits_at_cutoff() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((0.0, 0.0)); + path.quad_to((4.0, 8.0), (8.0, 0.0)); + path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0)); + path.close_path(); + path.move_to((2.0, -3.0)); + path.line_to((2.0, -3.0)); + + for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] { + let transformed = transform * path.clone(); + for x in -2..23 { + for y in -5..9 { + let point = transform * Point::new(f64::from(x), f64::from(y)); + let distance = distance_to_outline(&transformed, point); + for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] { + let inside = transformed.bounding_box().inflate(radius, radius).contains(point); + assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}"); + } + } + } + } + } + #[test] fn evenodd_hole() { let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 8182fde016..eb1e0dbc9e 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -730,6 +730,11 @@ impl Interp { !self.frames.is_empty() || self.promises.draining } + /// Whether promise jobs wait to run. + pub(crate) fn jobs_waiting(&self) -> bool { + !self.promises.queue.is_empty() + } + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's /// code ended with `completion`, which this gives back. pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { @@ -887,9 +892,10 @@ impl Interp { } /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of - /// them described, and how many there are; the run's notes are cleared. - pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { - let rejected = std::mem::take(&mut self.promises.rejected); + /// them described, and how many there are. The run's notes stay until the next run starts, so a + /// later call leaves out a promise that has a handler since. + pub(crate) fn unhandled(&mut self) -> (Vec, usize) { + let rejected = self.promises.rejected.clone(); let mut out = Vec::new(); let mut attribution = Vec::new(); let mut count = 0; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a720940b06..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -131,6 +131,7 @@ //! `await` (ECMA-262 2017 section 25.5, ). //! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 34cab5c170..0254c2fb80 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -489,7 +489,7 @@ impl Realm { } match result { Ok(v) => { - self.rejections = interp.take_unhandled(); + self.rejections = interp.unhandled(); Ok(interp.to_js_value(&v)) } Err(Abrupt::Throw(v)) => { @@ -755,6 +755,53 @@ impl Realm { } } + /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as + /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the + /// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause + /// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel, + /// and the host then gets the controls once more ([`crate::scriptui::refresh`]). The run's + /// report of unhandled rejections ([`Realm::unhandled_rejections`]) is then made again: it + /// takes in the rejections of those jobs and leaves out a run's rejection that a getter or a + /// job gave a handler. + pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { + let interp = &mut self.interp; + let total = interp.fuel; + let cap = self.unbroken_fuel.min(total); + interp.fuel = cap; + let r = crate::scriptui::refresh(interp); + let used = cap - interp.fuel; + interp.fuel = total - used; + match r { + Ok(()) => { + self.rejections = self.interp.unhandled(); + Ok(()) + } + // A refresh that fails reports no rejection, as after any failed run. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop) + } + Err(e) => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(e)).map(drop) + } + } + } + + /// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped, + /// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and + /// its thrown value. The report of unhandled rejections stays empty, as after any failed run. + pub fn refresh_script_ui_after_error(&mut self) { + let (tag, mark) = (self.interp.error_tag, self.interp.error_mark); + let thrown = self.interp.last_thrown.clone(); + let rejections = std::mem::take(&mut self.rejections); + let _ = self.refresh_script_ui(); + self.interp.error_tag = tag; + self.interp.error_mark = mark; + self.interp.last_thrown = thrown; + self.rejections = rejections; + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 80982a48ce..8864fc1911 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2,8 +2,9 @@ //! describes it, whose //! drawing a host does ([`crate::Realm::define_script_ui`]). //! -//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A -//! window of type `palette` or `window` throws an `Error` that says it is not available yet. +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`, and +//! `new Window("palette", ...)` a palette, once the host's `palette` allows it. A window of type +//! `window` throws an `Error` that says it is not available yet. //! `new Window` and `add` also take a resource specification in place of the type, as the help //! page //! describes it (read by [`crate::scriptui_resource`]), and then read no other argument: the @@ -12,7 +13,7 @@ //! assigned to the container's property of that name, a list's `items` gives its item texts as //! `add`'s third argument does, and each other value is assigned to the property of its name. A //! malformed specification throws a `SyntaxError`. `add(type[, bounds, text, properties])` adds a -//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! control to a dialog, a palette, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet, and @@ -55,6 +56,27 @@ //! other dialog can be shown while one is. When `show()` ends, the host's `end` is given its result //! and whether it ended normally. //! +//! A palette's `show()` gives the host's `paletteShow` its description and its id (none the first +//! time), which gives back the id, then runs `onShow` and returns `undefined` without waiting. +//! `hide()` gives `paletteHide` the id, and `close()` runs `onClose`, and unless it returns `false` +//! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps +//! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the +//! host's `paletteEvent` (`{palette, event, id, value, element}`, or `null`, with `element` the id +//! of the control), and gives it to that palette as a dialog takes one, without giving +//! `paletteUpdate` any description: the host gets the palettes' controls when the run ends +//! ([`crate::Realm::refresh_script_ui`]). `add()` on a shown palette gives `paletteUpdate` that +//! palette's description, so the host's list of its controls stays in step. +//! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits +//! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or +//! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving +//! `paletteUpdate` each palette's description before each one. When a handler's exception ends +//! this, `update()` calls `palettePending` once more before the exception leaves it. Then, called from the script's own code (not from a +//! handler, a callback of a built-in function, a getter or a conversion), it asks the host's +//! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the +//! palette's description. On the showing dialog, or a group or panel in it, `update()` does +//! nothing more, and on a window that is not showing it throws an `Error`. A dialog takes the +//! person's events once the running handler returns. +//! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] @@ -74,6 +96,10 @@ use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; use crate::scriptui_resource::{self, Fault, Res, Spec}; use crate::value::{Value, index_key}; +/// The global property, not an identifier, that the run of a palette's handler calls as +/// `this[PALETTE_EVENT_GLOBAL]()` to take its event ([`palette_event`]). +pub const PALETTE_EVENT_GLOBAL: &str = "%vcPaletteEvent"; + /// The most controls a dialog holds, its groups and panels included. pub const MAX_CONTROLS: usize = 512; /// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. @@ -106,6 +132,15 @@ const ITEMS: &str = "__vcItems"; const ITEMS_REV: &str = "__vcItemsRev"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const PALETTE_ID: &str = "__vcPaletteId"; +const SHOWN: &str = "__vcShown"; +const IN_CLOSE: &str = "__vcInClose"; +/// How many times a palette was hidden: an event it took before a hide is not its event after a +/// later `show()`. +const HIDES: &str = "__vcHides"; +/// How many times a list's items were added or removed: a palette's waiting change of the list is +/// for the items it had then. +const REVISION: &str = "__vcRevision"; const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; @@ -143,7 +178,8 @@ const EVENTS_LATER: [&str; 14] = [ "keydown", ]; -/// The objects of `Window`, kept by the realm, and the dialog that is showing. +/// The objects of `Window`, kept by the realm, the dialog that is showing, and the palettes the +/// host shows, shown or hidden. #[derive(Clone, Debug)] pub(crate) struct Classes { window_proto: ObjId, @@ -157,6 +193,9 @@ pub(crate) struct Classes { radio_get: ObjId, radio_set: ObjId, showing: Option, + palettes: Vec, + /// Whether an `update()` is taking the waiting events ([`take_waiting`]). + taking: bool, /// The event objects whose listeners are running, innermost last. dispatching: Vec, /// The containers above the targets of the running events. @@ -181,12 +220,23 @@ impl Classes { self.radio_set, ]; all.extend(self.showing); + all.extend(self.palettes.iter().copied()); all.extend(self.dispatching.iter().copied()); all.extend(self.above.iter().copied()); all } } +/// Is `kind` a window's: a dialog's or a palette's? +fn is_window(kind: &str) -> bool { + kind == "dialog" || kind == "palette" +} + +/// Does `kind` hold controls? +fn is_container(kind: &str) -> bool { + is_window(kind) || kind == "group" || kind == "panel" +} + /// Forgets the dialog that was showing, and the events that were running, when a run ended where /// it was. pub(crate) fn end_run(i: &mut Interp) { @@ -443,7 +493,7 @@ fn new_element( let d = dimension(i, -1.0, -1.0)?; set_open(i, o, name, d)?; } - let container = matches!(kind, "dialog" | "group" | "panel"); + let container = is_container(kind); if container { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; @@ -481,12 +531,20 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let creation = creation_properties(i, spec)?; - new_element(i, proto, "dialog", None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? + new_element(i, proto, ty, None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? } - None => new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, + None => new_element(i, proto, ty, None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, }; set_slot(i, o, COUNT, Value::Number(0.0))?; set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; @@ -645,9 +703,13 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if ty.to_lowercase() != "item" { return Err(error(i, "add: a list holds only items")); } - return add_item(i, o, &arg(args, 1)); + let item = add_item(i, o, &arg(args, 1))?; + if let Some(win) = object_slot(i, o, WINDOW)? { + i.rooted(std::slice::from_ref(&item), |i| publish_palette(i, win))?; + } + return Ok(item); } - if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + if !is_container(&kind) { return Err(error(i, &format!("add: a {kind} holds no controls"))); } if is_resource(&ty) { @@ -774,6 +836,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let counts = vec![(win, COUNT, Value::Number(count + 1.0), 0), (win, ITEM_COUNT, Value::Number(items + staged as f64), 0)]; append(i, o, KIDS, "children", Value::Object(c), counts)?; + // The host's copy of a shown palette keeps each control's place in the list, which events + // name it by. + publish_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -803,6 +868,8 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value, more: Vec>) -> JsRe i.rooted(&[Value::Object(item)], |i| { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; + let mut more = more; + more.push((o, REVISION, Value::Number(number_slot(i, o, REVISION)? + 1.0), 0)); append(i, o, ITEMS, "items", Value::Object(item), more)?; Ok(Value::Object(item)) }) @@ -827,6 +894,9 @@ fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { let kept = list(i, &items, false)?; i.temp_roots.push(Value::Object(kept)); set_items(i, o, kept)?; + // Each item counts as one change of the list's items ([`REVISION`]), as `add` counts it. + let revision = number_slot(i, o, REVISION)? + items.len() as f64; + set_slot(i, o, REVISION, Value::Number(revision))?; let copy = list(i, &items, true)?; set_open(i, o, "items", Value::Object(copy))?; Ok(items.len()) @@ -929,6 +999,7 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult, event: ObjId, phase: f64, cutoff: f64) -> JsResult { +/// `at` when the event started. None runs once the palette of `taker` no longer takes the event. +/// → whether it had any; `None` when the palette stopped taking the event. +fn run_listeners( + i: &mut Interp, + at: ObjId, + ty: &str, + capture: Option, + (event, phase, cutoff): (ObjId, f64, f64), + taker: Taker, +) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() @@ -1154,7 +1233,7 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve }; let first = wanted(i)?; if first.is_empty() { - return Ok(false); + return Ok(Some(false)); } let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); i.rooted(&functions, |i| { @@ -1164,9 +1243,12 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve if !wanted(i)?.iter().any(|(_, m)| m == n) { continue; } + if !takes(i, taker)? { + return Ok(None); + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } - Ok(true) + Ok(Some(true)) }) } @@ -1177,6 +1259,45 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve /// do not capture do not count. A container that a listener took the element out of before its /// turn does not hear the event. fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { + Ok(dispatch_for(i, target, ty, callback, None)?.unwrap_or(false)) +} + +/// The palette, the event it takes and the event's control, whose handlers run only while the +/// palette takes the event ([`still_takes`]) and holds the control; `None` for a dialog, which +/// always takes it. +type Taker = Option<(ObjId, ObjId, ObjId)>; + +/// Does the palette of `taker` still take its event and hold its control, with the control and +/// every container above it enabled and visible as they are now, read without running a getter +/// ([`plain_state`])? Always true for a dialog. +fn takes(i: &mut Interp, taker: Taker) -> JsResult { + match taker { + Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)? && live_up(i, win, c)?), + None => Ok(true), + } +} + +/// Whether `c` and each container above it, up to and including `top`, are enabled and visible, +/// read without running a getter ([`plain_state`]). +fn live_up(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH + 1 { + if !plain_state(i, at, "enabled")? || !plain_state(i, at, "visible")? { + return Ok(false); + } + if at == top { + return Ok(true); + } + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + at = p; + } + Ok(false) +} + +/// [`dispatch`] for the event a palette takes (`taker`): no handler or listener runs once a getter, +/// a handler or a listener of the event closed the palette or took the event's control out of it. +/// → `None` when that happened. +fn dispatch_for(i: &mut Interp, target: ObjId, ty: &str, callback: &str, taker: Taker) -> JsResult> { let above = containers_above(i, target)?; let proto = classes(i)?.event_proto; i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; @@ -1191,7 +1312,7 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult } None => 0, }; - let r = run_event(i, event, target, &above, ty, callback); + let r = run_event(i, event, target, &above, ty, callback, taker); if let Some(c) = i.script_ui.as_mut() { if let Some(n) = c.dispatching.iter().rposition(|e| *e == event) { c.dispatching.remove(n); @@ -1217,8 +1338,8 @@ fn containers_above(i: &mut Interp, target: ObjId) -> JsResult> { Ok(above) } -/// The phases of [`dispatch`] for the event object `event`. -fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str) -> JsResult { +/// The phases of [`dispatch_for`] for the event object `event`. +fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str, taker: Taker) -> JsResult> { i.rooted(&[Value::Object(event)], |i| { let bubbles = ty != "show"; set_open(i, event, "type", Value::str(ty))?; @@ -1235,38 +1356,65 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(true), event, 1.0, *n)?; + if run_listeners(i, *p, ty, Some(true), (event, 1.0, *n), taker)?.is_none() { + return Ok(None); + } if stopped(i)? { - return Ok(true); + return Ok(Some(true)); } } - let had = handler(i, target, callback)?.is_some(); - let heard = run_listeners(i, target, ty, None, event, 2.0, target_cutoff)?; + if !takes(i, taker)? { + return Ok(None); + } + let f = i.get_value(&Value::Object(target), &key(callback))?; + // A getter for the callback may have closed the palette. + if !takes(i, taker)? { + return Ok(None); + } + let had = i.is_callable(&f); + if had { + i.call(&f, &Value::Object(target), &[])?; + } + if !takes(i, taker)? { + return Ok(None); + } + let Some(heard) = run_listeners(i, target, ty, None, (event, 2.0, target_cutoff), taker)? else { return Ok(None) }; if bubbles && !stopped(i)? { for (p, n) in above.iter().zip(&cutoffs) { if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(false), event, 3.0, *n)?; + if run_listeners(i, *p, ty, Some(false), (event, 3.0, *n), taker)?.is_none() { + return Ok(None); + } if stopped(i)? { break; } } } - Ok(had || heard) + Ok(Some(had || heard)) }) } /// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then /// the click runs. → whether the click was handled, as [`dispatch`] says. fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { + Ok(click_control_for(i, c, kind, None)?.unwrap_or(false)) +} + +/// [`click_control`] for the click a palette takes (`taker`), as [`dispatch_for`] runs it. +fn click_control_for(i: &mut Interp, c: ObjId, kind: &str, taker: Taker) -> JsResult> { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + // A `value` getter may have disabled or hidden the box, or closed its palette. + if taker.is_some() && !takes(i, taker)? { + return Ok(None); + } i.put(c, key("value"), Value::Bool(!on), true)?; } else if kind == "radiobutton" { i.put(c, key("value"), Value::Bool(true), true)?; } - dispatch(i, c, "click", "onClick") + dispatch_for(i, c, "click", "onClick", taker) } /// `notify([event])`: simulates the control's `onClick`, `onChange` or `onChanging`. @@ -1384,12 +1532,14 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult { Ok(Value::Undefined) } -fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { +/// `this` as a window, and whether it is a palette. +fn this_window(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, bool)> { match kind_of(i, this)? { - Some((o, kind)) if kind == "dialog" => Ok(o), + Some((o, kind)) if is_window(&kind) => Ok((o, kind == "palette")), _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), } } -/// `close([result])`: closes the dialog that is showing once the running handler returns. +/// `close([result])`: closes the dialog that is showing once the running handler returns, or the +/// palette at once. fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let o = dialog_of(i, &this, "close")?; + let (o, palette) = this_window(i, &this, "close")?; let result = match arg(args, 0) { Value::Undefined => 0.0, v => number_arg(i, &v, "close: the result")?, }; - if classes(i)?.showing == Some(o) { + if palette { + close_palette(i, o)?; + } else if classes(i)?.showing == Some(o) { set_slot(i, o, CLOSING, Value::Number(result))?; } Ok(Value::Undefined) } -/// `hide()`: closes the dialog that is showing with the result 0. +/// `hide()`: closes the dialog that is showing with the result 0, or hides the palette, which a +/// later `show()` shows again as it was. A palette's `visible` is false once the host hid it, and +/// true again once the host shows it. fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - close(i, this, &[], false) + let (o, palette) = this_window(i, &this, "hide")?; + if !palette { + return close(i, this, &[], false); + } + if let Value::Number(id) = slot(i, o, PALETTE_ID)? { + let f = host_fn(i, "paletteHide")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + set_slot(i, o, SHOWN, Value::Bool(false))?; + let hides = number_slot(i, o, HIDES)? + 1.0; + set_slot(i, o, HIDES, Value::Number(hides))?; + i.put(o, key("visible"), Value::Bool(false), true)?; + } + Ok(Value::Undefined) +} + +/// `update()` on a window: [`update_window`]. +fn update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, palette) = this_window(i, &this, "update")?; + update_window(i, o, palette, own)?; + Ok(Value::Undefined) +} + +/// Whether the native running now was called from the script's own code in a run that can pause, +/// as the host's functions find whether a run can wait. +fn own_code(i: &Interp) -> bool { + i.in_slice && i.reentry == 0 +} + +/// `update()` on a `group` or a `panel`: [`update_window`] for the window that holds it. +fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, kind) = element(i, &this, "update")?; + if !is_container(&kind) { + return Err(i.type_error("update: this is not a ScriptUI window or container")); + } + let win = window_of(i, o, "update")?; + let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); + update_window(i, win, palette, own)?; + Ok(Value::Undefined) +} + +/// `update()` on the window `win`. On a shown palette: hands each event that waits for a palette of +/// the run's engine to its palette ([`take_waiting`]), and then, from the script's own code (`own`), +/// gives the host the palette's controls when the host draws it now (`paletteDraw`). The showing +/// dialog's controls go to the host when its handler returns, since a handler runs to its end in +/// one slice. Whether a palette shows is the host's, not its `visible` property. A window that is +/// not showing throws. +fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResult<()> { + let showing = if palette { slot(i, win, SHOWN)?.truthy() } else { classes(i)?.showing == Some(win) }; + if !showing { + return Err(error(i, "update: the window is not showing")); + } + if !palette { + return Ok(()); + } + take_waiting(i)?; + if !own || !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let f = host_fn(i, "paletteDraw")?; + if i.call(&f, &Value::Undefined, &[])?.truthy() { + update_palette(i, win)?; + } + Ok(()) +} + +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits +/// (`palettePending`). Before each one the host gets every palette's controls as the script and the +/// handlers before it left them, as at the end of a run, and drops an event whose control has since +/// been disabled, hidden or removed. An `update()` that a getter or a handler calls meanwhile takes +/// no events: the `update()` already taking them goes on with the next one. +fn take_waiting(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_some_and(|c| c.taking) { + return Ok(()); + } + set_taking(i, true); + let r = take_each(i); + set_taking(i, false); + r +} + +fn set_taking(i: &mut Interp, taking: bool) { + if let Some(c) = i.script_ui.as_mut() { + c.taking = taking; + } +} + +/// [`take_waiting`]'s loop. +fn take_each(i: &mut Interp) -> JsResult<()> { + let pending = host_fn(i, "palettePending")?; + let f = host_fn(i, "paletteTake")?; + loop { + if !i.call(&pending, &Value::Undefined, &[])?.truthy() { + return Ok(()); + } + update_palettes(i)?; + let answer = i.call(&f, &Value::Undefined, &[])?; + if answer.as_object().is_none() { + return Ok(()); + } + if let Err(e) = deliver(i, answer) { + // The host learns that the event's handlers have ended, as it does before the next + // event, when a handler's exception ends the loop. + if let Abrupt::Throw(v) = &e { + let v = v.clone(); + let _ = i.rooted(std::slice::from_ref(&v), |i| i.call(&pending, &Value::Undefined, &[])); + } + return Err(e); + } + } +} + +fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { + if let Some(c) = i.script_ui.as_mut() { + f(&mut c.palettes); + } +} + +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it, its +/// `visible` is false and its handlers no longer run. A `close()` while its `onClose` runs does +/// nothing more. +fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + if slot(i, win, IN_CLOSE)?.truthy() { + return Ok(()); + } + if !may_close(i, win)? { + return Ok(()); + } + if let Value::Number(id) = slot(i, win, PALETTE_ID)? { + set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_slot(i, win, SHOWN, Value::Bool(false))?; + set_palettes(i, |p| p.retain(|o| *o != win)); + let f = host_fn(i, "paletteClose")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + // The host has closed it; a `visible` the script made read-only stays as it is. + i.put(win, key("visible"), Value::Bool(false), false)?; + } + Ok(()) +} + +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. A +/// palette that `hide()` hid is not read: `show()` gives its controls when it shows it again. +fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + if !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let (desc, ..) = describe(i, win)?; + let f = host_fn(i, "paletteUpdate")?; + i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; + Ok(()) +} + +/// [`update_palette`] after an `add` or a `remove` that has already changed the palette: what a +/// getter throws while the palette is read does not take the place of the change's result. The +/// host gets the controls at the next update, or when the run ends ([`refresh`]). +fn publish_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + match update_palette(i, win) { + // The exception no longer propagates, so a later error is reported at its own place. + Err(Abrupt::Throw(_)) => { + i.passing = Value::Undefined; + i.thrown_mark = None; + i.throw_site = None; + Ok(()) + } + r => r, + } +} + +/// Gives the host the controls of every palette it shows, after a handler may have changed them. +fn update_palettes(i: &mut Interp) -> JsResult<()> { + // A getter may close a later palette, which removes it from the rooted list, so the copy is + // rooted until the loop ends. + let palettes = classes(i)?.palettes; + let roots: Vec = palettes.iter().map(|&win| Value::Object(win)).collect(); + i.rooted(&roots, |i| { + for win in palettes { + update_palette(i, win)?; + } + Ok(()) + }) +} + +/// Gives the host the controls of every palette the realm keeps, as a run left them +/// ([`crate::Realm::refresh_script_ui`]). When the getters queued promise jobs, the jobs run and +/// the host gets the controls once more, and the jobs that second pass queues run too. An +/// `update()` that a getter or a job calls meanwhile takes no waiting event, which waits for a run +/// of its own. +pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = (|| { + refresh_palettes(i)?; + if i.jobs_waiting() { + i.drain_jobs(Value::Undefined)?; + refresh_palettes(i)?; + i.drain_jobs(Value::Undefined)?; + } + Ok(()) + })(); + set_taking(i, was); + r +} + +/// Gives the host the controls of every palette the realm keeps, or does nothing without palettes. +fn refresh_palettes(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { + return Ok(()); + } + update_palettes(i) +} + +/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` +/// returns `undefined` without waiting. +fn show_palette(i: &mut Interp, win: ObjId) -> JsResult { + let (desc, ..) = describe(i, win)?; + let id = slot(i, win, PALETTE_ID)?; + let f = host_fn(i, "paletteShow")?; + Ok(Pause { host: f, args: vec![desc, id], keep: vec![Value::Object(win)], resume: palette_shown, failed: None }) +} + +fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its palette".into())) }; + let Value::Number(_) = id else { return Err(Abrupt::Internal("the host gave the palette no id".into())) }; + set_slot(i, win, PALETTE_ID, id)?; + if !classes(i)?.palettes.contains(&win) { + set_palettes(i, |p| p.push(win)); + } + set_slot(i, win, SHOWN, Value::Bool(true))?; + i.put(win, key("visible"), Value::Bool(true), true)?; + handler(i, win, "onShow")?; + update_palette(i, win)?; + Ok(Value::Undefined) +} + +/// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the +/// host's `paletteEvent` and gives it to the palette the way a dialog takes the person's event. The +/// host gets every palette's controls once the run ends ([`crate::Realm::refresh_script_ui`]). An +/// event for a palette that has closed does nothing. +fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let f = host_fn(i, "paletteEvent")?; + let answer = i.call(&f, &Value::Undefined, &[])?; + // An `update()` that a handler calls while this event runs takes no waiting event, so a later + // event does not run before this one has finished. + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = deliver(i, answer); + set_taking(i, was); + r?; + Ok(Value::Undefined) +} + +/// Gives the host's event `answer` (`{palette, event, id, value, element}`, or anything else for +/// none) to its palette the way a dialog takes the person's event. An event for a palette that has +/// closed does nothing. +fn deliver(i: &mut Interp, answer: Value) -> JsResult { + let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; + let mark = i.temp_roots.len(); + i.temp_roots.push(answer.clone()); + let r = (|| { + let id = slot(i, ev, "palette")?; + let palettes = classes(i)?.palettes; + let mut win = None; + for p in palettes { + if matches!((slot(i, p, PALETTE_ID)?, &id), (Value::Number(a), Value::Number(b)) if a == *b) { + win = Some(p); + } + } + let Some(win) = win else { return Ok(Value::Undefined) }; + // A hide from here on, even one a later show() follows, ends the palette's hold on the event. + let hides = number_slot(i, win, HIDES)?; + set_slot(i, ev, HIDES, Value::Number(hides))?; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + close_palette(i, win)?; + } else { + let (desc, nodes, ..) = describe(i, win)?; + // A getter read in the description may have closed the palette. + if !still_takes(i, win, ev, None)? { + return Ok(Value::Undefined); + } + i.temp_roots.push(desc.clone()); + i.temp_roots.push(Value::Object(nodes)); + let held = list_values(i, nodes)?; + // The host gives the control's id, which is found again in the palette as it is now: a + // getter read in the description may have added or removed a control before it. + let at = match slot(i, ev, "element")? { + Value::Number(element) => { + let mut at = None; + for (n, v) in held.iter().enumerate().skip(1) { + if let Some(c) = v.as_object() + && number_slot(i, c, ID)? == element + { + at = Some(n); + break; + } + } + at + } + _ => match slot(i, ev, "id")? { + Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => Some(n as usize), + _ => None, + }, + }; + // A getter read in the description may also have removed the control after the + // description listed it: no handler runs for it. + let gone = match at.filter(|&n| n >= 1 && n < held.len()) { + Some(n) => match held[n].as_object() { + Some(c) => !holds(i, win, c)?, + None => false, + }, + None => true, + }; + let Some(at) = at.filter(|_| !gone) else { + return Err(error(i, "a palette event names a control the palette no longer holds")); + }; + // A getter read in the description may have disabled or hidden the control, or a + // container above it: the event is dropped, as the host drops one for such a control. + if !live_in(i, &desc, at)? { + return Ok(Value::Undefined); + } + // A getter read later in the description may have disabled or hidden the control or a + // container above it after the description recorded it: read the states again without + // running a getter, and drop the event unless they are all live. + if !live_now(i, &desc, &held, at)? || !still_takes(i, win, ev, None)? || !holds_value(i, win, &held, at)? { + return Ok(Value::Undefined); + } + set_slot(i, ev, "id", Value::Number(at as f64))?; + take_event(i, win, nodes, ev, &event, None)?; + } + Ok(Value::Undefined) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Whether the element at `at` in the description `desc` ([`describe`]) is enabled and visible, and +/// every container above it too. +fn live_in(i: &Interp, desc: &Value, at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let Some(node) = nodes.get(k).and_then(Value::as_object) else { return Ok(false) }; + if !slot(i, node, "enabled")?.truthy() || !slot(i, node, "visible")?.truthy() { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + +/// Whether the control at `at` in `held` (the description's controls, in its order) and every +/// container above it, by the parents in `desc`, are enabled and visible as they are now, read +/// without running a getter ([`plain_state`]). +fn live_now(i: &Interp, desc: &Value, held: &[Value], at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let (Some(node), Some(o)) = (nodes.get(k).and_then(Value::as_object), held.get(k).and_then(Value::as_object)) else { + return Ok(false); + }; + if !plain_state(i, o, "enabled")? || !plain_state(i, o, "visible")? { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + +/// The state `name` of `o`, its own or the one its prototypes give, read without running a getter; +/// `false` when a getter gives it or nothing does. +fn plain_state(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.find_ordinary_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value.truthy(), + _ => false, + }) +} + +/// Whether the palette `win` still holds the control at `at` in `held`. +fn holds_value(i: &mut Interp, win: ObjId, held: &[Value], at: usize) -> JsResult { + match held.get(at).and_then(Value::as_object) { + Some(c) => holds(i, win, c), + None => Ok(false), + } +} + +/// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, +/// and a palette only while the host shows it under the id the event names and it has not been +/// hidden since it took the event. A getter or a handler run for the event may have closed or +/// hidden the palette, and shown it again. +fn still_takes(i: &mut Interp, win: ObjId, ev: ObjId, keep: Option<&[Value]>) -> JsResult { + if keep.is_some() { + return Ok(true); + } + if !slot(i, win, SHOWN)?.truthy() || number_slot(i, ev, HIDES)? != number_slot(i, win, HIDES)? { + return Ok(false); + } + let id = slot(i, ev, "palette")?; + Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) } fn host_fn(i: &mut Interp, name: &str) -> JsResult { @@ -1509,9 +2082,13 @@ fn set_showing(i: &mut Interp, showing: Option) { } } -/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). On a +/// palette: [`show_palette`]. fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { - let win = dialog_of(i, &this, "show")?; + let (win, palette) = this_window(i, &this, "show")?; + if palette { + return show_palette(i, win); + } match classes(i)?.showing { Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), @@ -1569,10 +2146,14 @@ fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. A `close()` that `onClose` calls belongs to -/// the close it decides on, so after `false` the dialog waits for the next event. +/// Runs `onClose`, during which a `close()` of the same palette does nothing. → false when it +/// returned `false`. A `close()` of a dialog that `onClose` calls belongs to the close it decides +/// on, so after `false` the dialog waits for the next event. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - let closes = !matches!(handler(i, win, "onClose")?, Some(Value::Bool(false))); + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let ran = handler(i, win, "onClose"); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + let closes = !matches!(ran?, Some(Value::Bool(false))); if !closes { set_slot(i, win, CLOSING, Value::Undefined)?; } @@ -1654,61 +2235,154 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { } return next(i, win); } - let id = match slot(i, ev, "id")? { - Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, - _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), - }; - let nodes = list_values(i, nodes)?; - let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { - return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); - }; - let value = slot(i, ev, "value")?; - match event.as_str() { - "click" => { - // A listener above the button that closed the dialog gives the result. - if !click_control(i, c, &kind)? && kind == "button" && matches!(slot(i, win, CLOSING)?, Value::Undefined) { - let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); - if is(2) { - set_slot(i, win, CLOSING, Value::Number(1.0))?; - } else if is(3) { - set_slot(i, win, CLOSING, Value::Number(2.0))?; - } - } - } - "change" => { - match kind.as_str() { - "edittext" => { - i.put(c, key("text"), value, true)?; - dispatch(i, c, "changing", "onChanging")?; - } - "slider" => { - i.put(c, key("value"), value, true)?; - dispatch(i, c, "changing", "onChanging")?; - } - _ => { - let n = match value { - Value::Number(n) => n, - _ => -1.0, - }; - // The index is into the items the person saw. - let shown = match arg(keep, 4).as_object() { - Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), - None => Value::Undefined, - }; - if !same(&slot(i, c, ITEMS)?, &shown) { - return Err(error(i, "show: a list's items changed before the person's choice was taken")); - } - set_slot(i, c, SELECTION, Value::Number(n))?; - } - } - dispatch(i, c, "change", "onChange")?; - } - _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), - } + take_event(i, win, nodes, ev, &event, Some(keep))?; next(i, win) }) } +/// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of +/// elements): the control takes it and its handlers and listeners run ([`dispatch_for`]). A +/// dialog's button without `onClick` and without a `click` listener of its own asks to close it +/// with 1 when it is the default element and 2 when it is the cancel element, which `keep` +/// (`show()`'s kept values) names; a palette has no `keep`. No handler or listener of a palette +/// runs once a getter, a setter or an earlier handler of the event closed the palette or took the +/// control out of it. +fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + let taker = if keep.is_none() { Some((win, ev, c)) } else { None }; + match event { + "click" => { + let Some(handled) = click_control_for(i, c, &kind, taker)? else { + return Ok(()); + }; + // A listener above the button that closed the dialog gives the result. + if !handled + && kind == "button" + && let Some(keep) = keep + && matches!(slot(i, win, CLOSING)?, Value::Undefined) + { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + if dispatch_for(i, c, "changing", "onChanging", taker)?.is_none() { + return Ok(()); + } + } + "slider" => { + i.put(c, key("value"), value, true)?; + if dispatch_for(i, c, "changing", "onChanging", taker)?.is_none() { + return Ok(()); + } + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + match keep { + // The index is into the items the person saw. + Some(keep) => { + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + } + // A palette's list may have changed while the event waited: the host gives + // the items the person saw and the list's revision then. + // The revision is read after the texts, whose getters may change the list. + None => { + let same = same_items(i, c, &slot(i, ev, "items")?)?; + let revised = match slot(i, ev, "revision")? { + Value::Number(r) => r != number_slot(i, c, REVISION)?, + _ => false, + }; + // An item's text getter may have closed the palette, and its `onClose` + // may have changed the list: the event is then dropped, not refused. + if !still_takes(i, win, ev, keep)? { + return Ok(()); + } + // A getter may have removed the list, which changes neither its + // revision nor the palette. + if !holds(i, win, c)? { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } + // An item's text getter may have disabled or hidden the list, or a + // group above it: the event is then dropped, as for a click. + if !live_up(i, win, c)? { + return Ok(()); + } + if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + return Err(error(i, "a palette's list changed before the person's choice was taken")); + } + } + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + // `onChanging` may have closed the palette. + dispatch_for(i, c, "change", "onChange", taker)?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + Ok(()) +} + +/// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True +/// when `seen` is not an array. A text a later item's getter changes after it was compared counts +/// as a change, and so does a text that is not a plain value of the item's own. +fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { + let Some(seen) = seen.as_object() else { return Ok(true) }; + let seen = list_values(i, seen)?; + let items = items_of(i, c)?; + if seen.len() != items.len() { + return Ok(false); + } + i.rooted(&items, |i| { + let mut texts = Vec::with_capacity(items.len()); + for (item, want) in items.iter().zip(&seen) { + let Some(item) = item.as_object() else { return Ok(false) }; + let text = get(i, item, "text")?; + let text = i.to_str(&text)?.to_rust_string(); + if text != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + texts.push((item, text)); + } + // Read again without running getters. Only a text held as a plain value can be checked so: + // one a getter, an inherited property or an object gives cannot, and counts as a change. + for (item, text) in texts { + let now = match i.get_own_property(item, &key("text"))? { + Some(Prop::Data { value, .. }) if !matches!(value, Value::Object(_)) => value, + _ => return Ok(false), + }; + if i.to_str(&now)?.to_rust_string() != text { + return Ok(false); + } + } + Ok(true) + }) +} + fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { let s = i.to_str(v)?; let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; @@ -1779,7 +2453,9 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { Some(Data::Number(n)) => *n, _ => 0.0, }; - return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + // Two finite numbers can add up to infinity; the sum is kept finite. + let end = |a: f64, b: f64| (a + b).clamp(-f64::MAX, f64::MAX); + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(end(n(0), n(2))), Data::Number(end(n(1), n(3)))])); } numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } @@ -1888,6 +2564,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { stack.push((kid, index, depth + 1)); } } + let in_palette = order.first().is_some_and(|(_, kind, _)| kind == "palette"); let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); i.temp_roots.extend(objects.iter().cloned()); let mut nodes = Vec::with_capacity(order.len()); @@ -1909,15 +2586,22 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; let text = text_of(i, &text_v, "a control's text")?; + // A palette is described as a dialog is; the host knows which it shows. + let shown_kind = if kind == "palette" { "dialog" } else { kind.as_str() }; let mut d: Vec<(String, Data)> = vec![ - ("kind".into(), Data::String(kind.clone())), + ("kind".into(), Data::String(shown_kind.to_string())), ("id".into(), Data::Number(number_slot(i, o, ID)?)), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), ]; - let enabled = get(i, o, "enabled")?.truthy(); - let visible = get(i, o, "visible")?.truthy(); + // In a palette, the states are read without running a getter, and a state that a getter + // gives counts as off, as when an event for the control is delivered ([`plain_state`]). + let (enabled, visible) = if in_palette { + (plain_state(i, o, "enabled")?, plain_state(i, o, "visible")?) + } else { + (get(i, o, "enabled")?.truthy(), get(i, o, "visible")?.truthy()) + }; // A control is enabled and visible only while every container above it is. let (above_enabled, above_visible) = if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; live.push((enabled && above_enabled, visible && above_visible)); @@ -1948,7 +2632,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("characters".into(), Data::Number(number_arg(i, &n, "show: a control's characters")?))); } } - if matches!(kind.as_str(), "dialog" | "group" | "panel") { + if is_container(kind) { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); let ac = get_kept(i, o, "alignChildren")?; @@ -2007,6 +2691,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { selected = number_slot(i, o, SELECTION)?; let sel = selection_index(i, o)?.filter(|n| *n < items.len()); d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + d.push(("revision".into(), Data::Number(number_slot(i, o, REVISION)?))); } _ => {} } @@ -2014,19 +2699,47 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { snapshot.push(listed); selections.push(selected); } - let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { - let given = get(i, win, name)?; - if let Some(n) = objects.iter().position(|o| same(o, &given)) { - return Ok(n as f64); + // The default and cancel elements are read before the states below, since their getters may + // also change a control's state. + let given_def = get(i, win, "defaultElement")?; + i.temp_roots.push(given_def.clone()); + let given_cancel = get(i, win, "cancelElement")?; + i.temp_roots.push(given_cancel.clone()); + // A palette's states are read again once every getter above has run, since one may have + // changed a control's state after it was read. + if in_palette { + let mut live: Vec<(bool, bool)> = Vec::with_capacity(order.len()); + for (n, (o, kind, parent)) in order.iter().enumerate() { + let (enabled, visible) = (plain_state(i, *o, "enabled")?, plain_state(i, *o, "visible")?); + let (above_enabled, above_visible) = + if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; + live.push((enabled && above_enabled, visible && above_visible)); + if let Some(entry) = names.get_mut(n) { + entry.0 = kind == "button" && enabled && visible && above_enabled && above_visible; + } + if let Some(Data::Object(d)) = nodes.get_mut(n) { + for (field, value) in d.iter_mut() { + match field.as_str() { + "enabled" => *value = Data::Bool(enabled), + "visible" => *value = Data::Bool(visible), + _ => {} + } + } + } + } + } + let target = |given: &Value, word: &str| -> f64 { + if let Some(n) = objects.iter().position(|o| same(o, given)) { + return n as f64; } if !matches!(given, Value::Undefined | Value::Null) { - return Ok(-1.0); + return -1.0; } let button = |by_name: bool| names.iter().position(|(c, n, t)| *c && (if by_name { n } else { t }).to_lowercase() == word); - Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64) }; - let def = target(i, "defaultElement", "ok")?; - let cancel = target(i, "cancelElement", "cancel")?; + let def = target(&given_def, "ok"); + let cancel = target(&given_cancel, "cancel"); if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? || !texts_unchanged(i, &item_texts)? { return Ok(None); } @@ -2079,14 +2792,22 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul radio_get, radio_set, showing: None, + palettes: Vec::new(), + taking: false, dispatching: Vec::new(), above: Vec::new(), next_id: 0.0, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; - // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; + i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; + // The run of a palette's handler calls the global one through `this`, under a name that is + // not an identifier: a script can neither replace nor delete it nor declare the name, so + // the palettes still take events after a script assigns to `Window`. let global = i.global; + i.define(global, key(PALETTE_EVENT_GLOBAL), Prop::Data { value: Value::Object(event), flags: 0 })?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. for name in ["alert", "confirm", "prompt"] { if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? && i.is_callable(&value) @@ -2104,12 +2825,14 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; + method(i, window_proto, "update", update, 0)?; pausable_method(i, window_proto, "show", show, 0)?; method(i, control_proto, "removeAll", remove_all, 0)?; method(i, control_proto, "find", find, 1)?; method(i, control_proto, "notify", notify, 1)?; method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; + method(i, control_proto, "update", control_update, 0)?; method(i, event_proto, "stopPropagation", event_stop, 0)?; method(i, event_proto, "preventDefault", nothing, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index dafe4dabc8..11bde4ca26 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -308,8 +308,10 @@ fn a_stop_from_end_when_show_fails_ends_the_run() { #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ - ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), - ("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('window')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('window { b: Button {} }')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('palette')", "Window: this host shows no palettes"), + ("new Window('palette { b: Button {} }')", "Window: this host shows no palettes"), ("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), @@ -706,6 +708,824 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() { assert_eq!(seen.borrow().ends, vec![(1.0, true)]); } +/// What a palette host was asked: each call's name and its palette id (0 for none). +type Calls = Rc>>; + +/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives +/// the events in `events`, in order, then `null`. +fn palette_realm(events: Vec) -> (Realm, Calls) { + palette_realm_with(events, Vec::new(), Vec::new()) +} + +/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, +/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the +/// answers in `draws`, in order, then `false`. +fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let calls: Calls = Rc::default(); + let events = Rc::new(RefCell::new(VecDeque::from(events))); + let id_of = |args: &[Data], at: usize| match args.get(at) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + let record = |name: &'static str, at: usize| -> HostFunction { + let c = calls.clone(); + Rc::new(move |args| { + c.borrow_mut().push((name.to_string(), id_of(&args, at))); + Ok(Data::Undefined) + }) + }; + let c = calls.clone(); + let show: HostFunction = Rc::new(move |args| { + let given = id_of(&args, 1); + let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 }; + c.borrow_mut().push(("paletteShow".into(), id)); + Ok(Data::Number(id)) + }); + let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let taken = Rc::new(RefCell::new(VecDeque::from(taken))); + let c = calls.clone(); + let left = taken.clone(); + let take: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteTake".into(), 0.0)); + Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let c = calls.clone(); + let pending: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("palettePending".into(), 0.0)); + Ok(Data::Bool(!taken.borrow().is_empty())) + }); + let draws = RefCell::new(VecDeque::from(draws)); + let c = calls.clone(); + let draw: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteDraw".into(), 0.0)); + Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false))) + }); + let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); + let items = vec![ + ("open".into(), HostItem::Function(none.clone())), + ("wait".into(), HostItem::Function(none.clone())), + ("end".into(), HostItem::Function(none)), + ("palette".into(), HostItem::Function(record("palette", 0))), + ("paletteShow".into(), HostItem::Function(show)), + ("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))), + ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), + ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), + ("paletteEvent".into(), HostItem::Function(event)), + ("paletteTake".into(), HostItem::Function(take)), + ("palettePending".into(), HostItem::Function(pending)), + ("paletteDraw".into(), HostItem::Function(draw)), + ]; + r.define_script_ui(items).unwrap(); + (r, calls) +} + +fn palette_event(palette: f64, event: Data) -> Data { + let Data::Object(mut fields) = event else { return Data::Null }; + fields.push(("palette".into(), Data::Number(palette))); + Data::Object(fields) +} + +fn names(calls: &Calls) -> Vec { + calls.borrow().iter().map(|(n, _)| n.clone()).collect() +} + +#[test] +fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]); + let made = r + .run( + "var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \ + var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \ + b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \ + t.onChange = function () { log.push('change ' + t.text); }; String(p.show())", + ) + .unwrap(); + assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting"); + assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(); + assert_eq!(updates(&calls), 1, "the handlers give the host nothing"); + r.refresh_script_ui().unwrap(); + assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls"); + assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); +} + +#[test] +fn a_palette_click_runs_no_handler_once_its_button_was_taken_out_of_the_palette() { + // The button's onClick getter takes it out of the palette and gives a function. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + Object.defineProperty(b, 'onClick', {get: function () { p.remove(b); return function () { log.push('ran'); }; }}); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "the getter's function does not run"); + // A capturing listener on the palette takes the button out before the button's own turn. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + b.onClick = function () { log.push('click'); }; b.addEventListener('click', function () { log.push('listener'); }); \ + p.addEventListener('click', function () { log.push('capture'); p.remove(b); }, true); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("capture".into())); +} + +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(3))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); var label = p.add('statictext', undefined, 'L'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_after_its_button_disables_the_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + var label = p.add('statictext', undefined, 'L'); \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } + // A getter that gives the button's state, and disables it while it says the button is visible. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var armed = false, log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show(); \ + Object.defineProperty(b, 'visible', {get: function () { b.enabled = false; return true; }}); b.enabled = true;", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into())); + // Without a getter that disables anything, the same click runs its handler. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("click".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]); + // The first item's getter gives `label`, which the second item's getter changes after the + // first was compared. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; var label = 'a', armed = false; \ + l.onChange = function () { got.push(String(l.selection)); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { return label; }}); \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (armed) { label = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + for arm in ["false", "true"] { + let e = r.run(&format!("armed = {arm}; label = 'a'; try {{ Window.__vcPaletteEvent(); 'none'; }} catch (e) {{ e.message; }}")).unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "armed {arm}"); + } + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn update_asks_the_host_once_more_after_a_handler_s_exception() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(thrown, JsValue::String("broken".into())); + let asked: Vec = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect(); + assert_eq!(asked, ["palettePending", "paletteTake", "palettePending"], "the host learns the event's handlers ended"); +} + +#[test] +fn closing_a_palette_runs_on_close_which_can_keep_it_open() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \ + var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible"); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible"); + assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +fn count(calls: &Calls, name: &str) -> usize { + calls.borrow().iter().filter(|(n, _)| n == name).count() +} + +#[test] +fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]); + r.start( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \ + for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }", + ) + .unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn"); + assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws"); +} + +#[test] +fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() { + let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]); + r.run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start("Window.__vcPaletteEvent();").unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn"); + assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends"); +} + +#[test] +fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \ + cancel.onClick = function () { stopped = true; }; p.show(); \ + var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); + assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits"); + assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event"); + let order = names(&calls); + let take = order.iter().position(|n| n == "paletteTake"); + let last_update = order.iter().rposition(|n| n == "paletteUpdate"); + assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken"); +} + +#[test] +fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \ + p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once"); + assert_eq!(count(&calls, "paletteTake"), 1); +} + +#[test] +fn update_throws_for_a_window_that_is_not_showing() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \ + ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into())); + let (mut r, _) = palette_realm(Vec::new()); + let hidden = r + .run( + "var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \ + p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()", + ) + .unwrap(); + assert_eq!(hidden, JsValue::String("before show,hidden".into())); +} + +#[test] +fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \ + [w.show(), done].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into())); +} + +#[test] +fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start( + "var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \ + p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \ + try { b.update(); } catch (e) { log.push(e.name); } log.join()", + ) + .unwrap(); + let log = loop { + if let Progress::Done(v) = r.advance(1_000_000).unwrap() { + break v; + } + }; + assert_eq!(log, JsValue::String("shown,hidden,TypeError".into())); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows"); +} + +#[test] +fn a_palette_list_change_after_its_items_changed_throws() { + let seen = |index: f64| { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + // The two items the list was made with. + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) + }; + let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap(); + let message = "a palette's list changed before the person's choice was taken"; + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts"); + r.run("l.removeAll(); l.add('item', 'a');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "fewer items"); + r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "new items with the same texts"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); +} + +/// A palette list change as the host gives it: the item index, the items the person saw (`a` and +/// `b`) and the revision of a list made with those two items. +fn seen_list_change(index: f64) -> Data { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) +} + +#[test] +fn a_palette_list_change_after_an_item_s_text_changed_throws() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("l.items[1].text = 'z';").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "the same items, one with another text"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read turns the getter back into a plain text and + // replaces the items with ones of the same texts, so only the list's revision tells them apart. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; var first = l.items[0]; \ + Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \ + Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \ + l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); +} + +#[test] +fn a_palette_event_finds_its_control_by_its_id() { + let of = |id: usize, element: f64| { + let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null }; + fields.push(("element".into(), Data::Number(element))); + Data::Object(fields) + }; + // The palette is element 1, the group 2 and the button 3. The host's indexes are stale: 1 is + // the group, and after the group is removed, 2 is past the end. + let (mut r, _) = palette_realm(vec![of(1, 3.0), of(2, 3.0), of(1, 99.0)]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control with its id"); + r.run("p.remove(g); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0), "the click follows the control after a control before it is removed"); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control with the id"); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() { + // The palette is element 1, the label 2 and the button 3. + let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") }; + fields.push(("element".into(), Data::Number(3.0))); + let (mut r, _) = palette_realm(vec![Data::Object(fields)]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which removes the button. + let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap(); + assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which closes the palette. + r.run("armed = true; Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \ + b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \ + p.addEventListener('click', function () { later++; }); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); + assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close"); +} + +#[test] +fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read closes the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() { + for disable in ["l.enabled = false;", "l.visible = false;"] { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person + // saw, disables the list. + r.run(&format!( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \ + p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "{disable}"); + assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() { + // Whichever read of `value` disables the box, the click neither sets it nor runs its handler. + for read in 1..=4 { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run(&format!( + "var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \ + Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \ + set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;" + )) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap(); + assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}"); + } +} + +#[test] +fn a_hidden_palette_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); p.hide(); \ + Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read"); + assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.hide(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!( + r.run("[heard, clicks, p.visible].join()").unwrap(), + JsValue::String("1,0,true".into()), + "a click the palette took before a hide is not its click after the palette shows again" + ); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click"); +} + +#[test] +fn a_palette_refresh_that_fails_reports_no_rejection() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \ + p.show(); Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled"); + assert!(r.refresh_script_ui().is_err()); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection"); +} + +#[test] +fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person saw, + // removes the list from the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.remove(l); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + // The second read of the second item's text, which compares it with the items the person saw, + // changes the first item's text, which that comparison already took. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn an_add_whose_palette_update_a_getter_breaks_still_returns_the_control() { + let (mut r, _) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'idle'; }}); \ + var list = p.add('listbox', undefined, ['a']); p.show();", + ) + .unwrap(); + let added = r + .run( + "armed = true; var c, d, m = []; try { c = p.add('button', undefined, 'New'); } catch (e) { m.push(e.message); } \ + try { d = list.add('item', 'b'); } catch (e) { m.push(e.message); } \ + try { list.remove(0); } catch (e) { m.push(e.message); } \ + try { p.remove(c); } catch (e) { m.push(e.message); } armed = false; \ + [String(c && c.text), String(d && d.text), list.items.length, p.children.length, m.length].join()", + ) + .unwrap(); + assert_eq!(added, JsValue::String("New,b,1,2,0".into()), "each change is made once and gives its result"); + // A later error is at its own line, not at the getter's. + let e = r.run("armed = true;\np.add('button', undefined, 'Other');\narmed = false;\nthrow new Error('later');").unwrap_err(); + assert_eq!((e.message.contains("later"), e.line), (true, 4), "{e:?}"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var ran = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.resolve().then(function () { ran++; b.text = 'Done'; }); Promise.reject(new Error('late')); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again after the jobs ran"); + assert_eq!(r.unhandled_rejections().len(), 1, "the job's rejection is the run's"); + assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh"); +} + +#[test] +fn a_run_s_rejection_that_a_palette_getter_handles_during_the_refresh_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false, caught = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + early.catch(function () { caught++; }); } return 'P'; }}); \ + p.show(); var early = Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (1, 1), "the run left the rejection unhandled"); + r.refresh_script_ui().unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "the getter gave it a handler"); +} + +#[test] +fn a_rejection_a_palette_getter_makes_while_a_failed_run_is_refreshed_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.reject('late'); } return 'P'; }}); p.show();", + ) + .unwrap(); + assert!(r.run("armed = true; throw new Error('failed');").is_err()); + r.refresh_script_ui_after_error(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed run reports no rejection"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var n = 0, reads = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); \ + Object.defineProperty(p, 'text', {get: function () { reads++; \ + Promise.resolve().then(function () { n++; }); return 'Title'; }});", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again once after the jobs run"); + assert_eq!(r.run("reads > 0 && n === reads").unwrap(), JsValue::Bool(true), "every getter read's job runs before the refresh returns"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_during_refresh_leave_waiting_clicks_queued() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.add_es2015(); + r.run( + "var clicks = 0, jobs = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { \ + Promise.resolve().then(function () { jobs++; p.update(); }); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteTake"), 0, "the refresh leaves the waiting click queued"); + assert_eq!(r.run("jobs > 0 && clicks === 0").unwrap(), JsValue::Bool(true), "the promise jobs run without dispatching the click"); + assert_eq!(r.run("armed = false; p.update(); clicks").unwrap(), JsValue::Number(1.0), "a later update takes the waiting click"); + assert_eq!(count(&calls, "paletteTake"), 1, "the refresh restores the event-taking guard"); +} + +#[test] +fn an_object_on_close_throws_stays_whole_while_the_close_ends() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, close())]); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.onClose = function () { throw {tag: 'kept'}; }; p.show();").unwrap(); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let thrown = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { String(e.tag); }"); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(thrown.unwrap(), JsValue::String("kept".into())); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text closes the palette, and its `onClose` adds an item. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + p.onClose = function () { l.add('item', 'c'); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error"); + assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into())); +} + +#[test] +fn a_palette_s_visible_follows_hide_and_show() { + let (mut r, _) = palette_realm(Vec::new()); + let v = r + .run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()") + .unwrap(); + assert_eq!(v, JsValue::String("true,false,true".into())); +} + +#[test] +fn a_close_inside_a_dialog_s_on_close_does_nothing() { + let (mut r, seen, _) = realm(vec![close(), click(13)]); + let source = format!( + "{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel"); + assert_eq!(seen.borrow().ends, vec![(2.0, true)]); +} + +#[test] +fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()") + .unwrap(); + let described = nodes(&seen.borrow().descriptions[0]); + let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]); + assert_eq!(field(&described[1], "bounds"), &want); +} + +#[test] +fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap(); + let shows: Vec = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect(); + assert_eq!(shows, [1.0, 1.0, 1.0]); +} + #[test] fn findelement_items_and_selection_follow_the_list() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1f0c290191..618c9d7529 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,6 +261,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index b3b5de36a4..a093ecc9c0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use vectorcraft_geom::Vec2; + use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, @@ -19,6 +21,37 @@ fn brushed(b: Option, reach: f64) -> Option { if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } } +/// Can the patch shade its own outline without folding across it? The differences of adjacent +/// tensor control points bound each directional derivative in a convex cone. If every pair of +/// derivatives has the same strict orientation, averaging them along any segment keeps them +/// independent, so distinct parameter points cannot map to the same point. +fn unfolded_patch(points: [(f32, f32); 12]) -> bool { + let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y))); + let top = [p[0], p[11], p[10], p[9]]; + let bottom = [p[3], p[4], p[5], p[6]]; + let left = [p[0], p[1], p[2], p[3]]; + let right = [p[9], p[8], p[7], p[6]]; + // Raise the linear blending terms of the Coons surface to cubic degree in each direction. + let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| { + let v = row as f64 / 3.0; + std::array::from_fn(|col| { + let u = col as f64 / 3.0; + let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v; + top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear + }) + }); + let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col])); + let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col])); + let orientation = du[0][0].cross(dv[0][0]).signum(); + du.into_iter().flatten().all(|u| { + dv.iter().flatten().all(|v| { + let cross = u.cross(*v) * orientation; + // Keep near-parallel directions on the existing clipped path through PDF quantization. + cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2() + }) + }) +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -542,7 +575,7 @@ impl Exporter<'_> { } } - /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads /// instead banded, left seams between them, and made files with many meshes very large. @@ -560,7 +593,6 @@ impl Exporter<'_> { if !writable(s, Affine::IDENTITY, bounds) { return false; } - let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false }; let page: Vec = m.points.iter().map(|p| self.page_color(&p.color)).collect(); let mixed = page.windows(2).any(|w| w[0].model() != w[1].model()); let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. })); @@ -584,6 +616,14 @@ impl Exporter<'_> { patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] }); } } + // An unfolded single patch shades its own outline. Filling that exact outline makes some + // readers antialias it twice and leave seams where patches touch. Keep the outline for + // folded geometry and for meshes with more than one patch, which can overlap themselves. + let bounds_path = match patches.as_slice() { + [patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)), + _ => None, + }; + let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false }; let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false }; s.set_stroke(None); s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index b2e8ecb2f6..b36926da21 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -2,12 +2,16 @@ //! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small //! flat-coloured paths that band, show seams and make the file large. +use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction}; +use craft::pdf::syntax::object::{Name, Object}; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use vectorcraft_testkit::raster::{assert_similar, render_artboard}; +use super::import_fidelity::stream; use crate::*; /// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured @@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) { (meshes, paths) } +fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document { + use std::fmt::Write as _; + let mut data = String::new(); + for boundary in boundaries { + data.push_str("00"); // Every patch supplies all its vertices. + for (x, y) in boundary { + write!(data, "{x:02X}{y:02X}").unwrap(); + } + data.push_str(&"28465A".repeat(4)); + } + data.push('>'); + let shading = stream( + "/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \ + /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode", + &data, + ); + let page = PdfPage { + resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)), + ..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q") + }; + let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap(); + assert_eq!(kinds(&imported).0, boundaries.len()); + imported +} + +fn has_curved_outline(bytes: &[u8]) -> bool { + let output = crate::pages::open(bytes, None).unwrap(); + let pages = output.pages(); + let has_curve = |content: &[u8]| { + let mut ops = TypedIter::new(content); + while let Some(op) = ops.next() { + if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) { + return true; + } + } + false + }; + if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) { + return true; + } + output.objects().into_iter().any(|object| match object { + Object::Stream(form) if form.dict().get::>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => { + has_curve(&form.decoded().unwrap()) + } + _ => false, + }) +} + +#[test] +fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() { + // The same cubic, in opposite directions, is the two patches' inner edge. + let imported = import_patches(&[ + [(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)], + [(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)], + ]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself"); + let reimported = import(&bytes).unwrap(); + assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings"); + assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01); +} + +#[test] +fn folded_pdf_mesh_still_uses_its_outline() { + let imported = + import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline"); +} + #[test] fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() { let d = doc(rgb, 1.0); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c9c0e89521..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -42,6 +42,7 @@ //! `"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)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4358cc180d..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6a40857796..a929c47d44 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -235,7 +235,7 @@ features! { Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, - ScriptuiPalette "scriptui.palette" HostOnly, + ScriptuiPalette "scriptui.palette" Dialogs, ScriptuiWindow "scriptui.window" Dialogs, SelectTool "selectTool" Dom, Socket "socket" HostOnly, diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9075c53517..868752339a 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; @@ -120,8 +121,8 @@ pub enum Need { MenuCommands, /// Dialogs and windows of its own. Dialogs, - /// Features only the reference app has (palettes, messages to other apps, network - /// connections, native code, actions). + /// Features only the reference app has (messages to other apps, network connections, native + /// code, actions). HostOnly, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 9aee330bd4..eec8e0e03f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -2163,6 +2163,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { assert_eq!(notify(five, &Limits::default()).0, Vec::::new()); } +#[test] +fn palettes_need_dialogs() { + let r = report("#targetengine tools\nvar w = new Window('palette');\nw.show();\n"); + assert_eq!(r.needs, [Need::Language, Need::Dialogs]); +} + #[test] fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 78ff31af5f..80d1230994 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -100,8 +100,11 @@ pub struct FontDb { colours: Mutex, /// The installed fonts: the system font scan's faces, found by any of their names /// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find - /// never depends on what ran before them. + /// never depends on what ran before them. The bundled faces join it on the first call of + /// [`FontDb::catalog`], so its faces are read through that call. catalog: Arc, + /// The bundled faces were added to [`Self::catalog`]. + bundled_cataloged: std::sync::Once, /// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces, /// so no family name, font menu, fallback or PostScript name lookup finds them. pub(super) file_faces: RwLock, @@ -387,6 +390,28 @@ mod race_tests { } } +#[cfg(all(test, feature = "bundled-fonts"))] +mod bundled_catalog_tests { + use super::*; + + fn bundled_in_catalog(catalog: &Catalog) -> usize { + catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled).count() + } + + #[test] + fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() { + let db = FontDb::with_font_dirs(Vec::new()); + assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start"); + assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog"); + // A lookup that only the catalog answers finds a bundled face. + assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string()))); + let added = bundled_in_catalog(&db.catalog); + assert!(added > 0, "the first read of the catalog adds the bundled fonts"); + assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family"); + assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time"); + } +} + #[cfg(test)] mod image_cache_tests { use super::*; diff --git a/crates/text/src/fontdb/added.rs b/crates/text/src/fontdb/added.rs index 2b0dc8e2e0..00d491924f 100644 --- a/crates/text/src/fontdb/added.rs +++ b/crates/text/src/fontdb/added.rs @@ -31,7 +31,7 @@ impl FontDb { /// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are /// never listed. Empty on wasm, which has no installed fonts. pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded { - let faces = self.catalog.faces(); + let faces = self.catalog().faces(); // Each file's creation time once for all its faces (a collection or a variable font's // named instances share one). let mut created: HashMap<&Path, Option> = HashMap::new(); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 474198cad6..b65dbab4f2 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -20,6 +20,14 @@ static NEXT_ID: AtomicU64 = AtomicU64::new(0); /// [`FontDb::global`]. static GLOBAL: std::sync::OnceLock = std::sync::OnceLock::new(); +/// The fonts a database starts with: the bundled fonts first, then explicitly supplied craft-fonts +/// faces: Japanese (Mincho first), Arabic, Thai, then remaining faces in manifest order. Existing +/// script fallback priorities stay ahead of the additional families users can now pick by name. +fn bundled_fonts() -> impl Iterator { + let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes); + BUNDLED.iter().copied().chain(craft) +} + impl FontDb { /// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders, /// read with their subfolders, and font files) and nothing else. @@ -44,15 +52,7 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] catalog.set_confined_dirs(confined_font_dirs()); let mut faces = Vec::new(); - // Bundled fonts first, then explicitly supplied craft-fonts faces: Japanese (Mincho - // first), Arabic, Thai, then remaining faces in manifest order. Existing script fallback - // priorities stay ahead of the additional families users can now pick by name. - let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes); - for data in BUNDLED.iter().copied().chain(craft) { - // Font pickers list the catalog's families: the fonts the app carries are in it as bundled faces. - if let Err(e) = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) { - log::warn!("a bundled font is not in the font catalog: {e}"); - } + for data in bundled_fonts() { for (i, spec) in enumerate_faces(data) { if let Some(f) = make_face(FontBytes::Static(data), i, spec, None) { faces.push(Arc::new(f)); @@ -65,6 +65,7 @@ impl FontDb { images: Mutex::new(GlyphCache::default()), colours: Mutex::new(GlyphCache::default()), catalog: Arc::new(catalog), + bundled_cataloged: std::sync::Once::new(), file_faces: RwLock::new(super::FileFaces::default()), canonical_cache: Mutex::new(CanonicalNames::new()), #[cfg(not(target_arch = "wasm32"))] @@ -119,7 +120,20 @@ impl FontDb { /// The installed fonts this database finds by name, shared with the framework's font menus and /// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]). + /// + /// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers + /// list them. A run that never looks a font up in the catalog, such as exporting a file without + /// type, does not hold the catalog's copies of their bytes. + // The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use + // can go once the catalog takes static bytes without copying them (craft-libs#4888). pub fn catalog(&self) -> &Arc { + self.bundled_cataloged.call_once(|| { + for data in bundled_fonts() { + if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) { + log::warn!("a bundled font is not in the font catalog: {e}"); + } + } + }); &self.catalog } @@ -164,7 +178,7 @@ impl FontDb { /// [`FontDb::families`], shared: cheap to call every frame. pub fn family_list(&self) -> Arc<[String]> { // The catalog's list is the same `Arc` until it rescans (here or in its watch). - let installed = self.catalog.families(); + let installed = self.catalog().families(); let mut cache = self.family_cache.lock().unwrap_or_else(|e| e.into_inner()); if let Some((from, list)) = cache.as_ref() && Arc::ptr_eq(from, &installed) @@ -238,7 +252,7 @@ impl FontDb { } // An installed family's, from its names in other languages, as a loaded face's is chosen // (every face of a family has the same names: one is enough). - let native = self.catalog.resolve(&family, "").and_then(|(f, _)| { + let native = self.catalog().resolve(&family, "").and_then(|(f, _)| { let names: Vec<(Option, String)> = f.localized_families.into_iter().map(|n| (n.language, n.name)).collect(); pick_native_label(&f.family, &names) }); @@ -256,7 +270,7 @@ impl FontDb { v.push((f.italic, f.weight, f.style.clone())); } } - for f in self.catalog.styles(family) { + for f in self.catalog().styles(family) { if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&f.style)) { v.push((f.italic, f.weight, f.style)); } @@ -282,7 +296,7 @@ impl FontDb { for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { consider(&mut best, f.weight, f.italic, &f.style); } - for f in self.catalog.styles(family) { + for f in self.catalog().styles(family) { consider(&mut best, f.weight, f.italic, &f.style); } best.map(|(_, style)| style) @@ -347,7 +361,7 @@ impl FontDb { /// folders, any other waits for that scan to finish, as every catalog lookup does. #[cfg(any(test, feature = "test-fonts"))] pub(crate) fn ensure_catalog(&self) { - let _ = self.catalog.families(); + let _ = self.catalog().families(); } /// Catalog the installed fonts on a background thread, so the first lookup by family name @@ -370,14 +384,14 @@ impl FontDb { let _change = self.catalog.is_ready().then(crate::test_fonts::font_change); // The first scan, or a rescan once it is done (never both at once). The count is of the installed faces: the // catalog's less the bundled faces no installed file also has. - let cataloged = self.catalog.rescan(); - let bundled_only = self.catalog.faces().iter().filter(|f| f.source == Source::Bundled && self.catalog.versions(f).len() == 1).count(); + let catalog = self.catalog(); + let cataloged = catalog.rescan(); + let bundled_only = catalog.faces().iter().filter(|f| f.source == Source::Bundled && catalog.versions(f).len() == 1).count(); let n = cataloged.saturating_sub(bundled_only); // Files may have been installed since: other versions are looked for again, in the catalog // the rescan published. A version lookup made during the scan read the previous one. self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); - let installed: std::collections::HashSet = - self.catalog.faces().iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect(); + let installed: std::collections::HashSet = catalog.faces().iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect(); // Faces loaded from a file this scan did not catalog, as a face or a version of one (the font was removed, or its folder // is no longer read) are dropped with their outlines. A family with no face left and no // cataloged file leaves the lists, and type set in it resolves to the fallback font. A face diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs index 05ec64bccb..01b04f1a99 100644 --- a/crates/text/src/fontdb/installed.rs +++ b/crates/text/src/fontdb/installed.rs @@ -30,13 +30,12 @@ impl FontDb { // 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 + let catalog = self.catalog(); + let cataloged: Vec<(String, String, PathBuf)> = 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)?; + let path = 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(); diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index f1a024d020..671b62ddad 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -73,7 +73,7 @@ impl FontDb { } #[cfg(not(target_arch = "wasm32"))] { - let faces = self.catalog.styles(family); + let faces = self.catalog().styles(family); let off = |f: &craft::font_catalog::FaceInfo| (f.italic, (f.weight - 400.0).abs()); let nearest = faces.iter().min_by(|a, b| { let ((ai, aw), (bi, bw)) = (off(a), off(b)); @@ -89,7 +89,7 @@ impl FontDb { /// Is `family` an installed family's own name (any ASCII case)? fn is_installed(&self, family: &str) -> bool { - self.catalog.family(family).is_some_and(|f| f.eq_ignore_ascii_case(family)) + self.catalog().family(family).is_some_and(|f| f.eq_ignore_ascii_case(family)) } /// The family's own name and the style for a name given in a document: any of a family's @@ -124,7 +124,7 @@ impl FontDb { self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect(); // The installed face the name gives: by a family name in its family, by a legacy family // name with its legacy style, by a full or PostScript name whatever the style. - let installed = self.catalog.resolve(family, style); + let installed = self.catalog().resolve(family, style); let ns = norm(style); // A family and style split from a PostScript name by an importer that didn't have the font // (`Honoka-Mincho` → Honoka, Mincho): once it is installed, the face of that PostScript @@ -147,7 +147,7 @@ impl FontDb { if let Some(a) = found.iter().find(|a| a.style.is_none()) { return (a.family.clone(), style.to_string()); } - if let Some(installed_family) = self.catalog.family(family) { + if let Some(installed_family) = self.catalog().family(family) { return (installed_family, style.to_string()); } if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) { @@ -278,7 +278,7 @@ impl FontDb { let key = norm(name); let mut families: Vec = vec![first.family.clone()]; let named = |f: &&FaceInfo| f.postscript_name.as_deref().is_some_and(|p| norm(p) == key); - for f in self.catalog.faces().iter().filter(named) { + for f in self.catalog().faces().iter().filter(named) { if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|known| known.eq_ignore_ascii_case(&f.family)) { families.push(f.family.clone()); } @@ -303,13 +303,14 @@ impl FontDb { /// The cataloged face of PostScript name `name`: an installed face before a bundled face of another family with the /// same name, as the installed faces alone answered before the bundled ones were cataloged. fn cataloged_postscript(&self, name: &str) -> Option { - let face = self.catalog.by_postscript_name(name)?; + let catalog = self.catalog(); + let face = catalog.by_postscript_name(name)?; if face.source != Source::Bundled { return Some(face); } let key = norm(name); let named = |f: &&FaceInfo| f.source != Source::Bundled && f.postscript_name.as_deref().is_some_and(|p| norm(p) == key); - Some(self.catalog.faces().iter().find(named).cloned().unwrap_or(face)) + Some(catalog.faces().iter().find(named).cloned().unwrap_or(face)) } /// Load the files of the installed `family`, every cataloged version of its faces included, @@ -317,8 +318,9 @@ impl FontDb { /// thread meanwhile. #[cfg(not(target_arch = "wasm32"))] fn load_cataloged(&self, family: &str) -> bool { - let faces = self.catalog.styles(family); - let mut paths: Vec = faces.iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect(); + let catalog = self.catalog(); + let faces = catalog.styles(family); + let mut paths: Vec = faces.iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect(); paths.sort(); paths.dedup(); let files = paths.into_iter().flat_map(|p| font_files(&p).into_iter().map(move |data| (data, Some(p.clone())))); @@ -403,7 +405,7 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] fn is_cataloged(&self, family: &str, style: &str) -> bool { let ns = norm(style); - self.catalog.styles(family).iter().any(|f| norm(&f.style) == ns) + self.catalog().styles(family).iter().any(|f| norm(&f.style) == ns) } /// The loaded face with [`FontFace::id`] `id` (the face a laid-out glyph came from), an @@ -680,7 +682,7 @@ impl FontDb { } sys.file_searches += 1; } - let mut paths: Vec = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect(); + let mut paths: Vec = self.catalog().faces().iter().filter_map(|f| f.path.clone()).collect(); paths.sort(); paths.dedup(); for p in paths { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..5adcecd679 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 442ddaffbf..0448534fda 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -149,6 +149,7 @@ impl VectorcraftApp { spelling: Default::default(), text_nodes: Default::default(), momentary: None, + momentary_keys: vec![], hand: None, zoom_tool: None, selection_box: None, @@ -586,15 +587,23 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); + // A palette event whose run starts on the next frame. While a run goes on, the block below + // asks for its frames, and a run that waits for the person goes on at their next input. An + // event that waits for an open undo group asks for no frame; the pass that ends the group + // asks for the next one (`ui_frame`). + if crate::script_palettes::can_start(self) { + ctx.request_repaint(); + } if self.session.script_running() && !crate::script_runs::waiting_for_print(self) && !self.session.script_waiting() && self.session.script_dialog().is_none() + && self.session.script_window().is_none() && self.session.script_picker().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. A // script at a file dialog goes on when the dialog answers, and `file_asks::poll` looks - // for that. + // for that. A script at its ScriptUI dialog goes on when the dialog gives it an event. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), @@ -801,6 +810,7 @@ impl VectorcraftApp { panels::learn::locate::tidy(self, &ctx); crate::doc_windows::show(self, ui); export_progress::show(self, ui); + crate::script_palettes::show(self, &ctx); // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); let drawn_document = self.session.active().map(|st| (st.uid, st.revision)); @@ -821,6 +831,10 @@ impl VectorcraftApp { toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } menus::native::sync(self, &ctx); + // A palette event that waited for an undo group this pass ended starts its run next frame. + if crate::script_palettes::can_start(self) { + ctx.request_repaint(); + } // Only a field's commit in the pass of the press is the one it made. self.canvas.committed_preview = false; self.drop_formats_after_egui_copy(&ctx); diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 2389373b4c..fc1694736a 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -44,6 +44,7 @@ impl VectorcraftApp { }); self.finish_captures(finished); let settle = settle_ms(ctx.global_style().animation_time); + let mut handled = 0usize; while let Some(req) = self.deferred_control.take().or_else(|| self.channel.as_mut().and_then(ControlChannel::next_request)) { // A request held past its deadline is answered as one still queued then. if req.deadline.is_some_and(|deadline| self.instant() >= deadline) { @@ -71,6 +72,7 @@ impl VectorcraftApp { // Guarded per request: a panic must not stop the requests behind it. let answer = file_access::confine(roots.as_ref(), || vectorcraft_engine::guard::catch_panic(|| control::handle(self, ctx, &req))); self.ui.answering_control = false; + handled += 1; let reply = match answer { Ok(reply) => reply, Err(msg) => { @@ -92,6 +94,10 @@ impl VectorcraftApp { host.paint_while_hidden(); } ctx.request_repaint(); + } else if handled > 0 && self.session.script_running() { + // A request may have answered the dialog a run waits at, which the app idles for: the + // next frame takes the answer and the run's next slice. + ctx.request_repaint(); } self.answer_pointer_waits(ctx); } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dcec22bff..d2809d5846 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -81,6 +81,9 @@ pub struct CanvasCache { /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, + /// The keys down when the held momentary command started; empty while none is held or when none started it. + /// Temporary, with `tool_adapter::end_missed_momentary` (craft-libs#5056). + pub momentary_keys: Vec, pub hand: Option, /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. pub zoom_tool: Option, diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index abe7c5a6db..9993669339 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -835,3 +835,65 @@ pub(in crate::canvas) fn live_paint_gap_overlays(app: &mut VectorcraftApp) -> Ve }; gaps.to_vec() } + +/// Teeth View → Show Curvature Comb draws on each segment. +const COMB_SAMPLES: usize = 16; +/// The comb's length at zoom 1, in screen points squared: a curve that bends with a radius of +/// 100 screen points has teeth 20 screen points long at any zoom. VectorCraft's own value. +const COMB_SCALE: f64 = 2000.0; + +/// View → Show Curvature Comb: on each selected path, and each path of a selected compound path, a +/// tooth along the normal at evenly spaced points of every segment, as long as the curvature there, +/// and a line through the teeth's tips, in the path's layer color. At most +/// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their +/// number of segments, so a large selection gets fewer teeth everywhere. +pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, comb_closes, curvature_comb}; + let Some(st) = app.session.active() else { return vec![] }; + if !(zoom.is_finite() && zoom > 0.0) { + return vec![]; + } + let scale = COMB_SCALE / (zoom * zoom); + let mut paths = vec![]; + for &id in &st.selection.objects { + let Some(n) = st.doc.node(id).filter(|n| !n.is_guide()) else { continue }; + let color = st.doc.layer_color(id); + match &n.kind { + NodeKind::Compound { children, .. } => paths.extend(children.iter().filter_map(|c| c.path_data()).map(|pd| (pd, color))), + _ => paths.extend(n.path_data().map(|pd| (pd, color))), + } + } + let all: Vec<_> = + paths.iter().flat_map(|(pd, color)| pd.subpaths.iter().map(move |sp| (sp, *color))).filter(|(sp, _)| sp.segment_count() > 0).collect(); + // With more subpaths than the teeth allow 2 each, every k-th subpath gets a comb. + let stride = (all.len() * 2).div_ceil(MAX_COMB_TEETH).max(1); + let chosen: Vec<_> = all.into_iter().step_by(stride).collect(); + // Each chosen subpath has 2 teeth set aside; the rest are shared by number of segments. + let total: usize = chosen.iter().map(|(sp, _)| sp.segment_count()).sum(); + let spare = MAX_COMB_TEETH.saturating_sub(2 * chosen.len()); + let mut o = vec![]; + for (sp, color) in chosen { + let extra = (spare as u128) * (sp.segment_count() as u128) / (total.max(1) as u128); + let share = 2usize.saturating_add(usize::try_from(extra).unwrap_or(usize::MAX)); + let teeth = curvature_comb(sp, COMB_SAMPLES, scale, share); + let mut envelope = BezPath::new(); + for t in &teeth { + o.push(Overlay::Line { a: t.at, b: t.tip, color, dashed: false }); + if t.start { + envelope.move_to(t.tip); + } else { + envelope.line_to(t.tip); + } + } + // A closed subpath combed all the way round ends where it starts: the line closes there. + if let Some(first) = teeth.first() + && comb_closes(sp, &teeth) + { + envelope.line_to(first.tip); + } + if teeth.len() > 1 { + o.push(Overlay::Path { path: envelope, color, width: 1.0, dashed: false }); + } + } + o +} diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 29336a8ad8..621a7b67e2 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -359,6 +359,46 @@ fn live_paint_gaps_follow_the_selected_groups() { assert!(live_paint_gap_overlays(&mut app).is_empty()); } +/// View → Show Curvature Comb: a selected circle of radius 100 gets teeth 20 screen points long at +/// zoom 1 and 10 at zoom 2, where it shows twice as large (within 3%: the circle is made of cubics), +/// and a line through their tips; a compound path gets a comb on each of its paths; nothing +/// selected draws nothing. +#[test] +fn the_curvature_comb_follows_the_selection_and_the_zoom() { + let mut app = app(); + let id = app.session.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let teeth = |o: &[Overlay], zoom: f64| -> Vec { + o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some(a.distance(*b) * zoom) } else { None }).collect() + }; + let at_one = teeth(&curvature_comb_overlays(&app, 1.0), 1.0); + for zoom in [1.0, 2.0] { + let o = curvature_comb_overlays(&app, zoom); + let got = teeth(&o, zoom); + assert_eq!(got.len(), 64, "16 teeth on each of the circle's four segments"); + let want = 2000.0 / (100.0 * zoom); + assert!(got.iter().all(|t| (t - want).abs() < 0.03 * want), "{zoom}: {got:?}"); + assert!(got.iter().zip(&at_one).all(|(t, one)| (t * zoom - one).abs() < 1e-9), "zoom divides each tooth's screen length"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1, "one line through the tips"); + let Some(Overlay::Path { path, .. }) = o.iter().find(|o| matches!(o, Overlay::Path { .. })) else { panic!("no line through the tips") }; + let ends: Vec<_> = path.elements().iter().filter_map(|e| e.end_point()).collect(); + assert_eq!(ends.first(), ends.last(), "the closed circle's line through the tips closes"); + } + let other = app.session.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id, other]})).unwrap(); + app.session.execute("object.compoundPath.make", &json!({})).unwrap(); + let o = curvature_comb_overlays(&app, 1.0); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 2, "the compound path's two paths"); + assert_eq!(teeth(&o, 1.0).len(), 128); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(curvature_comb_overlays(&app, 1.0).is_empty()); + assert!(app.run("view.curvatureComb", json!({"on": true})).is_err(), "it takes no parameters"); + assert!(!app.ui.view.curvature_comb, "a refused call leaves it off"); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(true)); + assert!(app.ui.view.curvature_comb); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(false)); +} + /// Draw Inside's arms: an open rectangle round the object, each arm a third of its side or 16 /// points at most, kept with the object deselected and gone with the mode. #[test] diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 4f50576df8..c2d53fcf97 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -8,15 +8,15 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Weak}; use craft::behavior::Input; -use craft::behavior::Metrics; +use craft::behavior::{CanvasView, Metrics}; use craft::draw::ui::{ - AnchorsShown, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleStyle, HandlesShown, Knot, KnotRef, PathOptionsSettings, PathSelection, + AnchorsShown, EditPath, EditSubpath, HandleSide, HandleStyle, HandlesShown, Knot, KnotRef, MAX_ANCHORS, PathOptionsSettings, PathSelection, SegmentMark, }; use craft::theme::Srgba; use craft::ui::canvas::{CanvasSpace, canvas_space}; -use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline}; -use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; +use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline, path_runs}; +use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _, Styled as _}; use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; use vectorcraft_doc::{Document, NodeId, NodeKind}; @@ -622,6 +622,457 @@ impl Component for SelectionDots<'_> { } } +// TEMPORARY: craft-libs#4900 and craft-libs#4928. `BezierOverlay` at the pinned craft-libs lays out its scene and +// flattens and strokes every outline on every paint, and the canvas cloned the paths for it each frame, so a large +// selection stalled every frame. `AnchorMarks` draws what the overlay draws under `BezierTool::Anchors`, from the +// kept marks, and keeps it as one mesh while the marks, the view and the look stay the same. When the craft-libs pin +// includes both pull requests, remove `AnchorMarks` and this section and go back to +// `BezierOverlay::display(...).revision(marks.key)`. + +/// The marks' look, resolved from the theme: the colors and widths `BezierOverlay` paints anchors, handles and +/// outlines with. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct AnchorMarksStyle { + #[style(metrics)] + metrics: Metrics, + /// The outline of a path without a color of its own, and the fill of a selected anchor. + line: craft::ui::style::StyleColor, + /// The fill of a hollow anchor and of a handle's end, per state. + fill: craft::ui::style::Stateful, + /// The edge of an anchor or a handle's end, for a path without a color of its own. + edge: craft::ui::style::StyleColor, + /// An anchor's side. + anchor: f32, + /// A handle end's side with Large handles. + large: f32, + thin: f32, + medium: f32, + thick: f32, + /// How far outside the canvas an anchor or a handle's end is still drawn. + reach: f32, +} + +/// [`AnchorMarksStyle`] for one paint, with the fill resolved: what the kept mesh is built from besides the marks. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MarkLook { + line: Color32, + fill: Color32, + edge: Color32, + anchor: f32, + large: f32, + thin: f32, + medium: f32, + thick: f32, + reach: f32, +} + +/// Everything the kept mesh of the anchor marks depends on. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MeshKey { + /// [`marks_key`] of the marks. + marks: u64, + view: CanvasView, + rect: Rect, + clip: Rect, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, + look: MarkLook, +} + +/// The anchor marks tessellated as one mesh, and what they were tessellated from. +pub(crate) struct KeptMesh { + key: MeshKey, + mesh: Arc, +} + +/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show. +struct MarkSet<'a> { + paths: &'a [EditPath], + selection: &'a PathSelection, + handles: HandlesShown, + shown: AnchorsShown, + segment_mark: SegmentMark, + options: &'a PathOptionsSettings, +} + +/// The two sets the canvas shows: the paths whose handles the tools drag, then the paths whose anchors show selected +/// without handles. +fn mark_sets(anchors: &Anchors) -> [MarkSet<'_>; 2] { + [ + MarkSet { + paths: &anchors.paths, + selection: &anchors.selection, + handles: anchors.handles, + shown: anchors.shown, + segment_mark: anchors.segment_mark, + options: &anchors.options, + }, + MarkSet { + paths: &anchors.plain, + selection: &anchors.plain_selection, + handles: HandlesShown::OneAnchor, + shown: anchors.shown, + segment_mark: SegmentMark::default(), + options: &anchors.options, + }, + ] +} + +/// The anchors, handles and outlines of the selection, painted over the canvas as one kept mesh: no pointer, key or +/// accessibility node, as `BezierOverlay` under `BezierTool::Anchors` has none. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control, content_painter)] +struct AnchorMarks<'a> { + #[common] + common: Common, + anchors: &'a Anchors, + /// [`marks_key`] of `anchors`. + key: u64, + kept: &'a std::cell::RefCell>, +} + +impl Component for AnchorMarks<'_> { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = AnchorMarksStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: AnchorMarksStyleKey) -> AnchorMarksStyle { + let tokens = cx.tokens; + let handle = cx.handle(); + AnchorMarksStyle { + metrics: Metrics::new(), + line: cx.color(tokens.color.overlay.line), + fill: handle.fill, + edge: handle.stroke, + anchor: tokens.size.handle.sm, + large: handle.side, + thin: tokens.stroke.thin, + medium: tokens.stroke.medium, + thick: tokens.stroke.thick, + reach: tokens.size.hit.target, + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(space) = canvas_space(&cx.env) else { return }; + let style = &cx.style; + let look = MarkLook { + line: style.line.egui(), + fill: cx.resolve(&style.fill).egui(), + edge: style.edge.egui(), + anchor: style.anchor, + large: style.large, + thin: style.thin, + medium: style.medium, + thick: style.thick, + reach: style.reach, + }; + let painter = ui.content_painter(cx); + let key = MeshKey { + marks: self.key, + view: space.view, + rect: cx.rect, + clip: painter.painter.clip_rect(), + pixels_per_point: painter.pixels_per_point(), + options: painter.painter.ctx().tessellation_options(|options| *options), + look, + }; + let shapes = || { + let mut shapes = Vec::new(); + for set in mark_sets(self.anchors) { + mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look); + } + shapes + }; + #[cfg(test)] + if tests::RAW_MARKS.with(std::cell::Cell::get) { + painter.painter.extend(shapes()); + return; + } + let mut kept = self.kept.borrow_mut(); + let mesh = match kept.as_ref().filter(|kept| kept.key == key) { + Some(kept) => Arc::clone(&kept.mesh), + None => { + let shapes = shapes(); + let mesh = Arc::new(tessellate(shapes, &key)); + *kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) }); + mesh + } + }; + if !mesh.is_empty() { + painter.painter.add(Shape::Mesh(mesh)); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// `shapes` as one mesh, tessellated as the frame would tessellate them, except that a small filled circle is a +/// polygon rather than a disc from the font atlas, so a later change to the atlas cannot leave the mesh wrong. +fn tessellate(shapes: Vec, key: &MeshKey) -> egui::Mesh { + #[cfg(test)] + tests::MESHES_BUILT.with(|built| built.set(built.get() + 1)); + let mut tessellator = egui::epaint::Tessellator::new(key.pixels_per_point, key.options, [1, 1], Vec::new()); + tessellator.set_clip_rect(key.clip); + let mut mesh = egui::Mesh::default(); + for shape in shapes { + tessellator.tessellate_shape(shape, &mut mesh); + } + mesh +} + +/// Shows the selection's anchors, handles and outlines from `marks`. +fn paint_anchor_marks(ui: &mut egui::Ui, rect: Rect, marks: &SelectionMarks) { + let anchors = &marks.anchors; + if anchors.paths.is_empty() && anchors.plain.is_empty() { + return; + } + #[cfg(test)] + if tests::OVERLAY_MARKS.with(std::cell::Cell::get) { + tests::paint_with_overlay(ui, rect, anchors); + return; + } + AnchorMarks { common: Common::new(), anchors, key: marks.key, kept: &marks.mesh }.label("Anchors").show_at(ui, rect); +} + +/// The fill of an anchor or a handle's end. +#[derive(Clone, Copy)] +enum MarkFill { + /// The look's fill. + Look, + /// The path's color, or the look's line without one: a selected anchor. + Path, +} + +/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the +/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors. +fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) { + let options = set.options; + let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0))); + let path_color = |path: &EditPath| path.color.map(Color32::from); + let anchor_side = options.anchor_size.unwrap_or(look.anchor); + let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor }; + let circles = set.shown == AnchorsShown::Curvature; + let line = |out: &mut Vec, points: Vec, closed: bool, segment: bool, color: Option| { + let named = if segment { look.thick } else { look.medium }; + let ink = color.unwrap_or(look.line); + match options.thickness { + Some(thickness) => { + if segment { + stroke_line(out, points.clone(), closed, Stroke::new(thickness, ink)); + stroke_line(out, points, closed, Stroke::new(named, ink)); + } else { + stroke_line(out, points, closed, Stroke::new(thickness, ink)); + } + } + None => stroke_line(out, points, closed, Stroke::new(named, ink)), + } + }; + for path in set.paths { + let color = path.color.map(Color32::from).or(option_color); + for sub in &path.subpaths { + for (points, closed) in path_runs(view, &sub.bez_path()) { + line(out, points, closed, false, color); + } + } + if set.segment_mark == SegmentMark::Line + && let Some(s) = set.selection.segment.filter(|_| set.selection.path == Some(path.key)) + && let Some(curve) = path.subpaths.get(s.subpath).and_then(|sub| sub.segment(s.knot)) + { + let mut segment = BezPath::new(); + segment.move_to(curve.p0); + segment.curve_to(curve.p1, curve.p2, curve.p3); + for (points, closed) in path_runs(view, &segment) { + line(out, points, closed, true, color); + } + } + } + let total: usize = set.paths.iter().map(EditPath::anchor_count).sum(); + if set.shown == AnchorsShown::Hidden || total > MAX_ANCHORS { + return; + } + let mark = |out: &mut Vec, at: egui::Pos2, side: f32, circle: bool, fill: MarkFill, color: Option| { + let fill = match fill { + MarkFill::Look => look.fill, + MarkFill::Path => color.unwrap_or(look.line), + }; + let edge = Stroke::new(look.thin, color.unwrap_or(look.edge)); + if circle { + let radius = side / 2.0; + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill, stroke: Stroke::NONE })); + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill: Color32::TRANSPARENT, stroke: edge })); + } else { + let square = Rect::from_center_size(at, egui::Vec2::splat(side)); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, fill, Stroke::NONE, StrokeKind::Inside))); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, Color32::TRANSPARENT, edge, StrokeKind::Inside))); + } + }; + // A direction handle: its line from the anchor, then its end. + let handle = |out: &mut Vec, path: &EditPath, knot: KnotRef, end: egui::Pos2| { + let color = path_color(path); + if let Some(knot) = path.knot(knot) { + out.push(Shape::line(vec![view.to_screen(knot.anchor), end], Stroke::new(look.thin, color.unwrap_or(look.line)))); + } + mark(out, end, handle_side, true, MarkFill::Look, color); + }; + let selected = Selected::of(set.selection); + let near = rect.expand(look.reach); + let shown = if circles { Vec::new() } else { shown_handles(set.paths, set.selection, &selected, set.handles, view) }; + let mut handles = shown.iter().peekable(); + for (at, path) in set.paths.iter().enumerate() { + for knot_ref in path.knot_refs() { + let Some(knot) = path.knot(knot_ref) else { continue }; + let anchor = view.to_screen(knot.anchor); + if near.contains(anchor) && set.selection.shows(path.key, knot_ref.subpath) { + let fill = if selected.draws_selected(path.key, knot_ref) { MarkFill::Path } else { MarkFill::Look }; + mark(out, anchor, anchor_side, circles, fill, path_color(path)); + } + while let Some(&(_, _, end)) = handles.next_if(|(p, k, _)| *p == at && *k == knot_ref) { + if near.contains(end) { + handle(out, path, knot_ref, end); + } + } + } + } + if circles || set.handles == HandlesShown::All { + return; + } + // The handles of anchors selected in paths other than the edited one. + let edited = set.selection.path.map_or(0, |_| set.selection.anchors.len()); + for path in set.paths { + if set.selection.path == Some(path.key) || !selected.listed.contains(&path.key) { + continue; + } + let own = PathSelection::new(Some(path.key), Vec::new(), None); + let listed = |key: u64, knot: KnotRef| selected.others.contains(&(key, knot)); + for (_, knot, end) in handles_of(std::slice::from_ref(path), &own, listed, selected.others_len + edited, set.handles, view) { + handle(out, path, knot, end); + } + } +} + +/// Strokes the run `points`, closed or open, on its centre line. +fn stroke_line(out: &mut Vec, points: Vec, closed: bool, stroke: Stroke) { + if closed { + if stroke.is_empty() { + return; + } + let mut line = egui::epaint::PathStroke::from(stroke); + line.kind = StrokeKind::Middle; + out.push(Shape::closed_line(points, line)); + } else { + out.push(Shape::line(points, stroke)); + } +} + +/// The anchors a [`PathSelection`] selects, gathered into sets once. +struct Selected { + path: Option, + anchors: std::collections::HashSet, + others: std::collections::HashSet<(u64, KnotRef)>, + listed: std::collections::HashSet, + others_len: usize, +} + +impl Selected { + fn of(sel: &PathSelection) -> Self { + Self { + path: sel.path, + anchors: sel.anchors.iter().copied().collect(), + others: sel.others.iter().flat_map(|(key, knots)| knots.iter().map(|knot| (*key, *knot))).collect(), + listed: sel.others.iter().map(|(key, _)| *key).collect(), + others_len: sel.others.iter().map(|(_, knots)| knots.len()).sum(), + } + } + + /// Whether `knot` of `path` is a selected anchor of the edited path. + fn has_anchor(&self, path: u64, knot: KnotRef) -> bool { + self.path == Some(path) && self.anchors.contains(&knot) + } + + /// Whether `knot` of `path` draws selected. + fn draws_selected(&self, path: u64, knot: KnotRef) -> bool { + self.has_anchor(path, knot) || self.others.contains(&(path, knot)) + } +} + +/// The handles that show for `sel`, in path order, in then out: each path's index, the knot and the end on screen. +fn shown_handles( + paths: &[EditPath], + sel: &PathSelection, + selected: &Selected, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + handles_of(paths, sel, |path, knot| selected.has_anchor(path, knot), sel.selected_len(), shown, view) +} + +/// The handles that show, with `has_anchor` answering whether a knot is a selected anchor and `count` the number of +/// selected anchors `HandlesShown::OneAnchor` counts. A retracted handle and the handles of a subpath the selection +/// does not show are left out. +fn handles_of( + paths: &[EditPath], + sel: &PathSelection, + has_anchor: impl Fn(u64, KnotRef) -> bool, + count: usize, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + let mut out = Vec::new(); + for (index, path) in paths.iter().enumerate() { + let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { + let (a, b) = path.subpaths.get(s.subpath)?.segment_ends(s.knot)?; + Some((KnotRef::new(s.subpath, a), KnotRef::new(s.subpath, b))) + }); + for knot_ref in path.knot_refs().filter(|k| sel.shows(path.key, k.subpath)) { + let Some(knot) = path.knot(knot_ref) else { continue }; + for side in [HandleSide::In, HandleSide::Out] { + let of_selection = || { + has_anchor(path.key, knot_ref) + || next_to_selected(path, &has_anchor, knot_ref, side) + || segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref)) + }; + let wanted = match shown { + HandlesShown::All => true, + HandlesShown::OneAnchor => count == 1 && of_selection(), + _ => of_selection(), + }; + if wanted && !knot.retracted(side) { + out.push((index, knot_ref, view.to_screen(knot.handle(side)))); + } + } + } + } + out +} + +/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out handle +/// or the next anchor's in handle, across a closed subpath's seam too. +fn next_to_selected(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool { + let Some(sub) = path.subpaths.get(knot.subpath) else { return false }; + let count = sub.knots.len(); + if side == HandleSide::Out { + return sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))); + } + let previous = (knot.knot + count.saturating_sub(1)) % count.max(1); + sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous))) +} + /// Whether the active tool draws its own points over the paths: the Curvature tool while it has a draft. fn tool_draws_points(app: &mut VectorcraftApp) -> bool { if app.session.tool_id() != "curvature" { @@ -675,27 +1126,7 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } outline.show_at(ui, rect); } - let anchors = &marks.anchors; - if !anchors.paths.is_empty() { - let mut paths = anchors.paths.clone(); - // The marks only show the selection: the tools make the edits. - let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) - .tool(BezierTool::Anchors) - .handles(anchors.handles) - .anchors(anchors.shown) - .segment_mark(anchors.segment_mark) - .path_options(&anchors.options) - .show_at(ui, rect); - } - if !anchors.plain.is_empty() { - let mut paths = anchors.plain.clone(); - let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) - .tool(BezierTool::Anchors) - .handles(HandlesShown::OneAnchor) - .anchors(anchors.shown) - .path_options(&anchors.options) - .show_at(ui, rect); - } + paint_anchor_marks(ui, rect, &marks); let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); @@ -722,6 +1153,8 @@ pub(crate) struct SelectionMarks { outlines: Vec, anchors: Anchors, dots: Dots, + /// The anchor marks as one mesh, from the last paint ([`AnchorMarks`]). + mesh: std::cell::RefCell>, } impl SelectionMarks { @@ -738,6 +1171,7 @@ impl SelectionMarks { outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st), + mesh: std::cell::RefCell::new(None), } } @@ -803,4 +1237,4 @@ fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) } #[cfg(test)] -mod tests; +pub(super) mod tests; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 42e0bc620b..42adf76890 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -942,6 +942,217 @@ fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_time assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get()); } +thread_local! { + /// Whether `show` draws the anchor marks with `BezierOverlay`, as it did before [`AnchorMarks`]. + pub(super) static OVERLAY_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether [`AnchorMarks`] paints its shapes one by one instead of as a mesh. + pub(in crate::canvas) static RAW_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many meshes [`AnchorMarks`] tessellated. + pub(super) static MESHES_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The anchor marks as `show` drew them before [`AnchorMarks`]: two `BezierOverlay`s under `BezierTool::Anchors`. +pub(super) fn paint_with_overlay(ui: &mut egui::Ui, rect: Rect, anchors: &Anchors) { + use craft::draw::ui::{BezierOverlay, BezierTool}; + use craft::ui::contract::Bind; + if !anchors.paths.is_empty() { + let mut paths = anchors.paths.clone(); + let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) + .tool(BezierTool::Anchors) + .handles(anchors.handles) + .anchors(anchors.shown) + .segment_mark(anchors.segment_mark) + .path_options(&anchors.options) + .show_at(ui, rect); + } + if !anchors.plain.is_empty() { + let mut paths = anchors.plain.clone(); + let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) + .tool(BezierTool::Anchors) + .handles(HandlesShown::OneAnchor) + .anchors(anchors.shown) + .path_options(&anchors.options) + .show_at(ui, rect); + } +} + +/// One frame of the canvas alone with `events`. +fn canvas_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui)); + out.textures_delta.clear(); + out +} + +/// The shapes a canvas frame paints, with the anchor marks drawn by `BezierOverlay` (`overlay`) or by +/// [`AnchorMarks`] one shape at a time. +fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) -> Vec { + OVERLAY_MARKS.with(|on| on.set(overlay)); + RAW_MARKS.with(|on| on.set(!overlay)); + canvas_frame(app, ctx, vec![]); + let out = canvas_frame(app, ctx, vec![]); + OVERLAY_MARKS.with(|on| on.set(false)); + RAW_MARKS.with(|on| on.set(false)); + crate::tests::labels::flat_painted_shapes(&out.shapes) +} + +/// A canvas app with one curve, the task bar off and every frame drawn on this thread. +fn canvas_app() -> (VectorcraftApp, NodeId) { + let mut app = blank(); + app.ui.task_bar = false; + app.canvas.worker_started = true; + let curve = id_of(&app.run("path.create", json!({"d": "M40 40 C60 10 90 10 110 40 S160 70 180 40 L180 90"})).unwrap()); + (app, curve) +} + +// The anchor marks paint the shapes `BezierOverlay` paints for the same marks: under the Selection tool, Direct +// Selection with a partial selection, a selected segment and the Curvature tool, with handles shown for one anchor or +// for every selected anchor, each handle style, and the Path Options color and thickness on paths without a color. +#[test] +fn the_anchor_marks_paint_what_the_bezier_overlay_paints() { + let (mut app, curve) = scene(); + let ctx = crate::testing::ui_context(); + let compare = |app: &mut VectorcraftApp, case: &str, change: &dyn Fn(&mut Anchors)| { + canvas_frame(app, &ctx, vec![]); + if let Some(marks) = app.canvas.selection_marks.as_mut() { + change(&mut marks.anchors); + } + let overlay = canvas_shapes(app, &ctx, true); + let marks = canvas_shapes(app, &ctx, false); + assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len()); + let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b); + assert!( + overlay == marks, + "{case}: {} shapes from the overlay, {} from the marks, first difference at {differs:?}", + overlay.len(), + marks.len() + ); + }; + let same = |_: &mut Anchors| {}; + app.select_tool("selection"); + compare(&mut app, "the Selection tool", &same); + for (multiple, style) in [(true, "solid"), (false, "hollow"), (true, "large")] { + app.session.prefs.show_handles_multiple_anchors = multiple; + app.session.prefs.handle_style = style.into(); + app.session.prefs.anchor_size = 5; + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("Direct Selection, multiple {multiple}, {style}"), &same); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("one anchor, multiple {multiple}, {style}"), &same); + } + // A segment selected in place keeps the revision, so the kept marks are dropped to build them again. + let pick_segment = |app: &mut VectorcraftApp| { + app.session.active_mut().unwrap().selection.segments.insert(curve, [(0, 1)].into_iter().collect()); + app.canvas.selection_marks = None; + }; + pick_segment(&mut app); + compare(&mut app, "a selected segment", &|anchors| assert!(anchors.selection.segment.is_some(), "a segment is selected")); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.all", json!({})).unwrap(); + compare(&mut app, "every handle", &|anchors| anchors.handles = HandlesShown::All); + let options = |anchors: &mut Anchors| { + anchors.options.color = Some([10, 200, 30]); + anchors.options.thickness = Some(3.0); + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }; + compare(&mut app, "the Path Options color and thickness", &options); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("directSelection"); + pick_segment(&mut app); + compare(&mut app, "a selected segment with a thickness", &options); + compare(&mut app, "paths without a color", &|anchors| { + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("curvature"); + compare(&mut app, "the Curvature tool", &same); +} + +// The canvas tessellates the anchor marks once and paints the kept mesh while nothing they show changes: frames that +// change nothing tessellate none, and a new selection, a scroll of the view and a new zoom each tessellate them once. +#[test] +fn an_idle_frame_tessellates_no_anchor_marks() { + let (mut app, curve) = canvas_app(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MESHES_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + canvas_frame(app, &ctx, vec![]); + } + MESHES_BUILT.with(std::cell::Cell::get) - before + }; + assert_eq!(frames(&mut app, 3), 1, "the first frame tessellates the marks"); + assert_eq!(frames(&mut app, 10), 0, "frames that change nothing"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + assert_eq!(frames(&mut app, 5), 1, "a new selection"); + app.view_mut().unwrap().center.x += 40.0; + assert_eq!(frames(&mut app, 5), 1, "a scroll"); + app.view_mut().unwrap().zoom *= 2.0; + assert_eq!(frames(&mut app, 5), 1, "a new zoom"); + app.run("select.none", json!({})).unwrap(); + assert_eq!(frames(&mut app, 5), 0, "nothing selected, nothing to tessellate"); +} + +/// What a press-drag and Tab presses did: the curve's bounds, its selected anchors, and the focused accessibility node +/// after each Tab. +type Reached = (vectorcraft_geom::Rect, Vec<(usize, usize)>, Vec>); + +/// What the canvas does with a press-drag from the curve's third anchor under `tool`, then Tab presses. +fn press_and_tab(tool: &str, overlay: bool) -> Reached { + OVERLAY_MARKS.with(|on| on.set(overlay)); + let (mut app, curve) = canvas_app(); + app.select_tool(tool); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + canvas_frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + // The curve's third anchor, and a drag away from it. + let (from, to) = (xf.to_screen(Point::new(110.0, 40.0)), xf.to_screen(Point::new(130.0, 60.0))); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + canvas_frame(&mut app, &ctx, vec![button(from, true)]); + for i in 1..=5 { + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * (i as f32 / 5.0))]); + } + canvas_frame(&mut app, &ctx, vec![button(to, false)]); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let focused = (0..4) + .map(|_| { + let out = canvas_frame(&mut app, &ctx, vec![tab.clone()]); + let update = out.platform_output.accesskit_update.as_ref().expect("an accessibility tree"); + update.nodes.iter().find(|(id, _)| *id == update.focus).and_then(|(_, node)| node.label().map(str::to_owned)) + }) + .collect(); + OVERLAY_MARKS.with(|on| on.set(false)); + let st = app.session.active().unwrap(); + let bounds = st.doc.bounds_of(&[curve], false).unwrap(); + let mut chosen: Vec<(usize, usize)> = st.selection.partial(curve).map(|set| set.iter().copied().collect()).unwrap_or_default(); + chosen.sort_unstable(); + (bounds, chosen, focused) +} + +// A press on a shown anchor reaches the tool and Tab from the canvas goes where it went with `BezierOverlay`: the +// Selection tool drags the whole path, Direct Selection drags the anchor, and Tab keeps the focus on the canvas. +#[test] +fn a_press_on_an_anchor_and_tab_reach_what_they_reached_with_the_overlay() { + for tool in ["selection", "directSelection"] { + let overlay = press_and_tab(tool, true); + let marks = press_and_tab(tool, false); + assert_eq!(marks, overlay, "{tool}"); + let (bounds, ..) = &marks; + assert!((bounds.x0 - 40.0).abs() > 1.0 || (bounds.x1 - 180.0).abs() > 1.0, "{tool}: the drag edited the curve: {bounds:?}"); + } +} + thread_local! { /// How many times the canvas built the selection's marks ([`SelectionMarks::build`]). pub(super) static MARKS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index d2bbdf1f5c..dcd87f71ee 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -12,7 +12,8 @@ use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; +use craft::ui::runtime::env::{Env, Label, WordRows, WordsOverride, with_env}; +use craft::ui::style::{UiTokens, rgba_color}; use vectorcraft_doc::NodeKind; use vectorcraft_doc::text::TextKind; use vectorcraft_geom::{Point, Rect}; @@ -488,12 +489,14 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> let has_shape = offer.shape.is_some(); let mut run: Option<(&'static str, serde_json::Value)> = None; let mut show_swatches = false; + let mut layer = None; let shown = TaskBar::new(tl!("Contextual Task Bar"), &offer.anchor, Bind::bound(&mut local)) .grip(TaskBarGrip::Bar) .member_gap(Gap::Item) .hang_gap(TaskBarHang::ClearOfHandles) .more_rows(more_rows(&offer)) .show(ui, space.view.rect, |ui, _| { + layer = Some((ui.layer_id(), ui.opacity())); for (label, icon, cmd, params) in &offer.actions { if *cmd == TASK_BAR_FIDELITY { // The Smooth tool's Fidelity, labeled, sets the tool's option once a typed or stepped value is @@ -567,6 +570,9 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> } }); let (rect, hide) = (shown.output.rect, shown.output.hide); + if let Some((layer, opacity)) = layer { + accent_outline(ui, layer, opacity, rect); + } if local != before { app.ui.task_bar_place.set(key, local); } @@ -599,6 +605,23 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Some(rect) } +/// Outlines the Contextual Task Bar at `rect` on its `layer` in the accent border color, on the corners of the floating +/// surface the bar paints and at its rect rounded to pixels, at the `opacity` the bar's members paint at while the bar +/// fades in or out. +/// +/// Temporary: craft-libs#4892 adds `TaskBar::edge(BarEdge::Accent)`, which draws this outline in place of the +/// surface's own border. Delete this function and set that edge on the bar once the craft-libs pin includes it. +fn accent_outline(ui: &Ui, layer: egui::LayerId, opacity: f32, rect: egui::Rect) { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let stroke = egui::Stroke::new(tokens.stroke.thin, rgba_color(tokens.color.accent.border)); + let corners = UiTokens::corner(tokens.shape.radius.window); + let mut painter = ui.ctx().layer_painter(layer); + painter.set_opacity(opacity); + let rect = egui::emath::GuiRounding::round_to_pixels(rect, painter.pixels_per_point()); + painter.rect_stroke(rect, corners, stroke, egui::StrokeKind::Inside); +} + /// The controls the Contextual Task Bar shows after its actions: the Fill and Stroke chips, /// Recolor Artwork, and Lock or a basic shape's Shape Properties. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index df0d8fc387..e7fec25534 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -267,10 +267,12 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { } /// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the -/// points of lines and paths. +/// points of lines and paths. The selection's anchor marks paint as the shapes their mesh is made of. fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + super::selection::tests::RAW_MARKS.with(|on| on.set(true)); let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + super::selection::tests::RAW_MARKS.with(|on| on.set(false)); out.textures_delta.clear(); let mut points = vec![]; for shape in flat_shapes(out.shapes) { diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 70f1080db5..34ef127f95 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -7,8 +7,8 @@ use craft::behavior::{CancelReason, CanvasView, Cursor, DropOperation, PointerKi use craft::keymap::{Chord, Key}; use craft::ui::canvas::ToolPath; use craft::ui::canvas::{ - Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass, - ToolPointer, + Autoscroll, CanvasTool, Momentary, MomentaryCommands, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, + ToolPass, ToolPointer, }; use serde_json::json; use vectorcraft_engine::ViewInfo; @@ -615,6 +615,37 @@ impl CanvasTool for SessionTool<'_> { } } +/// Ends the held momentary command (Space's Hand, Cmd+Space's Zoom...) once none of the keys that were down when it +/// started is down, and returns the command still held. The shortcut board drops a queued release when the canvas +/// does not run on the frame the key goes up (a dialog or another tab in front). A hold that started with no key down +/// (automation) lasts until its release. +/// +/// Temporary: craft-libs#5056 ends the hold inside the tool host. Remove this function, [`note_momentary_keys`], +/// their calls and `CanvasCache::momentary_keys` once the craft-libs pin includes that change. +fn end_missed_momentary(ctx: &egui::Context, momentary: &mut Momentary, keys: &mut Vec) -> Option { + let held = momentary.held()?; + if keys.is_empty() { + return Some(held); + } + let down = craft::ui::runtime::keys::held(ctx); + if keys.iter().any(|key| down.contains(key)) { + return Some(held); + } + momentary.fired(held, craft::ui::runtime::commands::FirePhase::Release); + keys.clear(); + None +} + +/// Notes the keys down when a momentary command starts (or changes), for [`end_missed_momentary`]; `before` is the +/// command held before the tool host's pass. +fn note_momentary_keys(ctx: &egui::Context, before: Option, momentary: &Momentary, keys: &mut Vec) { + match momentary.held() { + None => keys.clear(), + Some(held) if before != Some(held) => *keys = craft::ui::runtime::keys::held(ctx), + Some(_) => {} + } +} + /// Runs the tool host on `tool` with the app's momentary set, which the app keeps across passes. A finger, once a pen /// has been seen, only navigates (palm rejection). fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn CanvasTool) -> ToolHostResponse { @@ -622,7 +653,9 @@ fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn C let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); + let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut app.canvas.momentary_keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); + note_momentary_keys(ui.ctx(), before, &momentary, &mut app.canvas.momentary_keys); app.canvas.momentary = Some(momentary); response } @@ -755,9 +788,14 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); + let mut keys = std::mem::take(&mut app.canvas.momentary_keys); drop(app); + let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - tool.app().canvas.momentary = Some(momentary); + note_momentary_keys(ui.ctx(), before, &momentary, &mut keys); + let mut app = tool.app(); + app.canvas.momentary = Some(momentary); + app.canvas.momentary_keys = keys; response } @@ -782,6 +820,9 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in if app.ui.view.live_paint_gaps { extra.extend(super::marks::live_paint_gap_overlays(app)); } + if app.ui.view.curvature_comb { + extra.extend(super::marks::curvature_comb_overlays(app, space.view.zoom)); + } } super::overlays::show(app, ui, &space, &list, &extra); } diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 1ff48b983a..a9c60d1089 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -48,6 +48,69 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec out.textures_delta.clear(); } +/// A frame where the canvas does not run, as with a dialog or another tab in front. +fn frame_without_canvas(ctx: &egui::Context, events: Vec) { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |_| {}); + out.textures_delta.clear(); +} + +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// Space let go while the canvas is away for long enough that the shortcut board drops its queued release (two +/// frames) ends the momentary Hand at the canvas's next pass, and Space still held across such frames keeps it. The +/// Rectangle tool runs through the session's tool, and the Zoom tool through the framework's. +#[test] +fn space_let_go_while_the_canvas_is_away_ends_the_momentary_hand() { + for tool in ["rectangle", "zoom"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![space_key(true)]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "{tool}: Space down holds the Hand"); + frame_without_canvas(&ctx, vec![]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "{tool}: Space still down keeps the Hand across frames without the canvas"); + frame_without_canvas(&ctx, vec![space_key(false)]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(!view_tool_held(&app), "{tool}: Space let go while the canvas was away ends the Hand"); + } +} + +/// A momentary Hand whose key is down at another physical position than the one its shortcut names (another keyboard +/// layout) stays held across passes while that key is down, and ends once it goes up while the canvas is away. +#[test] +fn a_momentary_hand_from_another_layout_position_lasts_while_its_key_is_down() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + let key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Backtick), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![key(true)]); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "the key still down keeps the Hand"); + frame_without_canvas(&ctx, vec![key(false)]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(!view_tool_held(&app), "the key let go while the canvas was away ends the Hand"); +} + /// With the Live Paint Bucket and the pointer still, an Alt-only pass changes the cursor and back. #[test] fn bucket_modifier_only_hover_updates_the_visible_cursor() { diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index f4c1d52986..a0554f26bb 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -45,3 +45,40 @@ fn every_cursor_icon_the_app_names_is_in_its_set() { } } } + +/// Painted cursors use the SVG's alpha as ink. Drawing the vent in white makes it solid ink. +#[test] +fn the_painted_pen_nibs_keep_their_breather_holes() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let ink = rgba_color(tokens.color.overlay.cursor); + let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + let scale = 4.0; + let from_art_units = tokens.size.icon.md * scale / 24.0; + for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else { + panic!("{c:?} must have painted tool art"); + }; + let image = painted_image(&env, &painted, scale).expect("the cursor fits in its bitmap"); + let [hx, hy] = image.hotspot.map(f32::from); + let pixel = |x: f32, y: f32| { + let x = (hx + (x - hotspot.x) * from_art_units).round() as usize; + let y = (hy + (y - hotspot.y) * from_art_units).round() as usize; + let i = (y * usize::from(image.size[0]) + x) * 4; + &image.rgba[i..i + 4] + }; + assert!(is_ink(pixel(9.5, 13.2)), "{c:?}: the nib body is ink"); + assert!(!is_ink(pixel(6.62, 12.86)), "{c:?}: the vent must break up the ink"); + } + }) + .textures_delta + .clear(); +} diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 110c124717..f508f52904 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -93,8 +93,13 @@ impl Adjust { { old.preview.cancel(app); } + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { - ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) + let dialog = ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; *(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() }); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f45fadf201..d9d2fba515 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -287,6 +287,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); } + // The picker adds no dimming of its own over the canvas, so its live preview shows the true color; another open + // dialog's scrim can still dim the canvas. Presses on it stay blocked: + // the app does not take the picker's canvas eyedropper request. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + dialog = dialog.canvas(canvas).canvas_samples(false); + } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) { diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 1abafe7025..4d7e820a29 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -451,3 +451,46 @@ fn the_artboard_picker_leaves_restored_artboards_unchanged() { assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); } } + +/// The picker keeps the document's canvas open under its modal layer (#10639): the canvas is not dimmed, so the live +/// preview shows the true color, and the wheel over the canvas still scrolls the view. +#[test] +fn the_canvas_stays_open_under_the_picker() { + let step = |app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); + }; + let (mut app, ctx) = app(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + app.run("ui.colorPicker", json!({})).unwrap(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + assert!(!app.color_dialogs.pickers.is_empty(), "the picker is open"); + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + for _ in 0..3 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + } + let before = app.canvas_view().unwrap().center; + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -3.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..5 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + assert_ne!(app.canvas_view().unwrap().center, before, "the wheel over the canvas scrolls the view under the picker"); + // A click on the canvas stays blocked: it does not reach the tool and clear the selection. + let selected = app.session.doc().unwrap().selection.clone(); + let press = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::default() }; + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(true)]); + step(&mut app, &ctx, vec![press(false)]); + step(&mut app, &ctx, vec![]); + assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the picker leaves the selection"); +} diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 2b3760f38f..796a829836 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -249,8 +249,13 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field /// Open Flatten Transparency for the selection with the default preset. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| { - ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true) + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), move |fields| { + let dialog = ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }) // Flattening complex art is slow: the preview waits until it is turned on. .preview_off(); diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 654aebad35..893f2f1c38 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -102,9 +102,14 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); - let dialog = HostedParamDialog::command(&ctx, CMD, initial, |fields| { + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::command(&ctx, CMD, initial, move |fields| { let rows = screen_params(false, fields); - ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)) + let dialog = ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index 0f1aec1462..d9850c0edd 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -103,7 +103,11 @@ pub fn open(app: &mut VectorcraftApp) { if let Some(old) = app.object_dialogs.indexed.take() { old.cancel_preview(app); } - let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), move |fields| match canvas { + Some(canvas) => build(fields).canvas(canvas), + None => build(fields), + }); let opening = Arc::new(()); let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 292267fd62..2cbe092f14 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -532,9 +532,15 @@ pub(crate) fn asking_to_print(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. +/// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. A +/// script's palettes ([`crate::script_palettes`]) stay open beside the documents and are not +/// counted. pub(crate) fn busy(app: &VectorcraftApp) -> bool { - app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) + let other = |host: &mut DialogHost| { + let open = host.open_dialogs(); + !host.is_empty() && (open.is_empty() || open.iter().any(|d| d.key.as_deref() != Some(crate::script_palettes::KIND))) + }; + app.any_dialog_open() || with_host(app, |host, _| other(host)).unwrap_or(false) } /// Whether the run's question can open now: over nothing, or over the script's ScriptUI dialog @@ -764,7 +770,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { Some(parent) => { host.open_child(close_question(), parent); } - None if host.is_empty() => { + // The script's palettes stay open beside the question. + None if host.is_empty() || host.open_dialogs().iter().all(|d| d.key.as_deref() == Some(crate::script_palettes::KIND)) => { host.open(close_question()); } None => {} diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index c7a85c3e0c..48401c4b57 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -50,7 +50,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "scriptWindow"; /// The most of the dialog's content shown at once; a larger dialog scrolls. -const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); +pub(crate) const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); /// The room the engine's layout adds around a list box's rows. const LIST_PAD: f32 = 6.0; @@ -158,65 +158,20 @@ impl ScriptWindow { self.waiting = waiting.is_some(); if let Some(w) = waiting { self.window = w; - let fields: Vec = self.window.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect(); - self.drafts.retain(|id, _| fields.contains(id)); + keep_fields(&self.window, &mut self.drafts); } } /// Before a click or a close, gives the script the text typed in each edit field that has not - /// left the field yet, so the handler of a button that closes the dialog, or `onClose`, reads - /// it. A disabled or hidden field keeps its text for later. Each text is checked as the script - /// in `w` would check it first; when one is refused, every field keeps its text, `events` stays - /// as it was and the error is returned. + /// left the field yet ([`commit_texts`]). pub(crate) fn commit_drafts(&mut self, w: &ScriptUiDialog, events: &mut Vec) -> Result<(), String> { - let mut given = Vec::new(); - let mut changes = Vec::new(); - for (i, n) in w.nodes.iter().enumerate() { - if n.kind != UiKind::EditText - || n.readonly - || !n.enabled - || !n.visible - || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) - { - continue; - } - if let Some(text) = self.drafts.get(&n.id) { - if *text != n.text { - changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?); - } - given.push(n.id); - } - } - for id in given { - self.drafts.remove(&id); - } - let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); - events.sort_by_key(closing); - let at = events.iter().position(closing).unwrap_or(events.len()); - events.splice(at..at, changes); - Ok(()) + commit_texts(w, &mut self.drafts, events) } /// Takes out of `events` each text an edit field gave as it lost the focus that the script - /// would refuse, and puts it back in its field, so the person can fix it. → the error of the - /// last one. + /// would refuse ([`keep_refused`]). → the error of the last one. pub(crate) fn keep_refused_texts(&mut self, events: &mut Vec) -> Option { - let mut refused = None; - let (w, drafts) = (&self.window, &mut self.drafts); - events.retain(|e| { - let UiEvent::Change(i, UiValue::Text(text)) = e else { return true }; - match check_event(w, e.clone()) { - Ok(_) => true, - Err(error) => { - if let Some(n) = w.nodes.get(*i) { - drafts.insert(n.id, text.clone()); - } - refused = Some(error); - false - } - } - }); - refused + keep_refused(&self.window, &mut self.drafts, events) } /// The next queued event the dialog `w` can still take, with its control's index in `w` now. @@ -251,8 +206,72 @@ impl ScriptWindow { } } +/// Drops each typed text in `drafts` whose edit field the dialog `w` no longer has. +pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap) { + let fields: Vec = w.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect(); + drafts.retain(|id, _| fields.contains(id)); +} + +/// Before a click or a close, gives the script the text typed in each edit field of `w` that has +/// not left the field yet (`drafts`), so the handler of a button that closes the dialog, or +/// `onClose`, reads it. A disabled or hidden field keeps its text for later. Each text is checked +/// as the script in `w` would check it first; when one is refused, every field keeps its text, +/// `events` stays as it was and the error is returned. +pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap, events: &mut Vec) -> Result<(), String> { + let mut given = Vec::new(); + let mut changes = Vec::new(); + for (i, n) in w.nodes.iter().enumerate() { + if n.kind != UiKind::EditText + || n.readonly + || !n.enabled + || !n.visible + || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) + { + continue; + } + if let Some(text) = drafts.get(&n.id) { + if *text != n.text { + changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?); + } + given.push(n.id); + } + } + for id in given { + drafts.remove(&id); + } + // The events of one pass are listed in the order of the controls, not the order the person + // gave them, so each change goes before the clicks and the close, and a handler that closes + // the dialog reads it. + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + events.splice(at..at, changes); + Ok(()) +} + +/// Takes out of `events` each text an edit field of `w` gave as it lost the focus that the script +/// would refuse, and puts it back in its field (`drafts`), so the person can fix it. → the error of +/// the last one. +pub(crate) fn keep_refused(w: &ScriptUiDialog, drafts: &mut BTreeMap, events: &mut Vec) -> Option { + let mut refused = None; + events.retain(|e| { + let UiEvent::Change(i, UiValue::Text(text)) = e else { return true }; + match check_event(w, e.clone()) { + Ok(_) => true, + Err(error) => { + if let Some(n) = w.nodes.get(*i) { + drafts.insert(n.id, text.clone()); + } + refused = Some(error); + false + } + } + }); + refused +} + /// `event` in the dialog `w`, with its control by its id. -fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { +pub(crate) fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { let id = |i: usize| w.nodes.get(i).map(|n| n.id); Some(match event { UiEvent::Click(i) => Queued::Click(id(*i)?), @@ -266,8 +285,8 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { /// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now. /// `None` when `w` no longer has the control, or for a list's change, when the list's items are no -/// longer those the person chose from. -fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { +/// longer those the person chose from: other texts, or the same texts added again. +pub(crate) fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { match q { Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), Queued::Change(id, v, items) => { @@ -306,10 +325,7 @@ impl StackDialog for ScriptWindow { fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { let top = stack.is_top(self.id()); - let heading = match self.window.title() { - "" => tl!("Script Alert").to_string(), - title => shown_text(title, false), - }; + let heading = heading(&self.window); let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)]; let ScriptWindow { window, waiting, drafts, open, .. } = self; let (window, waiting, drafts) = (&*window, *waiting, &*drafts); @@ -320,35 +336,7 @@ impl StackDialog for ScriptWindow { let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); // The body can run twice in a pass (measure, then paint), so it only reports what the // person did; the dialog applies the last run's report after the container. - let shown = dialog.show(ui, |ui, _| { - let (width, height) = window.size(); - let size = egui::vec2(width.max(1.0), height.max(1.0)); - let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; - ui.scope(|ui| { - ui.set_max_size(MAX_SHOWN); - Stack::new().scroll(Scroll::both()).show(ui, |ui, _| { - let origin = ui.cursor().min; - ui.set_min_size(size); - // Each container comes before the controls it holds. - let mut containers: Vec> = vec![None; window.nodes.len()]; - for (i, n) in window.nodes.iter().enumerate().skip(1) { - if !n.visible { - continue; - } - let parent = containers.get(n.parent).copied().flatten(); - let place = Place { origin, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent }; - let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i))); - if let Some(slot) = containers.get_mut(i) { - *slot = shown.container; - } - pass.typing |= shown.typing; - pass.events.extend(shown.event); - pass.drafts.extend(shown.draft.map(|d| (n.id, d))); - } - }); - }); - pass - }); + let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting)); let pass = shown.inner.unwrap_or_default(); if pass.layer.is_some() { self.layer = pass.layer; @@ -418,6 +406,46 @@ impl StackDialog for ScriptWindow { } } +/// The heading of the ScriptUI window `w`: its title, or "Script Alert" without one. +pub(crate) fn heading(w: &ScriptUiDialog) -> String { + match w.title() { + "" => tl!("Script Alert").to_string(), + title => shown_text(title, false), + } +} + +/// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out, +/// with the text typed in its edit fields (`drafts`); none can be used unless `usable`. +pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, usable: bool) -> Pass { + let (width, height) = w.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; + ui.scope(|ui| { + ui.set_max_size(MAX_SHOWN); + Stack::new().scroll(Scroll::both()).show(ui, |ui, _| { + let origin = ui.cursor().min; + ui.set_min_size(size); + // Each container comes before the controls it holds. + let mut containers: Vec> = vec![None; w.nodes.len()]; + for (i, n) in w.nodes.iter().enumerate().skip(1) { + if !n.visible { + continue; + } + let parent = containers.get(n.parent).copied().flatten(); + let place = Place { origin, enabled: usable && n.enabled, default: w.default_element == Some(i), parent }; + let shown = control(ui, drafts, &place, (i, n, prompt_of(w, i))); + if let Some(slot) = containers.get_mut(i) { + *slot = shown.container; + } + pass.typing |= shown.typing; + pass.events.extend(shown.event); + pass.drafts.extend(shown.draft.map(|d| (n.id, d))); + } + }); + }); + pass +} + /// Where a control is drawn: from `origin`, enabled or not, whether it is the default button, and /// the accessibility node of the group or panel that holds it. struct Place { @@ -441,10 +469,10 @@ struct Shown { /// What one run of the dialog's body gave: the events, whether an edit field has the keyboard /// focus, the typed texts to keep or forget, by field id, and the overlay layer it was drawn in. #[derive(Default)] -struct Pass { - events: Vec, +pub(crate) struct Pass { + pub(crate) events: Vec, typing: bool, - drafts: Vec<(u64, Option)>, + pub(crate) drafts: Vec<(u64, Option)>, layer: Option, } @@ -733,11 +761,24 @@ pub(crate) fn pump(app: &mut VectorcraftApp) { UiEvent::Change(i, UiValue::Text(t)) => w.nodes.get(*i).map(|n| (n.id, t.clone())), _ => None, }; - if let Err(e) = give(app, &w, event) { - if let Some((id, text)) = typed { - with_window(app, |d| d.drafts.insert(id, text)); + match give(app, &w, event) { + // The event lets the run go on, which the app idles for while it waits: the next frame + // takes the run's next slice. + Ok(()) => { + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + } + Err(e) => { + if let Some((id, text)) = typed { + with_window(app, |d| d.drafts.insert(id, text)); + } + app.status(e); + // The next frame gives the run the next queued event. + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } } - app.status(e); } } } @@ -747,12 +788,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp) { /// next wait. fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result<(), String> { let mut events = vec![check_event(w, event)?]; + // When the run does not take the first event, the typed texts stay in their fields. + let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default(); if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?; } let mut events = events.into_iter(); - if let Some(first) = events.next() { - app.session.script_window_answer(first)?; + if let Some(first) = events.next() + && let Err(e) = app.session.script_window_answer(first) + { + with_window(app, |d| d.drafts = drafts); + return Err(e); } let later: Vec = events.filter_map(|e| queued(w, &e)).collect(); with_window(app, |d| { @@ -794,6 +840,8 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string()); }; let mut events = vec![cancel_event(&w)]; + // When the run does not take the first event, the typed texts stay in their fields. + let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default(); with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true); // A cancel after other events goes last, and is a click on the cancel button of the dialog the @@ -803,8 +851,12 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { events.pop(); } let mut events = events.into_iter(); - if empty && let Some(first) = events.next() { - app.session.script_window_answer(first)?; + if empty + && let Some(first) = events.next() + && let Err(e) = app.session.script_window_answer(first) + { + with_window(app, |d| d.drafts = drafts); + return Err(e); } let mut later: Vec = events.filter_map(|e| queued(&w, &e)).collect(); if deferred { diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 4a14fe4d2a..ab34502299 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -144,8 +144,13 @@ fn try_open(app: &mut VectorcraftApp) -> Result { let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let cuts = cut_options(app); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { - ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)) + let dialog = ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 4e9c73bbf3..26a6766d7e 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -515,7 +515,11 @@ pub(crate) fn open(app: &mut VectorcraftApp) { } } apply_links(&mut f, shared); - let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| form(fields, shared, lengths)); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| match canvas { + Some(canvas) => form(fields, shared, lengths).canvas(canvas), + None => form(fields, shared, lengths), + }); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; if let Some(id) = open_held_with(app, dialog, move |app, result| ok(app, &ctx, result), options) { app.object_dialogs.each = diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ea6dcb4c69..b0ed6bddbb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -40,12 +40,26 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { { // These panels lay out forms. Collection panels own their scrolling viewport // and reserve their own footer outside it. - Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); + let scroll = if empty_state_only(app, id) { Scroll::vertical().overlay().at_rest() } else { Scroll::vertical() }; + Stack::new().id_salt(id).fill().scroll(scroll).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); } None => memoized(app, ui, id, icon_panel_body), } } +/// Whether panel `id` is the Character or Paragraph panel showing only its empty state. Its body then scrolls with an +/// overlay bar, which leaves the message its full width: a scroll body measures its content beside the bar's lane, and a +/// message that wraps onto one more line there kept a bar it did not need. This case is temporary: the craft-libs pin +/// bump that includes craft-libs#4898, which fixes the measuring run, removes it and the two `shows_only_empty_state` +/// helpers. +fn empty_state_only(app: &VectorcraftApp, id: &str) -> bool { + match id { + "character" => panels::character::shows_only_empty_state(app), + "paragraph" => panels::paragraph::shows_only_empty_state(app), + _ => false, + } +} + /// The Layers panel's body. fn layers_body(p: &mut BodyProps<'_>, ui: &mut Ui) { #[cfg(test)] @@ -180,6 +194,8 @@ mod tests { static DIRECT: Cell = const { Cell::new(false) }; /// The panel [`draw`] shows. static SHOWN: RefCell<&'static str> = const { RefCell::new("") }; + /// The height of the body [`draw_unscrolled`] drew last. + static UNSCROLLED_HEIGHT: Cell = const { Cell::new(0.0) }; } pub(super) fn count_run() { @@ -202,6 +218,9 @@ mod tests { fn panel(id: &'static str) -> Panel { SHOWN.with(|s| *s.borrow_mut() = id); let mut app = VectorcraftApp::new(Session::new(), Default::default()); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends, and the + // bodies' inputs hold that generation: wait for it, or an idle frame that it ends in runs the body. + vectorcraft_text::FontDb::global().family_list(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); let mut panel = Panel::new(app, draw); @@ -356,6 +375,75 @@ mod tests { assert!(panel.shows_value_with(|v| v.starts_with('7')), "the panel shows the 7 pt weight: {:?}", panel.values()); } + /// The Character or Paragraph empty state, drawn without a scroll body; [`UNSCROLLED_HEIGHT`] holds its height. + fn draw_unscrolled(app: &mut VectorcraftApp, ui: &mut Ui) { + let top = ui.min_rect().top(); + crate::panels::show_icon_panel(app, ui, SHOWN.with(|s| *s.borrow())); + UNSCROLLED_HEIGHT.with(|h| h.set(ui.min_rect().bottom() - top)); + } + + /// Panel `id` drawn by `draw` over a document with nothing selected, in `room`. + fn empty_panel(id: &'static str, draw: fn(&mut VectorcraftApp, &mut Ui), room: egui::Vec2) -> Panel { + SHOWN.with(|s| *s.borrow_mut() = id); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.room(room); + panel.frame(); + panel.frame(); + panel + } + + /// The empty state's texts as `panel` paints them, in paint order. + fn empty_state_texts(panel: &Panel, message: &str) -> Vec<(String, egui::Rect)> { + panel.texts().into_iter().filter(|(text, _)| text == "No text selected" || text == message).collect() + } + + /// In a dock group tall enough for the Character or Paragraph empty state at the group's full width, the dock body + /// lays the message out as an unscrolled body does, and the wheel does not move it: the body shows no scroll bar + /// and keeps no room for one. The groups are a little wider than the widths at which the message wraps onto one + /// line fewer, so beside a bar's lane it would take one more line, and from the empty state's own height to about + /// one line more. + #[test] + fn an_empty_state_that_fits_its_group_does_not_scroll() { + let cases = [ + ("character", "Select a text object to edit its character attributes."), + ("paragraph", "Select a text object to edit its paragraph attributes."), + ]; + for (id, message) in cases { + let height_at = |width: f32| { + let tall = empty_panel(id, draw_unscrolled, egui::vec2(width, 1600.0)); + assert_eq!(empty_state_texts(&tall, message).len(), 2, "{id} shows its empty state: {:?}", tall.texts()); + UNSCROLLED_HEIGHT.with(Cell::get).ceil() + }; + let mut widths = Vec::new(); + let mut last = height_at(120.0); + for step in 1..=50 { + let width = 120.0 + 4.0 * step as f32; + let height = height_at(width); + if height < last { + widths.extend([width, width + 2.0]); + } + last = height; + } + assert!(widths.len() >= 4, "{id}: the message wraps onto fewer lines as the group widens"); + for width in widths { + let height = height_at(width); + for extra in [0.0, 4.0, 8.0, 12.0] { + let room = egui::vec2(width, height + extra); + let unscrolled = empty_panel(id, draw_unscrolled, room); + let mut docked = empty_panel(id, draw, room); + docked.scroll_at(egui::pos2(width / 2.0, room.y / 2.0), -120.0); + assert_eq!( + empty_state_texts(&docked, message), + empty_state_texts(&unscrolled, message), + "{id} at {room:?}: the docked empty state is laid out and stays where the unscrolled one is" + ); + } + } + } + } + /// The texts `id`'s body paints after idle frames, shown in its `MemoView` or, with `direct`, directly. fn texts(id: &'static str, direct: bool) -> Vec<(String, egui::Rect)> { DIRECT.with(|d| d.set(direct)); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index bb4156a036..ac6c435613 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6622,6 +6622,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg `answers` must be a list of answers `answers` ha de ser una llista de respostes @msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes +@msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat +@msg The list's items changed before the choice was taken Els elements de la llista han canviat abans que es prengués l'elecció @msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB @msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` @msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f5f44e308f..e2ad7a7d71 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9147,6 +9147,8 @@ breakText Glyphs Glyfy @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` musí uvádět indexy kotevních bodů (0, 1, 2…), ne {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí +@msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována +@msg The list's items changed before the choice was taken Položky seznamu se změnily dříve, než byla volba převzata @msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB @msg `answers` must be a list of answers `answers` musí být seznam odpovědí @msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cfc7dd75f4..88948a328d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -228,6 +228,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name} @msg `answers` must be a list of answers `answers` skal være en liste med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt +@msg The list's items changed before the choice was taken Listens elementer blev ændret, før valget blev modtaget @msg `answers` is larger than 1 MiB `answers` er større end 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2bd23256bb..2999862096 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8585,6 +8585,8 @@ breakText Glyphs Glyphen @msg `align` must be a string `align` muss ein String sein @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten +@msg The list's items changed before the choice was taken Die Einträge der Liste haben sich geändert, bevor die Auswahl übernommen wurde @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c2044cfd3e..3396a06dab 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2812,6 +2812,8 @@ liquify-list-end {0}, {1} {0} και {1} @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων @msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις +@msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε +@msg The list's items changed before the choice was taken Τα στοιχεία της λίστας άλλαξαν πριν ληφθεί η επιλογή @msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB @msg `answers[{i}]` {e} το `answers[{i}]` {e} @msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 58ed9b8a5b..55e2ae101d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5091,6 +5091,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg `answers` must be a list of answers `answers` debe ser una lista de respuestas @msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas +@msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado +@msg The list's items changed before the choice was taken Los elementos de la lista cambiaron antes de que se tomara la elección @msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB @msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` @msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 47a1158f51..1116fcc5c6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5334,6 +5334,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg `answers` must be a list of answers `answers` on oltava vastausten luettelo @msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty +@msg The list's items changed before the choice was taken Luettelon kohteet muuttuivat ennen kuin valinta otettiin vastaan @msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB @msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` @msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 57f6132977..ef77114ade 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9014,6 +9014,8 @@ breakText Glyphs Glyphes @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé +@msg The list's items changed before the choice was taken Les éléments de la liste ont changé avant que le choix soit pris en compte @msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio @msg `answers` must be a list of answers `answers` doit être une liste de réponses @msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1dcabb8251..14094a4a60 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7830,6 +7830,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए @msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं +@msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई +@msg The list's items changed before the choice was taken चुनाव लिए जाने से पहले सूची के आइटम बदल गए @msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0879de9fda..0bcb97fb7f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9018,6 +9018,8 @@ breakText Glyphs Glifák @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz +@msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva +@msg The list's items changed before the choice was taken A lista elemei megváltoztak, mielőtt a választás érvénybe lépett @msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál @msg `answers` must be a list of answers `answers`: válaszok listája kell @msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7ac37a8366..f831b57517 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -135,6 +135,8 @@ @msg {name}: `answers` has no answer left for this dialog {name}: `answers` tidak memiliki jawaban tersisa untuk dialog ini @msg `answers` must be a list of answers `answers` harus berupa daftar jawaban @msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan +@msg The list's items changed before the choice was taken Item daftar berubah sebelum pilihan diterima @msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB @msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` @msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 27e3c7d150..32e5cd85d7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8626,6 +8626,8 @@ breakText Glyphs Glifi @msg `align` must be a string `align` deve essere una stringa @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato +@msg The list's items changed before the choice was taken Le voci dell'elenco sono cambiate prima che la scelta fosse acquisita @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e64afd70a4..04289a09a4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7428,6 +7428,8 @@ axis Y Axis Y 軸 @msg `align` must be a string `align` には文字列を指定してください @msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています +@msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした +@msg The list's items changed before the choice was taken 選択が受け付けられる前にリストの項目が変更されました @msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています @msg `answers` must be a list of answers `answers` には回答のリストを指定してください @msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6df54defaf..0b034bdcf9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -177,6 +177,8 @@ @msg `answer` for this {kind} dialog must be one of: {_1} დიალოგისთვის (ტიპი: {kind}) `answer` უნდა იყოს ერთ-ერთი: {_1} @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს +@msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა +@msg The list's items changed before the choice was taken სიის ელემენტები შეიცვალა არჩევანის მიღებამდე @msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია @msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია @msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 35e6a09881..9ed6977dfb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8784,6 +8784,8 @@ breakText Glyphs 글리프 @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`에는 앵커 인덱스(0, 1, 2…)를 나열해야 합니다: {v} @msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다 +@msg The list's items changed before the choice was taken 선택이 적용되기 전에 목록의 항목이 변경되었습니다 @msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다 @msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다 @msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 698f0a3f0f..0ef7948d89 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6645,6 +6645,8 @@ imageTrace Outline Contour @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` moet ankerindexen bevatten (0, 1, 2…), niet {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden +@msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard +@msg The list's items changed before the choice was taken De items van de lijst zijn gewijzigd voordat de keuze werd overgenomen @msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB @msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn @msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8ae2ebecf9..9eb552d7a4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8829,6 +8829,8 @@ breakText Glyphs Glify @msg `align` must be a string `align` musi być ciągiem znaków @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi +@msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane +@msg The list's items changed before the choice was taken Elementy listy zmieniły się, zanim wybór został przyjęty @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c7772edf6b..b9f399e3d8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9200,6 +9200,8 @@ swatch Yellow Green Verde-amarelado @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` deve listar índices de pontos de ancoragem (0, 1, 2…), não {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas +@msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido +@msg The list's items changed before the choice was taken Os itens da lista mudaram antes de a escolha ser aplicada @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 10583bf9e8..b3648d114c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5116,6 +5116,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg `answers` must be a list of answers `answers` должен быть списком ответов @msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено +@msg The list's items changed before the choice was taken Элементы списка изменились до того, как выбор был принят @msg `answers` is larger than 1 MiB `answers` больше 1 МиБ @msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` @msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9093d1abdd..c1b66a1ad0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4988,6 +4988,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg `answers` must be a list of answers `answers` måste vara en lista med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte +@msg The list's items changed before the choice was taken Listans objekt ändrades innan valet togs emot @msg `answers` is larger than 1 MiB `answers` är större än 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e77c4bae56..cdbc54b58d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1035,6 +1035,7 @@ fn toggled_labels() -> Vec { "type.hiddenCharacters", "view.gradientAnnotator", "view.livePaintGaps", + "view.curvatureComb", "view.artboards", "view.template", "view.rulers", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d17c9ba3bf..f037a841b3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7806,6 +7806,8 @@ axis Y Axis Y ekseni @msg `align` must be a string `align` bir dize olmalıdır @msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı +@msg The list's items changed before the choice was taken Seçim alınmadan önce listenin öğeleri değişti @msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük @msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır @msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8317055f65..6e3a291eae 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8785,6 +8785,8 @@ breakText Glyphs Гліфи @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` має містити індекси опорних точок (0, 1, 2…), а не {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено +@msg The list's items changed before the choice was taken Елементи списку змінилися до того, як вибір було прийнято @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5ce16f684a..7da1aa1c06 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5616,6 +5616,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời @msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời +@msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại +@msg The list's items changed before the choice was taken Các mục của danh sách đã thay đổi trước khi lựa chọn được nhận @msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB @msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` @msg must have exactly `kind` and `value` phải có đúng `kind` và `value` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5e05c98008..7631ba753a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8837,6 +8837,8 @@ breakText Glyphs 字形 @msg `align` must be a string `align` 必须是字符串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在采用选择之前,列表的项目已更改 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52a09f56b4..bd3c03e59d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8780,6 +8780,8 @@ breakText Glyphs 字符 @msg `align` must be a string `align` 必須是字串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在採用選擇之前,清單的項目已變更 @msg `answers` is larger than 1 MiB `answers` 大於 1 MiB @msg `answers` must be a list of answers `answers` 必須是答案清單 @msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a51817a7f1..66583823b3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4,6 +4,7 @@ //! (view/window) here and everything else to the engine. The same entry point serves menus, //! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. @@ -74,6 +75,7 @@ pub mod recovery; pub mod render_worker; pub mod retype_runs; pub mod screen_color; +pub mod script_palettes; pub mod script_runs; pub mod scripts_menu; mod settings; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d94e4feef4..3ecff4863f 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -252,7 +252,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { .collect(); let unlock: Vec = [entry("Unlock Selected", sel.clone(), false), entry("Unlock All", (0..n).collect(), false)].into_iter().flatten().collect(); - for (label, items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + for (label, mut items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + // The selected and unselected targets are disjoint. If All matches a narrower row, it + // is adjacent to it after empty rows are removed. Keep the narrower row for that command key. + items.dedup_by(|a, b| matches!((a, b), (Node::Item(a), Node::Item(b)) if a.command == b.command)); if !items.is_empty() { v.push(sub(label, items)); } diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 66353c55be..71feba3195 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -76,7 +76,7 @@ const MENU_ONLY_COMMANDS: [&str; 5] = ["imageTrace.make", "imageTrace.makeAndExp /// action ([`plays_in_app`]): Outline, Pixel Preview, Trim View, Presentation Mode and Screen Mode, /// the zoom, fit and rotate view items, and the items that show or hide or turn snapping on or off. /// The saved-view slots are not among them. -const UI_STEP_COMMANDS: [&str; 30] = [ +const UI_STEP_COMMANDS: [&str; 31] = [ "view.outline", "view.pixelPreview", "view.trimView", @@ -100,6 +100,7 @@ const UI_STEP_COMMANDS: [&str; 30] = [ "view.gradientAnnotator", "view.cornerWidget", "view.livePaintGaps", + "view.curvatureComb", "view.guides", "view.smartGuides", "view.grid", diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 549d31b876..52ec3b33aa 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -29,6 +29,7 @@ fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { "type.hiddenCharacters" => if v.hidden_chars { "Hide Hidden Characters" } else { "Show Hidden Characters" }.into(), "view.gradientAnnotator" => if v.gradient_annotator { "Hide Gradient Annotator" } else { "Show Gradient Annotator" }.into(), "view.livePaintGaps" => if v.live_paint_gaps { "Hide Live Paint Gaps" } else { "Show Live Paint Gaps" }.into(), + "view.curvatureComb" => if v.curvature_comb { "Hide Curvature Comb" } else { "Show Curvature Comb" }.into(), _ => return None, }; Some(text) @@ -356,6 +357,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Show Gradient Annotator", "Hide Live Paint Gaps", "Show Live Paint Gaps", + "Hide Curvature Comb", + "Show Curvature Comb", "Hide Artboards", "Show Artboards", "Hide Rulers", diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index cd4d481cc5..84125b1a43 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -144,7 +144,7 @@ fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let (prefs, v) = (&s.prefs, &app.ui.view); (prefs.font_preview, prefs.font_samples_on_white, prefs.font_names_in_english, crate::workspaces::current_name(&app.ui)).hash(&mut h); (v.edges, v.templates, v.corner_widgets, v.shape_widgets, v.text_threads, v.hidden_chars, v.gradient_annotator).hash(&mut h); - (v.live_paint_gaps, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); + (v.live_paint_gaps, v.curvature_comb, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); (app.outline_view(), s.guides_locked(), s.slices_hidden()).hash(&mut h); // The Align To choice: Object › Align's checks and the Distribute buttons with the Artboard tool. app.ui.align_to.hash(&mut h); @@ -477,7 +477,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft: Ok(catalog) => { // While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it, // and the Type tool's commands run while it types. - let catalog = catalog.typing_rule(TypingRule::AllWait); + // The document canvas also defaults to Cmd+0, but its Fit on Screen stops at actual size. + // Leave that chord to VectorCraft's Fit Artboard in Window. + let fit_on_screen = CommandRef::from(craft::ui::canvas::ViewCommands::FitOnScreen); + let catalog = catalog.typing_rule(TypingRule::AllWait).replace_defaults(fit_on_screen.id, Vec::new()); let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)); let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new())); Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys))) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 50e2a7606e..35b09d45b6 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -408,7 +408,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { +fn run_ui_part4(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { let flag = |b: &mut bool| { *b = !*b; Ok(json!(*b)) @@ -419,6 +419,8 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option crate::panels::align::run_align_to(app, v), "view.gradientAnnotator" => flag(&mut app.ui.view.gradient_annotator), "view.livePaintGaps" => flag(&mut app.ui.view.live_paint_gaps), + "view.curvatureComb" if !(p.is_null() || p.as_object().is_some_and(|m| m.is_empty())) => Err("view.curvatureComb takes no parameters".into()), + "view.curvatureComb" => flag(&mut app.ui.view.curvature_comb), "effect.last" => match app.last_effect.clone() { Some((e, params)) => crate::dialogs::effect::open_last(app, &e, params), None => Err("no effect applied yet".into()), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index a59fe7f769..39909b57eb 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -773,6 +773,7 @@ fn last_effect_dialog_and_view_toggles() { ("view.textThreads", "Hide Text Threads", "Show Text Threads"), ("view.gradientAnnotator", "Hide Gradient Annotator", "Show Gradient Annotator"), ("view.livePaintGaps", "Show Live Paint Gaps", "Hide Live Paint Gaps"), + ("view.curvatureComb", "Show Curvature Comb", "Hide Curvature Comb"), ("type.hiddenCharacters", "Show Hidden Characters", "Hide Hidden Characters"), ("view.template", "Hide Template", "Show Template"), ] { diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 7cd830ef05..e044ac2580 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -678,6 +678,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec c("Hide Gradient Annotator", "view.gradientAnnotator"), c("Hide Corner Widget", "view.cornerWidget"), c("Show Live Paint Gaps", "view.livePaintGaps"), + c("Show Curvature Comb", "view.curvatureComb"), Sep, sub( "Guides", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f783fd4464..6f955c6dba 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -262,6 +262,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 1a47d5a7d2..4ec0a72a0c 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -21,6 +21,7 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked}; +use craft::ui::dialog::DialogId; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -73,6 +74,9 @@ pub(crate) struct Runtime { /// A panel just floated out of a tool rail, whose window takes over the held press on the next /// pass, with the pointer at this point inside it ([`continue_move`]). hand_over: Option<(String, egui::Vec2)>, + /// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic + /// Panels leaves the flyout open ([`show`]). + flyout_dialogs: Vec<(DialogId, u64)>, } /// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the @@ -1317,15 +1321,24 @@ fn window_viewport(app: &VectorcraftApp, panel: &str) -> Option