From 81870d2989c985a8cbf889ca5ca4488cdfeb8971 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 23:08:36 +0000 Subject: [PATCH 01/49] Text: stop COLR outline work past the budget and cap one outline's path elements --- crates/text/src/colr.rs | 12 +++++-- crates/text/src/fontdb/glyph_pen.rs | 53 ++++++++++++++++++++++++++++- crates/text/src/fontdb/lookup.rs | 2 +- crates/text/src/tests/colr.rs | 22 ++++++++++++ 4 files changed, 85 insertions(+), 4 deletions(-) diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 9045a4f550..a4be3b2160 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -114,7 +114,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) if let Some(g) = font.outline_glyphs().get(gid) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen); } - let mut path = pen.0; + let mut path = pen.finish(); path.apply_affine(FLIP); path } @@ -359,7 +359,9 @@ impl ColorPainter for Tree<'_> { } fn push_clip_glyph(&mut self, glyph_id: GlyphId) { - let mut clip = outline(self.font, self.location, glyph_id); + // Past the budget the glyph is drawn as its outline anyway: later layers are not drawn, + // only opened and closed so the callbacks stay balanced. + let mut clip = if self.too_large { BezPath::new() } else { outline(self.font, self.location, glyph_id) }; clip.apply_affine(self.transform()); self.charge(&clip); self.open(Open { clip: Some(clip), blend: None, children: vec![], flooded: false }); @@ -381,6 +383,9 @@ impl ColorPainter for Tree<'_> { self.unsupported.get_or_insert("a fill outside any glyph"); return; }; + if self.too_large { + return; + } let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; if at + 1 == self.groups.len() && let Some(g) = self.groups.last_mut() @@ -392,6 +397,9 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { + if self.too_large { + return; + } let mut path = outline(self.font, self.location, glyph_id); path.apply_affine(self.transform()); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index 7f02517037..504503b70f 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,23 +7,74 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } -/// A pen drawing outlines y down, as text space has them. +/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's +/// composite glyph repeating a large component many times) is drawn as nothing, not kept. +pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; + +/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path +/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path. pub(crate) struct FlipPen(pub(crate) BezPath); +impl FlipPen { + /// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`]. + pub(crate) fn finish(self) -> BezPath { + if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 } + } + + fn full(&self) -> bool { + self.0.elements().len() >= MAX_OUTLINE_ELEMENTS + } +} + impl OutlinePen for FlipPen { fn move_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.move_to((x as f64, -y as f64)); } fn line_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.line_to((x as f64, -y as f64)); } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); } fn close(&mut self) { + if self.full() { + return; + } self.0.close_path(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pen_past_the_cap_gives_nothing() { + let mut pen = FlipPen(BezPath::new()); + pen.move_to(0.0, 0.0); + for i in 0..MAX_OUTLINE_ELEMENTS + 10 { + pen.line_to(i as f32, 1.0); + } + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments"); + assert!(pen.finish().elements().is_empty()); + let mut small = FlipPen(BezPath::new()); + small.move_to(0.0, 0.0); + small.line_to(1.0, 1.0); + assert_eq!(small.finish().elements().len(), 2); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 71e8e7ab88..30b4b8229c 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -535,7 +535,7 @@ impl FontDb { { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); } - let p = Arc::new(pen.0); + let p = Arc::new(pen.finish()); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index 212882ce7a..43c833406c 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -411,3 +411,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() { assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}"); assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}"); } + +/// A layer list that reuses one run of layers many times grows the tree past its node cap: the +/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn. +#[test] +fn layers_repeating_a_run_of_layers_pass_the_cap() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32(); + let o = GlyphId16::new(u16::try_from(o).unwrap()); + let font = |runs: u8| { + // 255 glyph layers, then `runs` layers that each repeat all of them. + let mut layers: Vec = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect(); + layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0))); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into(); + colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into(); + crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap() + }; + assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit"); + assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not"); +} From 2ab519a6308b2d9d9e02e898f680a5cdfe31e6e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:04:09 -0800 Subject: [PATCH 02/49] Packaging Tools: a crease, partial cut or perforation can fold at its own angle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Set Fold Angle… (Object › Plug-ins › Packaging Tools) gives the selected fold lines their own fold angle, from -180° to 180°, in place of their role's 90° away from or toward the print, to the millionth of a degree; reset: true takes it away. The angle is kept in the line's data under vc-fold-angle, which native files and SVG with Preserve Editing keep and plain SVG export leaves out of the path's attributes. A line keeps its angle when it is given another role. The Fold Lines panel shows a Fold Angle field for the selected lines it can change, empty when they differ, and a Reset button. - addon.packaging.setFoldAngle is one undo step, none when nothing changes, and is dimmed while the selection holds no Crease, Partial Cut or Perforation line that is neither locked nor hidden. An angle stored as other text for the same number counts as unchanged. - addon.packaging.roles also returns foldLines, foldAngle, ownAngles and storedAngles for the lines Set Fold Angle can change, which are none while nothing is selected. - A hinge folds at the angle of the line with the most length in it, counting a line the planar map splits into pieces whole and a line's subpaths on top of each other once; among lines of equal length the lowest id wins, in any line order. Before, it took the role of its longest piece, so a hinge whose lines have different roles can now fold the other way when a split line is the longer one. - Fold Preview: a panel folded flat onto another (180°) is drawn behind that panel's printed side, and at -180° in front of it; a flap folded back over a folded panel lies between it and the panel before; a 0° hinge keeps its panel level with its parent. Panels in one plane keep their order when the panels they fold from are seen edge on, and a panel that comes round onto another's plane lies on the side it came from. Only panels in one plane stack by these rules; panels in different planes go by depth, so folds a hair short of flat stay in order wherever the blank lies in the document. The stack is worked out from the blank's largest panel whichever panel the window folds about, so a double-click on another panel moves the blank without changing which panel shows. Panels that 90° folds bring into one plane, such as a carton's closing flaps, now stack by these rules too. - Set Fold Angle…'s dialog keeps the angle within -180° to 180° as it is typed, as the panel's field does. Both show every decimal place the angle has. ui.menuDialog opens the dialog for addon.packaging.setFoldAngle, and gives the command's reason while the selection holds no line it can change. - Set Fold Angle skips a locked or hidden path of a compound path that is named by id or selected without its compound. addon.packaging.setRole (Make Cut Line and the other Make ... Line items) now skips it too; before, it changed the whole compound. - Folding: a hinge whose middle falls in a cutout turns its panel by the side its parent lies on next to the hinge's own pieces, not by a point anywhere inside the parent, which folded a panel the wrong way when the parent also ran on past the hinge. Docs: docs/mcp.md (Fold angles), ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/addons.rs | 2 +- crates/engine/src/cmd/addons/packaging.rs | 8 +- .../engine/src/cmd/addons/packaging/angle.rs | 250 ++++ .../src/cmd/addons/packaging/angle/tests.rs | 409 +++++++ .../engine/src/cmd/addons/packaging/check.rs | 6 +- .../engine/src/cmd/addons/packaging/fold.rs | 2 +- .../engine/src/cmd/addons/packaging/roles.rs | 73 +- .../engine/src/cmd/addons/packaging/tests.rs | 16 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/mcp/src/ui_catalog.rs | 2 +- crates/three-d/src/fold.rs | 63 +- crates/three-d/src/fold/pose.rs | 157 ++- crates/three-d/src/fold/raster.rs | 248 +++- crates/three-d/src/fold/raster/tests.rs | 1027 ++++++++++++++++- crates/three-d/src/fold/tests.rs | 207 +++- crates/ui-egui/src/addons/packaging.rs | 87 +- .../src/addons/packaging/preview/tests.rs | 2 + crates/ui-egui/src/addons/packaging/tests.rs | 159 ++- crates/ui-egui/src/dialogs/command.rs | 9 + crates/ui-egui/src/dialogs/form.rs | 8 + crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/menus/invoke.rs | 2 + crates/ui-egui/src/menus/run.rs | 5 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/numeric.rs | 15 + docs/mcp.md | 67 +- 56 files changed, 2882 insertions(+), 90 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/angle.rs create mode 100644 crates/engine/src/cmd/addons/packaging/angle/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index ea37f12caf..9b15d9afc3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 359fc8761f..67a75de367 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -839,7 +839,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{fold_source, print_hidden}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..32f8cfa645 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{fold_source, print_hidden}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..779b044358 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -2,13 +2,16 @@ //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each //! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold -//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu -//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set +//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins › +//! Packaging Tools) and its Fold Lines panel are the UI's. +mod angle; mod check; mod fold; mod roles; +pub use angle::{FoldAngles, selection_fold_angles}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -17,6 +20,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..b458a3e410 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -0,0 +1,250 @@ +//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease, +//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of +//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a +//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side. + +use std::collections::HashSet; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::kept_angle; + +use super::super::super::edit::refuse_symbol_part; +use super::super::super::overprint::edit_counted; +use super::super::super::pathops::number_given; +use super::super::super::{CommandSpec, bad, cmd, switch_or}; +use super::check::kind; +use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots}; +use crate::{Result, Session}; + +/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export +/// leaves `vc-` keys out. +pub(crate) const KEY: &str = "vc-fold-angle"; + +const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The range a fold angle may take, in degrees. +const RANGE: std::ops::RangeInclusive = -180.0..=180.0; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.setFoldAngle", + "Set Fold Angle…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}", + has_fold_line, + set_fold_angle + )] +} + +/// Why Set Fold Angle has nothing to change. +const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + +/// The last answer of [`has_fold_line`], with what it was for. +struct Answer { + /// The document (a weak reference keeps another document from taking the same address). + doc: Weak, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + found: bool, +} + +thread_local! { + /// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the + /// document, its revision and the objects looked at. + static LAST_ANSWER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object. +fn has_fold_line(s: &Session) -> std::result::Result<(), String> { + refuse_symbol_part(s).map_err(|e| e.to_string())?; + let st = s.doc().map_err(|e| e.to_string())?; + let objects = &st.selection.objects; + let kept = LAST_ANSWER.with_borrow(|last| match last { + Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found), + _ => None, + }); + let found = kept.unwrap_or_else(|| { + // An id of no object (given as `ids`) is left to the command, which names it. + let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects); + LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found })); + found + }); + if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) } +} + +/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through +/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`] +/// takes them, an object inside another one given is left out (a crease in a selected layer counts +/// no more than the layer does), a layer is left out, and a path of a compound path stands for the +/// compound path, which holds its role, unless it is locked or hidden. +fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool { + fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool { + match &n.kind { + // A group's clipping path draws no stroke. + NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)), + _ => hit(n), + } + } + let table = RoleTable::of(d); + let editable = d.editable(); + let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id); + let given: HashSet = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + let a = d.ancestry(id)?; + let (_, up) = a.split_last()?; + if up.iter().any(|p| given.contains(p)) { + return None; + } + match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) { + // A locked or hidden path of a compound path is left out, as `editable_members` leaves it. + Some(_) if !editable(id) => None, + Some(compound) => Some(compound), + None => Some(id), + } + }; + // An object given twice is looked through once. + let mut seen = HashSet::new(); + roots + .iter() + .filter_map(|id| outer(*id)) + .filter(|id| seen.insert(*id)) + .filter_map(|id| d.node(id)) + .filter(|n| !n.is_layer()) + .any(|n| find(n, &hit)) +} + +/// The text `n`'s data holds under [`KEY`], if any. +fn stored(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from +/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as +/// no angle of its own. +pub(super) fn own_angle(n: &Node) -> Option { + stored(n)?.trim().parse::().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle) +} + +/// Whether a line with `role` folds: every role but Cut. +pub(super) fn folds(role: Role) -> bool { + kind(role).fold_angle().is_some() +} + +/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed. +fn store(d: &mut Document, id: NodeId, angle: Option) -> bool { + // `+ 0.0` turns -0 into 0, so a line set to 0° reads "0". + let text = angle.map(|a| format!("{}", a + 0.0)); + // Read first: taking the node to change it copies it, its geometry included. An angle stored + // as other text for the same number ("45.0") is kept; a reset removes any stored text. + let same = |n: &Node| match angle { + Some(a) => own_angle(n) == Some(a), + None => stored(n).is_none(), + }; + if d.node(id).is_none_or(same) { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.edit_attrs(|a| match text { + Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = text, + None => a.data.push((KEY.into(), text)), + }, + None => a.data.retain(|(k, _)| k != KEY), + }); + true +} + +fn set_fold_angle(s: &mut Session, p: &Value) -> Result { + let angle = number_given(p, "angle", SET_FOLD_ANGLE)?; + let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?; + let angle = match (angle, reset) { + (Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")), + (None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")), + (Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")), + // Kept to the millionth of a degree, the angle the line folds at. + (a, _) => a.map(kept_angle), + }; + let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?; + let d = &s.doc()?.doc; + let (targets, skipped) = role_targets(d, &roots, false); + let mut skipped = skipped + named; + let mut ids = folding(d, &RoleTable::of(d), &targets); + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + skipped += targets.len() - ids.len(); + if ids.is_empty() { + return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE)); + } + let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" }; + let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order. +fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect() +} + +/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip +/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FoldAngles { + /// How many lines that fold it can change. + pub lines: usize, + /// The angle they all fold at (their own or their role's); `None` when they differ or there + /// are none. + pub angle: Option, + /// How many of them have an angle of their own. + pub own: usize, + /// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away. + pub stored: usize, +} + +/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them +/// with no `ids` (nothing, while it would refuse the selection). +pub fn selection_fold_angles(s: &Session) -> FoldAngles { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots), + _ => FoldAngles::default(), + } +} + +/// The [`FoldAngles`] of the outermost objects `roots` of `d`. +pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { + let table = RoleTable::of(d); + let editable = d.editable(); + let mut f = FoldAngles::default(); + for n in role_targets(d, &editable_members(d, roots.to_vec()).0, false).0.iter().filter_map(|id| d.node(*id)) { + // The role first: whether an object can be edited can take its bounds to find out. + if let Some(role) = table.role_of(n) + && folds(role) + && editable(n.id) + { + f.add(n, role); + } + } + f +} + +impl FoldAngles { + /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. + pub(super) fn add(&mut self, n: &Node, role: Role) { + let Some(default) = kind(role).fold_angle() else { return }; + let own = own_angle(n); + let a = own.unwrap_or(default); + self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) }; + self.lines += 1; + self.own += usize::from(own.is_some()); + self.stored += usize::from(stored(n).is_some()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -0,0 +1,409 @@ +//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it. + +use serde_json::{Value, json}; + +use super::{KEY, fold_angles, own_angle}; +use crate::*; + +const SET: &str = "addon.packaging.setFoldAngle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(SET, &p).unwrap_err().to_string() +} + +/// The text object `id`'s data holds under the fold angle key. +fn stored(s: &Session, id: u64) -> Option { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone())) +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases: top, right, bottom, left). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of +/// its outline's points (absolute moves and lines only) is above the base. +fn top_wall(p: &Value) -> bool { + let d = p["outline"].as_str().unwrap(); + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + (ys.0 + ys.1) / 2.0 < 140.0 +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +#[test] +fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + assert_eq!(steps(&s), before + 1, "one undo step"); + // The same angle again changes nothing and records no undo step. + let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // An angle is kept to the millionth of a degree, so one closer to 45 than that is 45. + let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}"); + s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap(); + assert_eq!(stored(&s, creases[3]).as_deref(), Some("180")); + s.execute("edit.undo", &json!({})).unwrap(); + // A number as text, and the selection when ids is left out; -0 is kept as 0. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + let r = s.execute(SET, &json!({"angle": "-0"})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "{r}"); + assert_eq!(stored(&s, creases[1]).as_deref(), Some("0")); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}"); + assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None)); + // Nothing left to reset: no undo step. + let at = steps(&s); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at)); + // Undo brings the angle back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); +} + +#[test] +fn bad_angles_and_targets_are_refused() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let plain = path(&mut s, "M10 10 L50 50"); + let before = steps(&s); + let ids = json!([creases[0]]); + assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`")); + assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both")); + assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false")); + // A cut line and a path without a role do not fold. + assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation")); + // An id of no object is named as such, alone or beside a crease. + assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999")); + assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); + // The ends of the range are allowed; cut lines and plain paths among fold lines are skipped. + let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}"); + s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("180")); + assert_eq!(stored(&s, outline), None); +} + +#[test] +fn set_fold_angle_is_dimmed_without_a_line_it_can_change() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok(); + assert!(!enabled(&s), "nothing selected"); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!(!enabled(&s), "a cut line does not fold"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap(); + assert!(enabled(&s)); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed"); + // A group holding a crease is enough. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + assert!(enabled(&s)); + // A layer selected with a crease in it: the crease is inside the layer, which is left out, as + // Set Fold Angle itself leaves them out. + let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap(); + s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert!(!enabled(&s), "dimmed as the command refuses it"); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); + // With nothing selected the counts are the document's, but Set Fold Angle takes no line. + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute(SET, &json!({"angle": 30})).is_err()); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!(r["scope"].as_str(), Some("document"), "{r}"); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}"); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); +} + +#[test] +fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold"); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(1), "{r}"); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line"); +} + +#[test] +fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap(); + let f = crate::cmd::selection_fold_angles(&s); + assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}"); +} + +#[test] +fn a_locked_crease_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(stored(&s, creases[1]), None); +} + +#[test] +fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320")); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + role(&mut s, "crease", &[compound]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(NodeId(a)) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation")); + // Named twice, it is skipped once. + let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, compound), None); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + assert_eq!(stored(&s, compound), None); + // With its compound, given or selected, the locked path is part of the compound, not skipped. + let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute("select.set", &json!({"ids": [compound, a]})).unwrap(); + let r = s.execute(SET, &json!({"angle": 25})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap(); + // The compound named by id takes the angle; its other path, not locked, names it too. + let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap(); + assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}"); + assert_eq!(stored(&s, compound).as_deref(), Some("30")); +} + +#[test] +fn a_damaged_angle_reads_as_none_of_its_own() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap(); + for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] { + n.edit_attrs(|a| { + a.data.retain(|(k, _)| k != KEY); + a.data.push((KEY.into(), text.into())); + }); + assert_eq!(own_angle(&n), want, "{text:?}"); + } +} + +#[test] +fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let id = NodeId(creases[0]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into()))); + } + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0")); + s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]), None); + // A reset also removes text that is not an angle. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}"); +} + +#[test] +fn a_line_keeps_its_own_angle_through_a_role_change() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + role(&mut s, "partialCut", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); + role(&mut s, "none", &[creases[0]]); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + role(&mut s, "crease", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); +} + +#[test] +fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned()); + assert!(svg.contains(" = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + assert!(angles.contains(&120.0), "{r}"); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // The top wall (y 100 to 140) folds at 45°. + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut angles: Vec = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + angles.sort_by(f64::total_cmp); + assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]); + for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) { + let z = vector(&p["frame"]["z"]); + let top = top_wall(p); + let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}"); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut up = 0; + for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) { + // The top wall folds toward the print, so its printed side faces back over the base + // (toward -y in the y-up frame); the other walls stand square to the base as before. + let top = top_wall(p); + let z = vector(&p["frame"]["z"]); + if top { + assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}"); + up += 1; + } else { + assert!(z[2].abs() < 1e-9, "{p}"); + } + } + assert_eq!(up, 1); +} + +#[test] +fn roles_reports_the_angle_the_selected_fold_lines_share() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}"); + s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap(); + assert!(r["foldAngle"].is_null(), "{r}"); + // A partial cut folds at -90° unless it has an angle of its own. + role(&mut s, "partialCut", &[creases[2]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}"); +} + +#[test] +fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap(); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}"); + assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}"); + // So Reset has nothing to change, as the panel shows it. + let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + let (lines, angle, own) = { + let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]); + (f.lines, f.angle, f.own) + }; + assert_eq!((lines, angle, own), (1, Some(90.0), 0)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::angle::own_angle; use super::roles::{Role, RoleTable, can_carry, role_targets}; use crate::{Result, Session}; @@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) } -fn kind(role: Role) -> LineKind { +/// The kind of fold line a line with `role` is. +pub(super) fn kind(role: Role) -> LineKind { match role { Role::Cut => LineKind::Cut, Role::Crease => LineKind::Crease, @@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) }); } Lines { scope, lines, non_printing } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..00e857540d 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fold", [], None, - "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", has_doc, fold_command )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use super::super::super::edit::{outermost, refuse_symbol_part, roots_of}; use super::super::super::overprint::edit_counted; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{Result, Session}; @@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool { } } +/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of +/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that +/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out +/// before it stands for its compound, and how many such paths were left out, each once. +pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec, usize)> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + let roots = checked_ids_or_selection(s, p, command)?; + return Ok(editable_members(&s.doc()?.doc, roots)); + } + refuse_symbol_part(s)?; + let st = s.doc()?; + // An object inside another selected one is left out first, as it is from `ids`. + let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc))); + Ok((roots_of(&st.doc, kept), left)) +} + +/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or +/// hidden group or layer, or on a locked artboard), and how many different ones were left out. +pub(super) fn editable_members(d: &Document, ids: Vec) -> (Vec, usize) { + let ok = d.editable(); + let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let mut left = std::collections::HashSet::new(); + let kept = ids + .into_iter() + .filter(|id| { + let out = member(*id) && !ok(*id); + if out { + left.insert(*id); + } + !out + }) + .collect(); + (kept, left.len()) +} + /// The objects under the outermost objects `roots` that can carry a role, through groups and clip /// groups, each once, and /// how many of `roots` and their members can't (text, images, symbol instances and other objects). @@ -257,7 +293,7 @@ pub fn specs() -> Vec { "Make Fold Line", ["Object", "Plug-ins", "Packaging Tools"], None, - "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", has_selection, set_role ), @@ -266,7 +302,7 @@ pub fn specs() -> Vec { "Fold Lines", [], None, - "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes", has_doc, roles ), @@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai fn set_role(s: &mut Session, p: &Value) -> Result { let role = role_param(p, SET_ROLE, true)?; let overprint = switch_or(p, "overprint", true, SET_ROLE)?; - let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (roots, left) = taken_roots(s, p, SET_ROLE)?; let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + let skipped = skipped + left; if ids.is_empty() { return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); } @@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result { fn roles(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, ROLES)?; - let d = &s.doc()?.doc; + // The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand + // for its compound there. They are the objects the counts are of unless such a path was left + // out, and only then are those found apart. + let (taken, left) = taken_roots(s, p, ROLES)?; + let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) }; + let st = s.doc()?; + let d = &st.doc; let (scope, ids) = match (given, roots.is_empty()) { (true, _) => ("ids", role_targets(d, &roots, false).0), (false, false) => ("selection", role_targets(d, &roots, false).0), (false, true) => ("document", document_targets(d)), }; + let whole = scope == "document"; + // The lines Set Fold Angle can change are those of the objects it takes: with nothing selected, + // or a selection that holds no such object (only a layer and what is in it), it takes none, + // though the counts are the document's. + let angles_of_all = given || !roots.is_empty(); let table = RoleTable::of(d); let mut counts = [0usize; 4]; - for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + let editable = d.editable(); + let mut angles = super::angle::FoldAngles::default(); + for n in ids.iter().filter_map(|id| d.node(*id)) { + let Some(r) = table.role_of(n) else { continue }; if let Some(c) = counts.get_mut(r.index()) { *c += 1; } + if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) { + angles.add(n, r); + } + } + if !whole && left > 0 { + angles = super::angle::fold_angles(d, &angle_roots); } let rows: Vec = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) }) .collect(); - Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) + Ok(json!({ + "roles": rows, "scope": scope, "selected": roots.len(), + "foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored, + })) } fn set_role_swatch(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() { let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // A locked member named by id is skipped, and its compound keeps its role. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(a) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden")); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden")); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // Named twice, it is skipped once. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}"); } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5a10ae3d9c..dbd4941748 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..ae3075f9be 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1411,7 +1411,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..14bc32fa6d 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -79,14 +98,17 @@ impl Panel { /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is -/// ([`LineKind::fold_angle`]). +/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most +/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle +/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its +/// pieces may not have at the middle of `from` to `to`. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, + pub on: Point, pub keys: Vec, pub straight: bool, pub angle: f64, @@ -1297,9 +1319,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1368,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } @@ -1331,7 +1378,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option { mod pose; pub mod raster; -pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon}; #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs index 650ab54291..91a6cdfb12 100644 --- a/crates/three-d/src/fold/pose.rs +++ b/crates/three-d/src/fold/pose.rs @@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in}; /// test and the preview. pub const MAX_POLYGON_POINTS: usize = 1 << 16; +/// How far apart two placements of a panel may turn a unit direction and still be one placement: +/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth +/// of a degree from another ([`super::kept_angle`], 1.7e-8). +const TURNED: f64 = 1e-10; + type V3 = [f64; 3]; fn sub(a: V3, b: V3) -> V3 { @@ -105,14 +110,24 @@ impl Pose { let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } } + + /// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the + /// flat blank's own terms. + fn about(&self, origin: V3) -> Pose { + Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) } + } } -/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no -/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it -/// and the base. +/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold +/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where +/// it is) and how many hinges lie between it and the base. #[derive(Clone, Debug)] pub struct FoldedPanel { pub pose: Pose, + /// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less + /// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a + /// blank far from the document's origin to the size of the blank. + pub local: Pose, pub parent: Option, pub depth: usize, } @@ -141,6 +156,28 @@ pub struct Folded { pub hinges: Vec, /// Pairs of panels (`a` < `b`) that pass through each other. pub collisions: Vec<(usize, usize)>, + /// The fold tree that panels folded flat onto each other stack by. + pub stack: Stack, + /// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about. + pub origin: [f64; 3], +} + +/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its +/// `root`), whichever panel is the base, so choosing another base moves the folded blank without +/// changing which panel shows where they lie flat on each other. The base's own tree when the two +/// join different panels. +#[derive(Clone, Debug, Default)] +pub struct Stack { + pub root: usize, + /// Each panel's parent in this tree. + pub parent: Vec>, + /// The panels in breadth-first order from `root`, the panels not joined to it last. + pub order: Vec, + /// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector + /// in the parent's plane, across the hinge to the side the fold took the parent to be on, as + /// long as the corners of the parent's bounds reach that way. `None` for `root` and the + /// panels not joined to it. + pub toward_parent: Vec>, } /// The panel of `blank` that `p` (document coordinates) lies in. @@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }); } let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); - let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // The corners of each panel's bounds (flat). + let corners: Vec> = blank + .panels + .iter() + .map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y))))) + .collect(); + let origin = corners + .iter() + .flatten() + .flatten() + .fold(None, |b: Option<(V3, V3)>, c| { + Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0]))) + }) + .map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5)); + let placing = Placing { blank, by_panel: &by_panel, centers: ¢ers, corners: &corners, origin }; + let (panels, tree, order, toward_parent) = place(&placing, base, amount); // Closing hinges are measured with every hinge at its full angle, so a blank that closes when // folded is not reported open part of the way there. - let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) }; let measured = full.as_deref().unwrap_or(&panels); let hinges = blank .hinges @@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }) .collect(); let collisions = collisions(blank, &panels, tolerance); - Some(Folded { base, panels, order, hinges, collisions }) + let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent }; + let stack = match base_panel(&blank.panels) { + Some(root) if root != base => { + let (placed, root_tree, root_order, toward) = place(&placing, root, amount); + // Whether the root's tree puts every panel where the base's does, moved with the root + // (which lies at the identity in its own): the same hinges do, and around a loop of + // panels another tree can leave out a fold that placed them. Each panel's turn is + // compared to within `TURNED` whatever its size or place, and its inside point by the + // poses about `origin` (`local`), to rounding at that distance from it. + let agrees = |r: &FoldedPanel| { + let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b))); + placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| { + let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some()); + let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin)); + let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + .into_iter() + .all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED); + joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at)))) + }) + }; + match panels.get(root) { + // The root's tree in the base's terms. + Some(r) if root_tree == tree || agrees(r) => Stack { + root, + parent: placed.iter().map(|p| p.parent).collect(), + order: root_order, + toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(), + }, + _ => own, + } + } + _ => own, + }; + Some(Folded { base, panels, order, hinges, collisions, stack, origin }) } -/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its -/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not -/// joined to the base last). -fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { +/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and +/// [`Stack::toward_parent`]. +type Tree = (Vec, Vec, Vec, Vec>); + +/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and +/// bounds corners (flat), and the point the panels' local poses are about. +struct Placing<'a> { + blank: &'a Blank, + by_panel: &'a [Vec], + centers: &'a [Option], + corners: &'a [Option<[V3; 4]>], + origin: V3, +} + +/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined +/// to the base last), and [`Stack::toward_parent`]. +fn place(placing: &Placing, base: usize, amount: f64) -> Tree { + let Placing { blank, by_panel, centers, corners, origin } = *placing; let n = blank.panels.len(); - let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut toward_parent: Vec> = vec![None; n]; let mut reached = vec![false; n]; let mut tree = vec![false; blank.hinges.len()]; let mut order = Vec::with_capacity(n); @@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u // The parent on the left of the hinge's direction, the child on its right. The side is // read next to the hinge, so a parent with a notch or an arm past the hinge's line still // turns the child the right way; the panel's inside point is the fallback. - let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) { Some(left) => left, None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), }; @@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u continue; } if let Some(slot) = panels.get_mut(child) { - *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + let local = parent.local.turned_about(sub(from, origin), axis, theta); + *slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 }; + } + // Across the hinge, to its left: into the parent, as far as the corners of its bounds + // reach that way. + let into = [-axis[1], axis[0], 0.0]; + let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max)); + if let Some(slot) = toward_parent.get_mut(child) { + *slot = Some(parent.pose.turn(scale(into, reach))); } if let Some(r) = reached.get_mut(child) { *r = true; @@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u } } order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); - (panels, tree, order) + (panels, tree, order, toward_parent) } /// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) -/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and -/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset -/// tells them apart. The nearest offset is tried first. -fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { +/// next to it: `true` when a point just off the line on the left is inside it and the matching +/// point on the right is not, `false` the other way round. `on` (a point of the line where the +/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an +/// eighth of the way along, each with the nearest offset first; `None` when no point tells the +/// sides apart. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option { let bp = outline.to_bezpath(); - let mid = scale(add(from, to), 0.5); let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; let doc = |v: V3| Point::new(v[0], -v[1]); let mut offsets = [1e-3, 0.25, len * 0.01]; offsets.sort_by(f64::total_cmp); - offsets.into_iter().find_map(|off| { - let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); - (l != r).then_some(l) + let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t))); + std::iter::once(on).chain(along).find_map(|at| { + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0); + (l != r).then_some(l) + }) }) } diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 9cccbaf6d9..4db9cd728f 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096; pub const MAX_PIXELS: u32 = 1 << 21; /// The share of the eye's distance a panel is cut at in front of the eye. const NEAREST: f64 = 1e-3; -/// How far apart (points of view depth) two panels may be and still tie. +/// How far apart (points of view depth) two panels in one plane may be and still tie. const TIE: f64 = 1e-4; +/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one +/// plane. +const PARALLEL: f64 = 1e-9; +/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding, +/// as this many times the precision of a number at their distance from the origin for each hinge +/// that placed them. +const COPLANAR: f64 = 16.0 * f64::EPSILON; +/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count +/// as along it. +const ALONG: f64 = 1e-6; /// The light's direction: above, to the left of and toward the viewer. const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; @@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) } -fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { +fn map_panel(camera: &Camera, pose: &super::Pose) -> Option { let r = camera.rotation(); - let turn = |v: V3| mul(&r, f.pose.turn(v)); + let turn = |v: V3| mul(&r, pose.turn(v)); let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); - let o = camera.to_view(f.pose.t); + let o = camera.to_view(pose.t); let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); let normal = turn([0.0, 0.0, 1.0]); let (w, k, printed) = match camera.eye() { @@ -326,18 +336,23 @@ struct Target { panel: Vec, } -/// One panel's fill: its map, rank (for ties), panel number and colors. +/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as +/// [`planes`] gives them), panel number and colors. struct Fill<'a> { mapped: &'a Mapped, rank: u16, + planes: &'a [u16], panel: u16, print: Option<&'a Print>, + /// The flat point the map is about ([`Folded::origin`]): a flat point less it is what + /// `mapped` maps. + origin: [f64; 2], inside: [f32; 4], outside: [f32; 4], } impl Fill<'_> { - /// The document point under pixel center `(x, y)`, or `None` behind the eye. + /// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye. fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) @@ -346,7 +361,7 @@ impl Fill<'_> { /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { let base = if self.mapped.printed { - let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint)); let under = 1.0 - p[3] / 255.0; [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] } else { @@ -370,8 +385,12 @@ impl Fill<'_> { let [a, b, c] = self.mapped.depth; let z = u * a + v * b + c; let i = row * target.width + col; - let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; - let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue }; + // Panels in one plane tie within `TIE` and stack by rank; panels in different planes + // that pass this close go by depth alone. Panel numbers count from 1. + let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p)); + let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a)); + let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb }; if !wins { continue; } @@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option>> { Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) } +/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each +/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed +/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are +/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so +/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between +/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the +/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later +/// one nearer seen from one side of their plane and the earlier one seen +/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other +/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel +/// it branched from, after leaving it, takes the side of that plane it came back from for every +/// step up to the one it left by: the side the nearest panel out of the plane lies on from the +/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as +/// [`planes`] does. +fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec { + let n = folded.panels.len(); + // Each panel's layer holds a step per fold up to the base: past the panels a blank can have, + // the order alone decides. So it does when every panel lies where it lies flat (a fold amount + // of 0), as panels there do not overlap. + if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) { + return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(); + } + // The step each panel takes off its parent: the parent's printed side, negated for a positive + // angle; none for a 0° hinge or a panel without a parent. + // The parents are those of [`Folded::stack`], so the panels stack the same about any base. + let stack = &folded.stack; + let parent_of = |c: usize| stack.parent.get(c).copied().flatten(); + let mut step: Vec> = vec![None; n]; + for c in 0..n { + let Some(p) = parent_of(c) else { continue }; + let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue }; + let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue }; + let [x, y, z] = parent.pose.normal(); + *slot = match h.angle { + a if a > 0.0 => Some([-x, -y, -z]), + a if a < 0.0 => Some([x, y, z]), + _ => None, + }; + } + // Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's + // plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next + // to its parent, before any later step, however many folds deep. + // Each panel's place in the stack's order. + let mut place = vec![0usize; n]; + for (i, &pi) in stack.order.iter().enumerate() { + if let Some(slot) = place.get_mut(pi) { + *slot = i; + } + } + // Each step also carries the place in `folded.order` of the panel that took it, so panels whose + // steps match up to a fold that branches stack by that branch: the later panel nearer seen from + // one side of their plane, the earlier one seen from the other, so the two sides show opposite + // panels. The rest of a branch stays with it. + // Whether the view sees each panel's printed side. + let sees_print: Vec = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect(); + // The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it + // lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1 + // the other; `None` when every panel on the way lies in the plane. The plane is the one + // [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it + // and a stack folded a hair short of flat goes by depth instead. + let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> { + let (mut child, mut up) = (pi, parent_of(pi)); + for _ in 0..n { + let c = up?; + if planes.get(c) != planes.get(pi) + && let Some(Some(way)) = stack.toward_parent.get(child) + { + let d = dot(*way, n_view); + if d != 0.0 { + return Some((c, if d > 0.0 { 1 } else { -1 })); + } + } + (child, up) = (c, parent_of(c)); + } + None + }; + let layer = |pi: usize| -> Vec<(i8, i64)> { + let Some(f) = folded.panels.get(pi) else { return vec![] }; + let printed = sees_print.get(pi).copied().unwrap_or(true); + let n_view = { + let [x, y, z] = f.pose.normal(); + if printed { [x, y, z] } else { [-x, -y, -z] } + }; + let mut out = vec![]; + let mut at = Some(pi); + // From the nearest panel out of the plane on the way to the base, every step counts as on + // the side of the plane that panel lies on: a panel that comes round onto the plane of a + // panel it branched from lies on the side it came back from, whatever its folds before. + let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s)); + let mut returned = false; + // A panel's chain to the base is at most the panel count long. + for _ in 0..n { + let Some(c) = at else { break }; + returned |= Some(c) == back_at; + if let Some(Some(s)) = step.get(c) { + let d = if returned { f64::from(back_side) } else { dot(*s, n_view) }; + // Branches off one panel stack one way seen from that panel's printed side and the + // other way from its back, so the panels of one plane that compare a step off one + // parent agree, however the parent is turned. + let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX)); + // A parent seen edge on gives no side: the panel that took the step gives it, and + // when that is edge on too, the largest part of the view's normal does. Each choice + // gives two panels of one plane the same sign however an edge-on dot rounds, and + // each turns over with the side of the plane the view is on. + let faces = |f: &super::FoldedPanel| { + let d = dot(f.pose.normal(), n_view); + (d.abs() > ALONG).then_some(d >= 0.0) + }; + // The view's normal in the root's flat terms, so this too is the same about any base. + let largest = || { + let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m); + let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::()); + local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0) + }; + let parent = parent_of(c).and_then(|p| folded.panels.get(p)); + let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest); + let branch = if parent_faces { branch } else { -branch }; + // Any step that is not along the plane counts whole, so a step seen from two panels + // of one plane counts the same for both. + out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch)); + } + at = parent_of(c); + } + out.reverse(); + out + }; + // Layers compared step by step, a missing step as none. + let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| { + (0..a.len().max(b.len())) + .map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0)))) + .find(|o| o.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }; + // A panel alone in its plane ties with no other, so its layer is not worked out. + let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)]; + for &p in planes { + if let Some(c) = in_plane.get_mut(usize::from(p)) { + *c += 1; + } + } + let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1); + let mut keys: Vec<(Vec<(i8, i64)>, usize)> = + folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect(); + // Then by the stack's order, for panels that stack as one. + let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX); + keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1))); + let mut ranks = vec![0u16; folded.order.len()]; + for (r, &(_, i)) in keys.iter().enumerate() { + if let Some(slot) = ranks.get_mut(i) { + *slot = u16::try_from(r + 1).unwrap_or(u16::MAX); + } + } + ranks +} + /// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more /// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than /// [`super::MAX_POLYGON_POINTS`] points, are left out. @@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option { Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); - for (rank, &pi) in scene.folded.order.iter().enumerate() { + let planes = planes(scene.folded, scene.blank); + let ranks = tie_ranks(scene.folded, &camera, &planes); + // Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat + // points and the view's center moved to match. + let o = scene.folded.origin; + let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera }; + for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; - let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(mapped) = map_panel(&local, &f.local) else { continue }; let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let rings: Vec> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect(); let projected: Vec> = rings .iter() .map(|r| match near { @@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option { .collect(); let fill = Fill { mapped: &mapped, - rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + rank, + planes: &planes, panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), print: scene.print, + origin: [o[0], o[1]], inside, outside, }; @@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option { Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) } +/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their +/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them +/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the +/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is +/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`] +/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the +/// planes. Past [`super::MAX_PANELS`] panels, one plane for all. +fn planes(folded: &Folded, blank: &Blank) -> Vec { + let n = folded.panels.len(); + if n > super::MAX_PANELS { + return vec![0; n]; + } + let length = |v: V3| dot(v, v).sqrt(); + // Each plane's normal, a point of it, the size of the coordinates that point came from and the + // hinges that placed it. + let mut kinds: Vec<(V3, V3, f64, usize)> = vec![]; + folded + .panels + .iter() + .enumerate() + .map(|(i, f)| { + let o = folded.origin; + let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]); + let (normal, at) = (f.local.normal(), f.local.apply(middle)); + let size = length(at).max(length(middle)); + let same = |(m, p, s, d): &(V3, V3, f64, usize)| { + let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]]; + let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs(); + // Saturating: a `Folded` built by a caller may carry any depth. + let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX)); + length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s)) + }; + let k = kinds.iter().position(same).unwrap_or_else(|| { + kinds.push((normal, at, size, f.depth)); + kinds.len() - 1 + }); + u16::try_from(k).unwrap_or(u16::MAX) + }) + .collect() +} + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 8639615a53..b6251985ca 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; -use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose, Stack}; use super::*; fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { @@ -16,10 +18,12 @@ fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { let n = panels.len(); let folded = Folded { base: 0, - panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + panels: poses.into_iter().map(|pose| FoldedPanel { pose, local: pose, parent: None, depth: 0 }).collect(), order: (0..n).collect(), hinges: vec![], collisions: vec![], + stack: Stack { root: 0, parent: vec![None; n], order: (0..n).collect(), toward_parent: vec![None; n] }, + origin: [0.0; 3], }; (Blank { panels, hinges: vec![], holes: vec![] }, folded) } @@ -135,6 +139,1025 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); } +#[test] +fn of_two_parallel_panels_the_nearer_shows_however_close() { + // 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE` + // equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn + // first. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + for (near, poses) in [(1, vec![moved(2.0), moved(2.0001)]), (0, vec![moved(2.0001), moved(2.0)])] { + let (b, f) = scene_of(vec![whole(), whole()], poses); + assert_eq!(planes(&f, &b).iter().collect::>().len(), 2, "two planes"); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), Some(near)); + } +} + +#[test] +fn a_scene_whose_panels_claim_any_depth_still_draws() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, mut f) = scene_of(vec![whole(), whole()], vec![moved(5.0), moved(5.0)]); + for p in &mut f.panels { + p.depth = usize::MAX; + } + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert!(img.panel_at(50, 50).is_some()); +} + +#[test] +fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() { + // A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // Folds a hair short of flat lie on the same side, everywhere within a tie of the base. + for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] { + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(60.0, 0.0), (60.0, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(angle), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = 1 - f.base; + let views = [ + (front(), true), + (Camera { rotate_y: 180.0, ..front() }, false), + (Camera { perspective: 60.0, ..front() }, true), + (Camera { rotate_y: 180.0, perspective: 60.0, ..front() }, false), + ]; + for (camera, seen_from_print) in views { + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // The point x 40, y 30 of the blank, where the flap lies over the base. + let x = if seen_from_print { 40 } else { 60 }; + let want = if flap_in_front == seen_from_print { flap } else { f.base }; + assert_eq!(img.panel_at(x, 30), Some(want), "{angle}°, seen from the print: {seen_from_print}, {camera:?}"); + } + } +} + +#[test] +fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() { + // A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to + // 100) folded back at 180°, which lies behind the base from x 30 to 60. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2, 0.0), + crease(65.0, 3, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(45, 30), Some(f.base), "the base is in front of the flap behind it"); +} + +#[test] +fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() { + // A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at + // 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at + // x 20 to 30. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = f.panels.iter().position(|p| p.parent == Some(f.base)).expect("the panel folded from the base"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(25, 30), Some(f.base), "the base, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(75, 30), Some(middle), "the folded panel, from the back"); + // Folded about the flap instead, the blank only moves: the flap (x 100 to 110 now) still lies + // between the other two, the 60 pt panel over it on the printed side. + let tip = super::super::panel_at(b, Point::new(105.0, 30.0)).expect("the flap"); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [105.0, -30.0, 0.0], ..front() }; + let wide = super::super::panel_at(b, Point::new(30.0, 30.0)).expect("the 60 pt panel"); + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() { + // The strip of the test above turned 45° and moved to about (3,000,000, 3,000,000) pt, folded + // about its 10 pt flap: the 60 pt panel still lies over the flap on the printed side. + let s = std::f64::consts::FRAC_1_SQRT_2; + let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s); + let poly = + |pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::>(), closed)); + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let panel = |x: f64, y: f64| super::super::panel_at(b, at(x, y)).expect("a panel"); + let (wide, middle, tip) = (panel(30.0, 30.0), panel(80.0, 30.0), panel(105.0, 30.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let c = at(105.0, 30.0); + let at_tip = Camera { center: [c.x, -c.y, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_flat_stack_far_from_the_origin_stays_in_one_plane() { + // A strip from x = 3,000,000 pt: the base (60 pt wide), a 40 pt panel folded back under it at + // 180° and a 35 pt flap folded back at 180° between the two. + let x0 = 3_000_000.0; + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let middle = super::super::panel_at(b, Point::new(x0 + 80.0, 30.0)).expect("the middle panel"); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(planes(&f, b).iter().collect::>().len(), 1, "one plane"); + let draw = |rotate_y| { + let camera = Camera { rotate_y, center: [x0 + 40.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 50) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(middle))); +} + +#[test] +fn a_panel_parallel_to_the_base_a_hair_behind_it_goes_by_depth() { + // A strip 30 pt tall: the base (x 0 to 100), a 20 pt panel folded back at 179.9999° and a 30 pt + // flap at 0.0001° off it, parallel to the base and about 0.000035 pt behind it; then the same + // strip 100,000 pt to the right; then at 179.999999° and 0.000001°, about 0.00000035 pt behind, + // 3,000,000 pt to the right; then with a 1 pt middle panel, about 0.0000000175 pt behind, at the + // origin and 3,000,000 pt to the right. + for (dx, back, w) in + [(0.0, 0.0001, 20.0), (100_000.0, 0.0001, 20.0), (3_000_000.0, 0.000001, 20.0), (0.0, 0.000001, 1.0), (3_000_000.0, 0.000001, 1.0)] + { + parallel_a_hair_behind(dx, back, w); + } +} + +fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(100.0, 2, 180.0 - back), + crease(100.0 + w, 3, back), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = Point::new(115.0 + w + dx, 15.0); + let flap = super::super::panel_at(b, at).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let m = f.panels[flap].pose.place(at); + assert!(m[2] < 0.0 && m[2] > -1e-4, "the flap lies a hair behind the base: {m:?}"); + let draw = |rotate_y| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(flap)), "at x + {dx}, a {w} pt middle panel"); +} + +#[test] +fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() { + // A 4 pt strip, its second half folded back at 179.999999° so it lies a hair behind the first, + // seen at a three-quarter turn with and without perspective: every pixel shows the same panel + // at the origin and 3,000,000 pt right and down. + let draw = |at: f64, perspective: f64| { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::>(), closed)) + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(2.0, 0.0), (2.0, 1.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(179.999999), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let base = super::super::panel_at(b, Point::new(0.5 + at, 0.5 + at)).expect("the base"); + let f = super::super::fold(b, Some(base), 1.0, 0.0001).expect("folds"); + let camera = Camera { rotate_x: 35.0, rotate_y: 40.0, scale: 40.0, perspective, center: [1.0 + at, -0.5 - at, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown: Vec> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.panel_at(x, y).map(|p| p == base)).collect(); + assert!(shown.contains(&Some(true)), "the base shows"); + shown + }; + for perspective in [0.0, 40.0] { + assert!(draw(0.0, perspective) == draw(3_000_000.0, perspective), "perspective {perspective}"); + } +} + +#[test] +fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() { + // A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no + // layer is worked out. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for i in 1..64u32 { + let x = f64::from(i) * 10.0; + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 10.0)], false), + kind: super::super::LineKind::Crease, + key: u64::from(i) + 1, + angle: Some(180.0), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let f = super::super::fold(&blanks[0], None, 0.0, 0.1).expect("folds"); + let ranks = tie_ranks(&f, &front(), &planes(&f, &blanks[0])); + assert_eq!(ranks, (1..=64).collect::>()); +} + +#[test] +fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() { + // A 100 × 100 blank cut into four 50 pt squares by four creases, one per side of the middle + // point. The crease that closes the loop when folded about the largest panel folds at 180° and + // the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap + // lies flat behind the panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let lines = |flat_key: Option| { + let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }), + }; + vec![ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (blanks, issues) = super::super::blanks(&lines(None), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let level = super::super::fold(&blanks[0], None, 1.0, 0.1).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = *blanks[0].hinges[closing].keys.first().expect("a line"); + let (blanks, issues) = super::super::blanks(&lines(Some(key)), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let h = &b.hinges[closing]; + assert_eq!(h.keys, [key]); + let f = super::super::fold(b, Some(h.a), 1.0, 0.1).expect("folds"); + assert!(f.hinges[closing].tree); + // The panel's middle, in pixels: the blank's top left square is pixels 0 to 50. + let middle = |p: usize| { + let c = b.panels[p].outline.bounds().expect("bounds").center(); + (c.x as u32, c.y as u32) + }; + let (x, y) = middle(h.a); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(x, y), Some(h.a), "the panel, from its printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(100 - x, y), Some(h.b), "the flap, from the back"); +} + +#[test] +fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() { + // A 2 × 2 grid of panels joined by 0° creases (the largest at the bottom left), and two flaps + // folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the + // tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way, + // and the stack stays as it is about the largest panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((60.0, 0.0), (60.0, 40.0), 2, 0.0), + crease((60.0, 40.0), (60.0, 100.0), 3, 0.0), + crease((0.0, 40.0), (60.0, 40.0), 4, 0.0), + crease((60.0, 40.0), (100.0, 40.0), 5, 0.0), + crease((100.0, 0.0), (100.0, 40.0), 6, 180.0), + crease((130.0, 0.0), (130.0, 40.0), 7, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = |x: f64, y: f64| super::super::panel_at(b, Point::new(x, y)).expect("a panel"); + let (corner, under, tip) = (at(80.0, 20.0), at(115.0, 20.0), at(135.0, 20.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [135.0, -20.0, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(corner), "the top right panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(under), "the first flap, from the back"); +} + +#[test] +fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() { + // The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the + // left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(52.0, 20.0), (58.0, 20.0), (58.0, 40.0), (52.0, 40.0)], true, Cut, 2, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(80.0, 0.0), (80.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let through_window = draw(front()).panel_at(55, 30); + let from_back = draw(Camera { rotate_y: 180.0, ..front() }).panel_at(45, 30); + let flaps: Vec = (0..b.panels.len()).filter(|&i| i != f.base).collect(); + assert!(through_window.is_some_and(|p| flaps.contains(&p)), "{through_window:?}"); + assert!(from_back.is_some_and(|p| flaps.contains(&p)), "{from_back:?}"); + assert_ne!(through_window, from_back); +} + +#[test] +fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { + // The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to + // 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(90.0, 0.0), (90.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(15.0, 0.0), (15.0, 60.0)], false, Crease, 4, Some(0.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 140 - x in the image. + let right_flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 90.0).abs() < 1e-6)).expect("the right flap"); + let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); + assert_eq!(near == Some(right_flap), far == Some(right_flap), "{near:?} {far:?}"); +} + +#[test] +fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() { + // Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap + // (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and + // the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(20.0, 0.0), (20.0, 60.0)], false, Crease, 2, Some(-180.0)), + line(&[(70.0, 0.0), (70.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (tip, left, right) = (starts_at(0.0), starts_at(20.0), starts_at(140.0)); + let camera = Camera { width: 210, center: [105.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 210 - x in the image. + let (flaps_only, with_tip) = (img.panel_at(210 - 90, 30), img.panel_at(210 - 110, 30)); + if flaps_only == Some(right) { + assert_eq!(with_tip, Some(right), "the right flap covers the left flap and the tip on it"); + } else { + assert_eq!((flaps_only, with_tip), (Some(left), Some(tip)), "the left flap, and the tip on it, cover the right flap"); + } +} + +#[test] +fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() { + // The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to + // 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + // The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base. + for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] { + let base = middle + 20.0; + let end = base + middle + 10.0; + let lines = [ + line(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(base, 0.0), (base, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(base + middle, 0.0), (base + middle, 60.0)], false, Crease, 3, Some(tip_angle)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let tip = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (base + middle)).abs() < 1e-6)).expect("the tip"); + let back = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: back }).expect("drawn"); + assert_eq!(img.panel_at(100 - 25, 30), Some(tip), "{middle} pt, {tip_angle}°"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(25, 30), Some(f.base), "{middle} pt, {tip_angle}°"); + } +} + +#[test] +fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_lid() { + // A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to + // 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps + // meet in one plane 40 pt below the base and overlap from x 140 to 160. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0)); + let lines = [ + line(&[(0.0, 0.0), (300.0, 0.0), (300.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + crease(60.0, 2), + crease(100.0, 3), + crease(200.0, 4), + crease(240.0, 5), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + // Looking up at the lid from below, a little to one side and then the other, at its middle. + let shown = |rotate_y: f64| { + let camera = Camera { width: 200, rotate_y, center: [150.0, -30.0, -40.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(100, 50) + }; + let (left, right) = (shown(175.0), shown(185.0)); + assert!(left.is_some_and(|p| p != f.base), "{left:?}"); + assert_eq!(left, right); +} + +#[test] +fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() { + // The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100, + // with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded + // at -180° onto the panel's printed side, where they overlap from y 20 to 40. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let shown = |tilt: f64| { + let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(100.0, -40.0), (100.0, 0.0)], false, Cut, 2, None), + line(&[(100.0, 60.0), (100.0, 100.0)], false, Cut, 3, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 4, Some(tilt)), + line(&[(100.0, 0.0), (200.0, 0.0)], false, Crease, 5, Some(-180.0)), + line(&[(100.0, 60.0), (200.0, 60.0)], false, Crease, 6, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 200, center: [150.0, -30.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0)); + let shown = img.panel_at(100, 50); + if shown == flap(-40.0) { + "above" + } else if shown == flap(60.0) { + "below" + } else { + "neither" + } + }; + let (up, down) = (shown(1.0), shown(-1.0)); + assert_ne!(up, "neither"); + assert_eq!(up, down); +} + +#[test] +fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() { + // The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180° + // onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(60.0, 0.0), (60.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 3, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(60.0), starts_at(100.0)); + let mut sides = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the wall from one side and then the other, the middle row of the view. + let camera = Camera { width: 200, height: 100, rotate_y, center: [60.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[wall].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = |p: usize| (0..img.width).filter(|&x| img.panel_at(x, 50) == Some(p)).count(); + let (walls, flaps) = (count(wall), count(flap)); + if printed { + assert!(flaps > 25 && walls < 15, "from the wall's printed side the flap covers it: wall {walls} px, flap {flaps} px"); + } else { + assert!(flaps == 0 && walls > 35, "from the back the wall covers the flap: wall {walls} px, flap {flaps} px"); + } + sides.push(printed); + } + assert_ne!(sides[0], sides[1], "both sides of the wall are looked at"); +} + +#[test] +fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_side() { + // The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each + // with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover + // the same 100 pt. Looking straight through that end, the base and walls are edge on. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(40.0, 0.0), (40.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(90.0)), + line(&[(0.0, 60.0), (40.0, 60.0)], false, Crease, 4, Some(90.0)), + line(&[(140.0, 60.0), (180.0, 60.0)], false, Crease, 5, Some(90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6 && r.y0 > 59.0)).expect("a flap"); + let (left, right) = (flap(0.0), flap(140.0)); + let shown = |rotate_x: f64| { + let camera = Camera { width: 300, height: 300, rotate_x, center: [90.0, -60.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = + |p: usize| (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(p)).count(); + (count(left), count(right)) + }; + let (one, other) = (shown(90.0), shown(-90.0)); + // Each view shows one flap over (nearly) the whole of the other. + let winner = |(l, r): (usize, usize)| { + if l > 10 * r.max(1) { + Some(left) + } else if r > 10 * l.max(1) { + Some(right) + } else { + None + } + }; + assert!(winner(one).is_some() && winner(other).is_some(), "the flaps cover the same end: {one:?} {other:?}"); + assert_ne!(winner(one), winner(other), "{one:?} {other:?}"); +} + +#[test] +fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() { + // A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90° + // and -90°, so the last one comes round and lies on the base's plane over part of it. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(-90.0)), + line(&[(200.0, 0.0), (200.0, 60.0)], false, Crease, 4, Some(-90.0)), + line(&[(240.0, 0.0), (240.0, 60.0)], false, Crease, 5, Some(-90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 240.0).abs() < 1e-6)).expect("the flap"); + // The panels between the base and the flap all lie behind the base's printed side. + for (i, (panel, folded)) in b.panels.iter().zip(&f.panels).enumerate() { + let r = panel.outline.bounds().expect("bounds"); + let z = folded.pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0))[2]; + if i != f.base && i != flap { + assert!(z < -1.0, "panel {i} at z {z}"); + } + } + // At x 90 the flap lies on the base: from the front the base covers it, from the back it + // covers the base. + let at = |rotate_y: f64, x: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(x, 50) + }; + assert_eq!(at(0.0, 200 - 10), Some(f.base)); + assert_eq!(at(180.0, 200 + 10), Some(flap)); +} + +#[test] +fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from() { + // A strip 60 pt tall: the base (x 0 to 100) and panels 20, 20, 40, 40 and 20 pt wide, then a + // flap (240 to 270, y 0 to 30), folded 90°, -90°, -90°, -90°, -90° and 90°. The 20 pt wall the + // flap folds from stands on the printed side of the base, and the flap lands on the base at x + // 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60), + // through the base's plane, which moves its middle to the other side of that plane. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with + // a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side. + let shown = |tab: bool, cutout: f64| { + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = if tab { + vec![ + line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (340.0, 30.0), (340.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(240.0, 30.0), (270.0, 30.0)], false, Cut, 2, None), + ] + } else { + vec![line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (0.0, 60.0)], true, Cut, 1, None)] + }; + let creases = + [(100.0, 60.0, 90.0), (120.0, 60.0, -90.0), (140.0, 60.0, -90.0), (180.0, 60.0, -90.0), (220.0, 60.0, -90.0), (240.0, 30.0, 90.0)]; + for (i, (x, high, a)) in creases.into_iter().enumerate() { + let key = 10 * (i as u64 + 1); + if cutout > 0.0 { + let (lo, hi) = if cutout > 5.0 { (2.0, high - 2.0) } else { (high / 2.0 - 5.0, high / 2.0 + 5.0) }; + let w = cutout.min(5.0); + lines.push(line(&[(x - w, lo), (x + w, lo), (x + w, hi), (x - w, hi)], true, Cut, key, None)); + lines.push(line(&[(x, 0.0), (x, lo)], false, Crease, key + 1, Some(a))); + lines.push(line(&[(x, hi), (x, high)], false, Crease, key + 2, Some(a))); + } else { + lines.push(line(&[(x, 0.0), (x, high)], false, Crease, key, Some(a))); + } + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(220.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let m = middle(flap); + assert!(m[2].abs() < 1e-6 && (m[0] - 65.0).abs() < 1e-6, "the flap lies on the base: {m:?}"); + assert_eq!(middle(wall)[2] > 0.0, !tab, "the wall's middle is on the printed side without the tab only"); + // The flap's row at y 5, at x 65, from the front and from the back (mirrored). + let at = |rotate_y: f64, px: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(px, 25) + }; + let named = |p: Option| match p { + Some(p) if p == f.base => "base", + Some(p) if p == flap => "flap", + _ => "other", + }; + (named(at(0.0, 200 - 35)), named(at(180.0, 200 + 35))) + }; + assert_eq!(shown(false, 0.0), ("flap", "base")); + assert_eq!(shown(true, 0.0), ("flap", "base"), "the side next to the hinge decides, not the wall's middle"); + assert_eq!(shown(false, 5.0), ("flap", "base"), "a hinge broken by a cutout"); + assert_eq!(shown(true, 5.0), ("flap", "base"), "both"); + assert_eq!(shown(true, 6.0), ("flap", "base"), "hinges joined only near their ends"); +} + +#[test] +fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_came_from() { + // A strip 30 pt tall: the base (x 0 to `base`), a panel 10 pt wide folded down behind it, one + // 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp + // `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that + // lies on the base from where the ramp ends. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let shown = |base: f64, ramp: f64, drop: f64| { + // To the millionth of a degree a line keeps, and the drop that ramp comes down by. + let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees()); + let drop = ramp * tilt.to_radians().sin(); + let up = base + 30.0; + let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)]; + let end = up + 10.0 + drop + ramp + 30.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (end - 30.0)).abs() < 1e-6)).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let r = b.panels[flap].outline.bounds().expect("bounds"); + let m = f.panels[flap].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)); + let x = base + 20.0 - ramp - 15.0; + assert!(m[2].abs() < 1e-6 && (m[0] - x).abs() < 1e-2 && x > 0.0, "the flap lies on the base at {x}: {m:?}"); + // The flap's middle, from the front and from the back. + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + (at(0.0) == Some(flap), at(180.0) == Some(f.base)) + }; + assert_eq!(shown(100.0, 40.0, 0.01), (true, true), "a 40 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.01), (true, true), "a 500 pt ramp 0.01 pt high"); + assert_eq!(shown(2100.0, 2000.0, 0.01), (true, true), "a 2,000 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.001), (true, true), "a 500 pt ramp 0.001 pt high"); +} + +#[test] +fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_from() { + // A strip 30 pt tall: the base (x 0 to 1,000) and panels 100, 300, 200 and 50 pt wide, folded + // `tilt`, 180°, -2 `tilt` and `tilt`: at 0.04° the 200 pt panel comes back down onto the base's + // plane from about 0.14 pt off it, at 0.00001° from 0.00004 pt, and the last panel lies on the + // base. + for tilt in [0.04, 0.00001] { + flap_brought_back_by_folds_all_near_flat(tilt); + } +} + +fn flap_brought_back_by_folds_all_near_flat(tilt: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)]; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (ramp, flap) = (starts_at(1400.0), starts_at(1600.0)); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let (m, above) = (middle(flap), middle(ramp)[2]); + assert!(m[2].abs() < 1e-3 && (0.0..1000.0).contains(&m[0]) && above.abs() > tilt * 0.25, "the flap lies on the base: {m:?}, the ramp at {above}"); + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + let (from_front, from_back) = (at(0.0), at(180.0)); + if above > 0.0 { + assert_eq!((from_front, from_back), (Some(flap), Some(f.base)), "{tilt}°"); + } else { + assert_eq!((from_front, from_back), (Some(f.base), Some(flap)), "{tilt}°"); + } +} + +#[test] +fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() { + // The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's + // first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)]; + lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0))); + for (i, (x, a)) in [(100.0, 90.0), (120.0, -90.0), (140.0, -90.0), (180.0, -90.0), (220.0, -90.0)].into_iter().enumerate() { + lines.push(line(&[(x, 0.0), (x, 60.0)], false, Crease, 3 + i as u64, Some(a))); + } + lines.push(line(&[(240.0, 0.0), (240.0, 30.0)], false, Crease, 9, Some(90.0))); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (panel, flap) = (starts_at(0.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(f.base, starts_at(-150.0)); + let mut seen = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the panel from one side and then the other: how many pixels show the flap. + let camera = Camera { width: 400, height: 200, rotate_y, center: [0.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[panel].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flaps = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(flap)).count(); + seen.push((printed, flaps)); + } + let (from_print, from_back) = if seen[0].0 { (seen[0].1, seen[1].1) } else { (seen[1].1, seen[0].1) }; + assert_ne!(seen[0].0, seen[1].0, "both sides of the panel are looked at"); + assert!(from_print > 600 && from_back == 0, "the flap shows on the panel's printed side only: {seen:?}"); +} + +#[test] +fn a_strip_rolled_up_45_times_keeps_the_base_in_front() { + // A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so + // each panel rolls under the one before it and all of them lie behind the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let end = 60.0 + 45.0 * 50.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| { + let x = 60.0 + 50.0 * f64::from(i); + super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 10 + u64::from(i), + angle: Some(180.0), + } + })); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(40, 30), Some(f.base)); +} + +#[test] +fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() { + // A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to + // 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies + // behind the flat strips at x 65 to 75. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0))); + lines.push(crease(105.0, 2, 180.0)); + lines.push(crease(145.0, 3, 180.0)); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (strip, middle, flap) = (starts_at(70.0), starts_at(105.0), starts_at(145.0)); + let camera = Camera { width: 160, center: [80.0, -50.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown = img.panel_at(70, 30); + assert_eq!(shown, Some(strip), "a flat strip, not the flap ({flap}) or the folded panel ({middle})"); +} + #[test] fn a_hole_in_a_panel_is_left_empty() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..6781a2c64d 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() { + // A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes + // the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest + // panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the + // origin and 3,000,000 pt to the right. + let own_tree = |dx: f64| { + let lines = |closing: Option| { + let crease = |a: (f64, f64), b: (f64, f64), key: u64| { + let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key); + l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 }); + l + }; + vec![ + cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1), + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (b, issues) = check(&lines(None)); + assert!(issues.is_empty(), "{issues:?}"); + let level = fold(&b[0], None, 1.0, TOL).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = b[0].hinges[closing].keys[0]; + let (b, issues) = check(&lines(Some(key))); + assert!(issues.is_empty(), "{issues:?}"); + let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds"); + f.stack.root == f.base + }; + assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree"); + assert!(own_tree(3_000_000.0), "far from the origin too"); +} + +#[test] +fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() { + // A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the + // grid's right squares. Every crease is at 0° but the one between the two left squares, at a + // millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out + // and places the other square at most 0.0000001 pt from where the fold's own tree does. + let mut lines = vec![ + cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1), + crease((5.0, 0.0), (5.0, 5.0), 2), + crease((5.0, 5.0), (5.0, 10.0), 3), + crease((0.0, 5.0), (5.0, 5.0), 4), + crease((5.0, 5.0), (10.0, 5.0), 5), + crease((10.0, 0.0), (10.0, 10.0), 6), + ]; + for l in &mut lines { + l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 }); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge"); + let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds"); + assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4])); + assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns"); +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 3f4d2e4551..e43aed7ec8 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -1,8 +1,10 @@ //! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected -//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu +//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold +//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold +//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches… +//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each //! with a Select button; each document's list is kept until that document changes. Its Fold Preview //! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). @@ -27,6 +29,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that sets or resets the fold angle of fold lines. +pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees. +pub const FOLD_ANGLES: std::ops::RangeInclusive = -180.0..=180.0; +/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is +/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the +/// place the field's fine steps (a tenth of a degree) round to. +pub fn angle_places(angle: Option) -> usize { + // f64's Display is the shortest text that reads back as the same number, without an exponent. + angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1) +} /// The command that shows the Fold Preview window. pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. @@ -50,6 +64,7 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Cmd("Set Fold Angle…", SET_FOLD_ANGLE, Value::Null), Item::Sep, Item::Cmd("Fold Preview", PREVIEW, json!({})), ] @@ -211,15 +226,23 @@ struct Rows { /// What they were read for: the document, its revision and its selection. key: Option<(u64, u64, Vec)>, rows: Vec, + /// Whether the rows count the selection (not the whole document). + selection: bool, + /// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change. + fold_lines: u64, + /// The angle they all fold at (`None`: they differ, or there are none). + angle: Option, + /// How many of them hold a stored angle, readable or not: what Reset takes away. + stored_angles: u64, } /// The rows for the active document as it is now, read again only when it changed. -fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; +fn read_rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Rows { + let Some(st) = app.session.active() else { return Rows::default() }; let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); let mut kept: Rows = pstate(ctx, STATE); if kept.key.as_ref() == Some(&key) { - return kept.rows; + return kept; } let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); let d = app.session.active().map(|st| st.doc.clone()); @@ -228,9 +251,55 @@ fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) }; - kept = Rows { key: Some(key), rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect() }; + kept = Rows { + key: Some(key), + rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(), + selection: answer["scope"] == "selection", + fold_lines: answer["foldLines"].as_u64().unwrap_or(0), + angle: answer["foldAngle"].as_f64(), + stored_angles: answer["storedAngles"].as_u64().unwrap_or(0), + }; set_pstate(ctx, STATE, kept.clone()); - kept.rows + kept +} + +/// The role rows for the active document as it is now. +fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + read_rows(app, ctx).rows +} + +/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle +/// the selected lines that it can change all fold at, else 90°. The command's reason while it +/// can't change any. +pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result { + let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; + (command.enabled)(&app.session)?; + let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); + Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle })) +} + +/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle +/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which +/// takes away the angles of their own. +fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { + if !kept.selection || kept.fold_lines == 0 { + return; + } + let mut call = None; + ui.horizontal(|ui| { + widgets::field_label(ui, tl!("Fold Angle")); + if let Some(a) = widgets::mixed_field_within(ui, "fold-angle", kept.angle, "°", angle_places(kept.angle), 64.0, FOLD_ANGLES) { + call = Some(json!({ "angle": a })); + } + if ui.add_enabled_ui(kept.stored_angles > 0, |ui| widgets::flat_button_fit(ui, tl!("Reset"), 56.0)).inner.clicked() { + call = Some(json!({ "reset": true })); + } + }); + if let Some(p) = call + && let Err(e) = app.run(SET_FOLD_ANGLE, p) + { + app.status(e); + } } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -244,7 +313,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); } let mut picked = None; - for (role, swatch, paint, count) in rows(app, ui.ctx()) { + let kept = read_rows(app, ui.ctx()); + for (role, swatch, paint, count) in kept.rows.iter().cloned() { let label = ROLES.iter().find(|(_, id)| *id == role).map_or(role.as_str(), |(l, _)| *l); let clicked = ui .add_enabled_ui(selected, |ui| { @@ -267,6 +337,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_angle(app, ui, &kept); show_check(app, ui); } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index c3c69c3f31..79d6ba345a 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -470,6 +470,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { order: vec![], hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], collisions: vec![(0, 1)], + stack: Default::default(), + origin: [0.0; 3], }; let lines = status(3, Some((&Blank::default(), &f)), true); assert_eq!( diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 2ce5643fc3..4ee1334759 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_engine::Session; -use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use super::{CHECK, ID, ROLES, SET_FOLD_ANGLE, SET_ROLE, SET_ROLE_SWATCH, show}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -274,12 +274,167 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { + let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } } +#[test] +fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Set Fold Angle…").expect("listed"); + assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE)); + let opened = |app: &mut VectorcraftApp| { + let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params); + menus::invoke(app, &target, p); + let d = app.ui.dialog.take().expect("a dialog"); + assert_eq!((d.kind.as_str(), d.str("__command")), ("command", SET_FOLD_ANGLE.to_string())); + d.fields["angle"].as_f64() + }; + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(opened(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own"); + app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap(); + assert_eq!(opened(&mut app), Some(45.0)); + // The cut line does not fold, so the crease's angle is still the one shown. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(opened(&mut app), Some(45.0)); + // Lines that differ open on 90°. + let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap(); + app.run("select.set", json!({"ids": [a, c]})).unwrap(); + assert_eq!(opened(&mut app), Some(90.0)); + // With only a cut line selected there is nothing to set: no dialog opens. + app.run("select.set", json!({"ids": [b]})).unwrap(); + let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params); + menus::invoke(&mut app, &target, p); + assert!(app.ui.dialog.is_none()); + // ui.menuDialog gives the command's reason. + let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err(); + assert!(e.contains("select a crease, partial cut or perforation line"), "{e}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap(); + assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(45.0)); + // The options dialog opened with an angle keeps it. + menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}})); + assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(30.0)); +} + +/// Set Fold Angle… keeps the angle typed into its dialog within -180° to 180°, so OK applies the +/// nearest end instead of closing on an angle the command refuses. +#[test] +fn set_fold_angle_s_dialog_keeps_the_angle_within_its_range() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("181"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(180.0)); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}"); + // An angle typed with more places than the field shows is kept as typed, as the panel keeps it. + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("179.9999"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(179.9999)); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(179.9999), "{r}"); + // Opened on an angle with more places than that, the dialog shows them all, so typing 180 sets 180. + h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap(); + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("180"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}"); + // A fine step from a whole angle steps a tenth of a degree. + h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 90, "ids": [a]})).unwrap(); + menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({})); + h.run_steps(3); + h.get_by_role_and_label(Role::TextInput, "Angle:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::ArrowUp); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(90.1)); +} + +#[test] +fn a_fold_angle_field_shows_every_place_the_angle_has() { + use super::angle_places; + assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]); +} + +#[test] +fn the_panel_shows_and_resets_the_selected_lines_fold_angle() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let text = painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("Fold Angle") && text.contains("135"), "{text}"); + click_row(&mut app, "Reset"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "{r}"); + // Stored text that is not an angle: the field shows the role's angle, and Reset removes the text. + app.session + .edit("Test", |d, _| { + if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) { + n.edit_attrs(|at| at.data.push(("vc-fold-angle".into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64(), r["storedAngles"].as_u64()), (Some(90.0), Some(0), Some(1)), "{r}"); + click_row(&mut app, "Reset"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["storedAngles"].as_u64(), Some(0), "{r}"); +} + #[test] fn the_panel_without_a_document_asks_for_one() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index de7836f0a5..5f57750cf8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -163,6 +163,15 @@ pub(super) fn length_range(command: &str, key: &str) -> Option Option> { + match (command, key) { + (crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES), + _ => None, + } +} + /// The order the fields of the commands this dialog edits come in, where the order of their /// names isn't it (the rest follow, by name). fn order(command: &str) -> &'static [&'static str] { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index b46f35a79f..b2c2b3cb61 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -510,6 +510,14 @@ pub(super) fn param_fields( changed = true; } } + Value::Number(n) if let Some(range) = super::command::number_range(&d.str("__command"), &k) => { + // Kept within the range as typed, and shown to the places a fold angle keeps. + let places = crate::addons::packaging::angle_places(n.as_f64()); + if let Some(x) = crate::widgets::mixed_field_within(ui, ("fx-num", &k), n.as_f64(), "", places, 140.0, range) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + } Value::Number(n) => { // A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language. let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() }; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d371a5f1e4..5b99e36d20 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7653,6 +7653,11 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Fold Angle Ъгъл на сгъване + Set Fold Angle… Задай ъгъл на сгъване… + Set Fold Angle Задай ъгъл на сгъване + Reset Fold Angle Нулирай ъгъла на сгъване +@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита Check Провери Check Fold Lines Провери линиите на сгъване @msg No cut lines are in the selection. В селекцията няма линии за рязане. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 00d07d469d..09e931ff5c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7708,6 +7708,11 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Fold Angle Ugao savijanja + Set Fold Angle… Postavi ugao savijanja… + Set Fold Angle Postavi ugao savijanja + Reset Fold Angle Poništi ugao savijanja +@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena Check Provjeri Check Fold Lines Provjeri linije savijanja @msg No cut lines are in the selection. U odabiru nema linija rezanja. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 78e5a77c9e..b5dbfa65ca 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8610,6 +8610,11 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Fold Angle Angle de plegat + Set Fold Angle… Defineix l’angle de plegat… + Set Fold Angle Defineix l’angle de plegat + Reset Fold Angle Restableix l’angle de plegat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada Check Comprova Check Fold Lines Comprova les línies de plegat @msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bd3e76ec50..dd629eba4b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -10406,6 +10406,11 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Fold Angle Úhel skladu + Set Fold Angle… Nastavit úhel skladu… + Set Fold Angle Nastavit úhel skladu + Reset Fold Angle Obnovit úhel skladu +@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá Tap Krátký stisk Clear Hold Vymazat podržení Hold Shortcuts Zkratky podržením diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3fb128a27a..c1263a2f8e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10498,6 +10498,11 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Fold Angle Foldevinkel + Set Fold Angle… Angiv foldevinkel… + Set Fold Angle Angiv foldevinkel + Reset Fold Angle Nulstil foldevinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult Check Kontrollér Check Fold Lines Kontrollér foldelinjer @msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6ad4e3850b..2309e2d1dd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -10019,6 +10019,11 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Fold Angle Faltwinkel + Set Fold Angle… Faltwinkel festlegen… + Set Fold Angle Faltwinkel festlegen + Reset Fold Angle Faltwinkel zurücksetzen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist Tap Kurz drücken Clear Hold Halten löschen Hold Shortcuts Halte-Tastaturbefehle diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7d2e5b6363..0e17bbc511 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8584,6 +8584,11 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Fold Angle Γωνία δίπλωσης + Set Fold Angle… Ορισμός γωνίας δίπλωσης… + Set Fold Angle Ορισμός γωνίας δίπλωσης + Reset Fold Angle Επαναφορά γωνίας δίπλωσης +@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή Check Έλεγχος Check Fold Lines Έλεγχος γραμμών δίπλωσης @msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 30678f8a13..49bcbf2730 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -10330,6 +10330,11 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Fold Angle Ángulo de plegado + Set Fold Angle… Definir ángulo de plegado… + Set Fold Angle Definir ángulo de plegado + Reset Fold Angle Restablecer ángulo de plegado +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta Check Comprobar Check Fold Lines Comprobar líneas de plegado @msg No cut lines are in the selection. No hay líneas de corte en la selección. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 873d339833..056fc15f8b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8667,6 +8667,11 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Fold Angle Taittokulma + Set Fold Angle… Aseta taittokulma… + Set Fold Angle Aseta taittokulma + Reset Fold Angle Palauta taittokulma +@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu Check Tarkista Check Fold Lines Tarkista taittoviivat @msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68bcc455b2..985f343e7a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -10391,6 +10391,11 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Fold Angle Angle de pliage + Set Fold Angle… Définir l’angle de pliage… + Set Fold Angle Définir l’angle de pliage + Reset Fold Angle Réinitialiser l’angle de pliage +@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée Tap Appui bref Clear Hold Effacer le maintien Hold Shortcuts Raccourcis de maintien diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index d7bb081e02..ffbd2bd3fb 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5396,6 +5396,11 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Fold Angle ફોલ્ડ ખૂણો + Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો… + Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો + Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો +@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય Check ચેક કરો Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો @msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2837a15b67..c9363394c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10012,6 +10012,11 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Fold Angle फ़ोल्ड कोण + Set Fold Angle… फ़ोल्ड कोण सेट करें… + Set Fold Angle फ़ोल्ड कोण सेट करें + Reset Fold Angle फ़ोल्ड कोण रीसेट करें +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो Tap जल्दी दबाना Clear Hold होल्ड साफ़ करें Hold Shortcuts होल्ड शॉर्टकट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fbc2e30bd1..82af3ad6b8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -10394,6 +10394,11 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Fold Angle Hajtásszög + Set Fold Angle… Hajtásszög beállítása… + Set Fold Angle Hajtásszög beállítása + Reset Fold Angle Hajtásszög visszaállítása +@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve Tap Rövid lenyomás Clear Hold Nyomva tartás törlése Hold Shortcuts Nyomva tartásos billentyűparancsok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ab48475d3d..51f9b7b34c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7668,6 +7668,11 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Fold Angle Sudut lipat + Set Fold Angle… Atur sudut lipat… + Set Fold Angle Atur sudut lipat + Reset Fold Angle Atur ulang sudut lipat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden pilih garis lekuk, garis potong sebagian, atau garis perforasi yang tidak terkunci dan tidak tersembunyi Check Periksa Check Fold Lines Periksa garis lipat @msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a3b493cd1d..43c01df826 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -10052,6 +10052,11 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Fold Angle Angolo di piega + Set Fold Angle… Imposta angolo di piega… + Set Fold Angle Imposta angolo di piega + Reset Fold Angle Reimposta angolo di piega +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleziona una linea di cordonatura, di taglio parziale o di perforazione che non sia bloccata né nascosta Tap Pressione breve Clear Hold Cancella pressione prolungata Hold Shortcuts Scorciatoie a pressione prolungata diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5de0cae50c..8a88738a10 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10116,6 +10116,11 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Fold Angle 折り角度 + Set Fold Angle… 折り角度を設定… + Set Fold Angle 折り角度を設定 + Reset Fold Angle 折り角度をリセット +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ロックも非表示もされていない筋入れ線、半抜き線またはミシン目線を選択してください Tap 短押し Clear Hold 長押しを消去 Hold Shortcuts 長押しショートカット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 81fc06870d..24a4e6b853 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10746,6 +10746,11 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მარკირებისთვის. Remove Fold Line Role ხაზის ტიპის მოხსნა + Fold Angle მოკეცვის კუთხე + Set Fold Angle… მოკეცვის კუთხის დაყენება… + Set Fold Angle მოკეცვის კუთხის დაყენება + Reset Fold Angle მოკეცვის კუთხის ჩამოყრა +@msg select a crease, partial cut or perforation line that is neither locked nor hidden მონიშნეთ ბიგის, ნაწილობრივი ჭრის ან პერფორაციის ხაზი, რომელიც არც ჩაკეტილია და არც დამალული Check შემოწმება Check Fold Lines მოკეცვის ხაზების შემოწმება @msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4a6963bbd2..56a0a96573 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -10015,6 +10015,11 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Fold Angle 접는 각도 + Set Fold Angle… 접는 각도 설정… + Set Fold Angle 접는 각도 설정 + Reset Fold Angle 접는 각도 재설정 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 잠기거나 숨겨지지 않은 오시선, 하프 컷 선 또는 미싱선을 선택하세요 Tap 짧게 누르기 Clear Hold 길게 누르기 지우기 Hold Shortcuts 길게 누르기 단축키 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 894c7096f6..18bc758d8c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10443,6 +10443,11 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Fold Angle Vouwhoek + Set Fold Angle… Vouwhoek instellen… + Set Fold Angle Vouwhoek instellen + Reset Fold Angle Vouwhoek herstellen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecteer een rillijn, halve snijlijn of perforatielijn die niet vergrendeld of verborgen is Tap Kort drukken Clear Hold Vasthouden wissen Hold Shortcuts Vasthoudsneltoetsen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c69ed2cf28..d660ec1acd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -10269,6 +10269,11 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Fold Angle Kąt zgięcia + Set Fold Angle… Ustaw kąt zgięcia… + Set Fold Angle Ustaw kąt zgięcia + Reset Fold Angle Resetuj kąt zgięcia +@msg select a crease, partial cut or perforation line that is neither locked nor hidden zaznacz linię bigowania, nacięcia lub perforacji, która nie jest zablokowana ani ukryta Tap Krótkie naciśnięcie Clear Hold Wyczyść przytrzymanie Hold Shortcuts Skróty przytrzymania diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6bae5e26f1..b52732995d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10478,6 +10478,11 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Fold Angle Ângulo de Dobra + Set Fold Angle… Definir Ângulo de Dobra… + Set Fold Angle Definir Ângulo de Dobra + Reset Fold Angle Redefinir Ângulo de Dobra +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecione uma linha de vinco, de meio-corte ou de perfuração que não esteja bloqueada nem oculta Tap Toque Rápido Clear Hold Limpar Pressionamento Longo Hold Shortcuts Atalhos de Pressionamento Longo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 74156da429..0a5172c786 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10492,6 +10492,11 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Fold Angle Угол сгиба + Set Fold Angle… Задать угол сгиба… + Set Fold Angle Задать угол сгиба + Reset Fold Angle Сбросить угол сгиба +@msg select a crease, partial cut or perforation line that is neither locked nor hidden выделите линию биговки, надреза или перфорации, которая не закреплена и не скрыта Check Проверить Check Fold Lines Проверить линии сгиба @msg No cut lines are in the selection. В выделении нет линий реза. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4d683cb1ea..a4013cc169 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10096,6 +10096,11 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Fold Angle Falsvinkel + Set Fold Angle… Ange falsvinkel… + Set Fold Angle Ange falsvinkel + Reset Fold Angle Återställ falsvinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markera en biglinje, halvskärlinje eller perforeringslinje som varken är låst eller dold Check Kontrollera Check Fold Lines Kontrollera falslinjer @msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d0e30b8fdc..07fb929d7d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10364,6 +10364,11 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Fold Angle Katlama Açısı + Set Fold Angle… Katlama Açısını Ayarla… + Set Fold Angle Katlama Açısını Ayarla + Reset Fold Angle Katlama Açısını Sıfırla +@msg select a crease, partial cut or perforation line that is neither locked nor hidden kilitli ya da gizli olmayan bir pilyaj, yarım kesim veya perforaj çizgisi seçin Tap Kısa Basma Clear Hold Basılı Tutmayı Temizle Hold Shortcuts Basılı Tutma Kısayolları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 82ba9af243..2541e72109 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -10028,6 +10028,11 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Fold Angle Кут згину + Set Fold Angle… Задати кут згину… + Set Fold Angle Задати кут згину + Reset Fold Angle Скинути кут згину +@msg select a crease, partial cut or perforation line that is neither locked nor hidden виділіть лінію біговки, надрізу або перфорації, яка не закріплена й не прихована Tap Коротке натискання Clear Hold Очистити утримання Hold Shortcuts Клавіші утримання diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 04ebd9992d..dfe76ef3de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8137,6 +8137,11 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Fold Angle Góc gấp + Set Fold Angle… Đặt góc gấp… + Set Fold Angle Đặt góc gấp + Reset Fold Angle Đặt lại góc gấp +@msg select a crease, partial cut or perforation line that is neither locked nor hidden hãy chọn một đường cấn, đường cắt một phần hoặc đường đục lỗ không bị khóa và không bị ẩn Check Kiểm tra Check Fold Lines Kiểm tra đường gấp @msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d20ae8d9e8..a1ae040aec 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -10253,6 +10253,11 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Fold Angle 折叠角度 + Set Fold Angle… 设置折叠角度… + Set Fold Angle 设置折叠角度 + Reset Fold Angle 重置折叠角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 请选择未锁定且未隐藏的压痕线、半切线或打孔线 Check 检查 Check Fold Lines 检查折线 @msg No cut lines are in the selection. 所选内容中没有切割线。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5fde762f9..56855c3a66 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -10068,6 +10068,11 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Fold Angle 摺疊角度 + Set Fold Angle… 設定摺疊角度… + Set Fold Angle 設定摺疊角度 + Reset Fold Angle 重設摺疊角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 請選取未鎖定且未隱藏的壓痕線、半切線或打孔線 Check 檢查 Check Fold Lines 檢查摺線 @msg No cut lines are in the selection. 選取範圍中沒有切割線。 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 42c6da3a10..f48cf11dae 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -75,6 +75,8 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + // Set Fold Angle… opens on the angle the selected fold lines fold at, while it can change one. + crate::addons::packaging::SET_FOLD_ANGLE => ("command", crate::addons::packaging::dialog_fields(app).ok()?), crate::addons::pathtools::set_corners::COMMAND => { (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..931a66b52c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -963,6 +963,11 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::envelope::open(app, c), + // Set Fold Angle's dialog says why it can't open, as the command does. + Some(crate::addons::packaging::SET_FOLD_ANGLE) => crate::addons::packaging::dialog_fields(app).map(|fields| { + app.ui.dialog = Some(crate::state::Dialog::new("command", fields)); + Value::Null + }), c => match c.and_then(|c| menu_dialog(app, c)) { Some((kind, fields)) => { app.ui.dialog = Some(crate::state::Dialog::new(kind, fields)); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fbfd12b24e..ddb4bc3939 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1412,7 +1412,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d6a0f7c50e..7f44f2bbca 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -60,7 +60,7 @@ pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_labe pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ - SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, + SpinPick, mixed_field, mixed_field_named, mixed_field_within, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, num_field_within_empty, opt_field, opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_length_within, spin_plain, spin_plain_named, spin_range, diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index a9d4020ab3..efdbf64006 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -842,6 +842,21 @@ pub fn mixed_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option, su mixed_field_named(ui, id, None, value, suffix, decimals, width) } +/// [`mixed_field`] whose value is kept within `bounds`: steps stop at its ends, and a typed value +/// past one is brought to it. +pub fn mixed_field_within( + ui: &mut Ui, + id: impl std::hash::Hash, + value: Option, + suffix: &str, + decimals: usize, + width: f32, + bounds: RangeInclusive, +) -> Option { + let label = take_previous_label(ui); + bounded_field(ui, id, label, None, value, suffix, decimals, width, &bounds, None, false, false).map(|v| within(v, &bounds)) +} + /// [`mixed_field`] for a row named explicitly instead of by an adjacent label widget. pub fn mixed_field_named( ui: &mut Ui, diff --git a/docs/mcp.md b/docs/mcp.md index 5bc273289c..f4fd4ced7d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14304,10 +14304,11 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and -`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, -Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the -selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check`, +`addon.packaging.setFoldAngle` and `addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold +Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run +`addon.packaging.setRole` on the selection, Check Fold Lines runs `addon.packaging.check`, Set Fold Angle… opens the +options of `addon.packaging.setFoldAngle`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -14338,11 +14339,17 @@ the color it shows, no longer linked to the swatch, and stops overprinting. Text objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. -`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's -swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object -of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are -counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows -these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so. +`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected, foldLines, +foldAngle, ownAngles, storedAngles}`: each role's swatch, whether the document has it, and how many of the objects have +the role. It counts the selection, or every object of the document while nothing is selected and `ids` is left out +(`scope` says which). Locked and hidden objects are counted in every scope, and an object is counted once when both it +and its group are given. `foldLines` is how many of the Crease, Partial Cut and Perforation lines among them +`addon.packaging.setFoldAngle` can change, which leaves out locked and hidden lines; it is 0 while nothing is selected +and `ids` is left out, and while the selection holds only a layer and objects in it. `foldAngle` is the angle in degrees +those lines all fold at (see Fold angles), or null when they fold at different angles or there are none; `ownAngles` is +how many of them have an angle of their own, and `storedAngles` how many hold stored angle text, an angle or not, which +`reset: true` removes. The Fold Lines panel shows these counts; clicking a role gives the selected paths that role. With +nothing selected the panel says so. `addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or @@ -14403,17 +14410,47 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold angles + +A Crease or a Perforation folds 90° away from the printed side, so the print ends up outside, and a Partial Cut folds +90° toward it. A Crease, Partial Cut or Perforation line can have an angle of its own instead, from -180° to 180°: a +positive angle folds away from the printed side and a negative one toward it. The angle is stored in the line's data +under `vc-fold-angle` as a number of degrees, rounded to the millionth of a degree (a stored value with more places +folds at it rounded the same way). Native files keep it. SVG export leaves it out of the path's attributes; an SVG with +`preserveEditing` keeps it in the document the SVG carries. A value that is not a number from -180 to 180 counts as no +angle of its own. A cut line ignores it. A line keeps its own angle when `addon.packaging.setRole` gives it another +role, or `none`, so a line made a Partial Cut after it was given 45° still folds at 45°; `reset: true` takes the angle +away. In the Fold Preview window, a panel folded flat onto another (180°) is drawn behind that panel's printed side, and +at -180° in front of it. Panels folded flat onto each other stack as they do when the blank is folded about its largest +panel, whichever panel the window folds about. + +`addon.packaging.setFoldAngle` (`{angle?: -180..180, reset?: false, ids?}`) gives each Crease, Partial Cut and +Perforation line among the objects (the selection by default), through groups and clip groups, the angle, or with +`reset: true` takes the line's own angle away. Give exactly one of `angle` and `reset: true`. Locked and hidden objects +are skipped as `addon.packaging.setRole` skips them; cut lines and objects without a role are skipped and counted. The +command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside +the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. + +Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the +angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. +While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection +holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it, and the Reset button beside it takes their own angles away. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.setFoldAngle","params":{"angle":135}}} +``` + ### Fold Preview `addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it -to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from -the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of -panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, -whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of -hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything -else is an error. The command does not change the document. +to the base, each by its angle times `amount` (0 is flat, 1 is folded). A hinge's angle is the fold angle of the line +with the most length in it (see Fold angles), the one with the lowest id among lines of equal length. A hinge that closes +a loop of panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all +the way, whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no +chain of hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; +anything else is an error. The command does not change the document. Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document From 4875606bb7d7a42a8f786fac505e77a66ad3596b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 02:47:00 -0800 Subject: [PATCH 03/49] Live Corners: a Corners link opens the corner settings of the picked corners The Control bar and the Properties panel show a Corners link beside the radius field of the picked corners. It opens a pop-up with the corner kind, the radius (blank while the picked corners differ) and Relative or Absolute rounding. Each change sets the picked corners of every selected path in one object.setLiveShape call with items, one undo step: the corners holding a Direct-Selected anchor, or every corner of a path selected whole. The Properties panel shows the link while a corner is Direct-Selected; its corner rows now cover several selected paths too, and a live rectangle or polygon selected alone, which keeps its own radius and kind rows, shows the link for the pop-up. object.setLiveShape with relativeRadii: true now works on a plain path with corners: the path keeps its outline as the base of its Live Corners. Before, it did nothing, and relativeRadii: false added an empty undo step. A Relative path whose corners are all uncut again keeps its rounding, and Absolute on one with no corner cut makes it a plain path again. With Relative rounding, a radius is now compared as the fraction it would store, so typing the radius the field shows, or a radius past the corner's maximum again, adds no undo step. Before, it was compared with the radius as drawn. Part of #1232. Reported by XTRECY-BD. --- crates/doc/src/corners.rs | 7 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 38 +++++- crates/engine/src/tests/livecorners.rs | 63 +++++++++ crates/ui-egui/src/chrome/control_bar.rs | 47 ++----- crates/ui-egui/src/chrome/tests.rs | 41 ++++++ crates/ui-egui/src/panels.rs | 112 ++++++++++++++++ crates/ui-egui/src/panels/properties.rs | 46 ++++--- crates/ui-egui/src/panels/properties/tests.rs | 125 +++++++++++++++++- crates/ui-egui/tests/control_bar_corners.rs | 2 +- docs/mcp.md | 15 ++- docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 13 files changed, 432 insertions(+), 68 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 24228604a6..3810bbb1f5 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -205,8 +205,8 @@ impl<'a> LiveCorners<'a> { /// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of /// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again. /// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a -/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they -/// are. +/// plain path again once no corner is cut, unless its rounding is Relative. Ellipses and lines +/// have no corners: they stay as they are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { fn edit( base: &PathData, @@ -268,7 +268,8 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, } match live.as_deref_mut() { - Some(LiveShape::Path { base, radii, kinds, .. }) if radii.is_empty() && kinds.is_empty() => { + // A path with Relative rounding keeps its record, and with it the rounding. + Some(LiveShape::Path { base, radii, kinds, radii_relative: false }) if radii.is_empty() && kinds.is_empty() => { *path = std::mem::take(base); *live = None; } diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..98b5579cbb 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole path: a live rectangle, a live polygon or any path with a corner, which keeps its outline as the base of its Live Corners; a path without Live Corners is Absolute, and a path whose anchors are edited loses its Live Corners and is Absolute again; ellipses and lines are left as they are), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut, unless its rounding is Relative; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index a4cec6253c..24274782d8 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,6 +99,17 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Whether `relativeRadii` applies to a path drawn as `path` with live shape `live`: a live +/// rectangle, a live polygon, a path with Live Corners, or a plain path with a corner. A plain +/// path's rounding is Absolute. +fn takes_rounding(path: &PathData, live: Option<&LiveShape>) -> bool { + match live { + Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }) => true, + Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => false, + None => LiveCorners::new(path, None).is_some_and(|c| !c.all().is_empty()), + } +} + /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about /// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { @@ -277,7 +288,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { + if relative_radii.is_some_and(|on| takes_rounding(path, live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -291,10 +302,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { && picked.iter().all(|k| { *k < c.base.anchor_count() // A radius stored in document units can be larger than it draws; a relative - // one is a fraction, so it is compared as drawn. + // one is compared as the fraction `set_corners` would store for it, to a + // precision of 1e-9 pt on a corner whose maximum is 1 pt or more. && radius.is_none_or(|r| { - let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) }; - (now - r.max(0.0)).abs() < 1e-9 + let r = r.max(0.0); + if c.radii_relative() { + let max = c.corner(*k).map_or(0.0, |c| c.max_radius()); + let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 }; + (c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9 + } else { + (c.radius(*k) - r).abs() < 1e-9 + } }) && kind.is_none_or(|kd| c.kind(*k) == kd) }) @@ -348,11 +366,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *l = new.clone(); *path = l.to_path(); } + // A path with corners and no Live Corners yet keeps its outline as their base, so that + // Relative rounding has a record to go in. + if relative_radii == Some(true) && live.is_none() && takes_rounding(path, None) { + *live = Some(Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![], radii_relative: false })); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { convert_radii_relative(l, on); *path = l.to_path(); + // Absolute with no corner cut: a plain path again, as `set_corners` leaves one. + if let LiveShape::Path { radii, kinds, radii_relative: false, .. } = l + && radii.is_empty() + && kinds.is_empty() + { + *live = None; + } } if radius.is_none() && kind.is_none() { continue; diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 288f0236d1..35d4f061ec 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,6 +910,69 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } +/// Relative rounding on a path with corners and no Live Corners yet takes effect in one undo step, +/// a radius set afterwards is stored as a fraction, and the rounding stays when no corner is cut +/// any more. Absolute, which such a path already has, and Relative on an ellipse, which has no +/// corners, add no undo step. +#[test] +fn relative_rounding_takes_on_a_plain_path() { + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.expandShape", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + assert_eq!(steps(&s), n, "Absolute: no change"); + run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); + assert_eq!(steps(&s), n + 1, "Relative: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(LiveCorners::of(node).unwrap().radii_relative()); + let max = LiveCorners::of(node).unwrap().corner(0).unwrap().max_radius(); + run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": max / 2.0})); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!(c.radii_relative() && (c.radius(0) - 0.5).abs() < 1e-9, "stored fraction: {}", c.radius(0)); + // With no corner cut again, the path keeps its Relative rounding. + run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": 0})); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!(c.radii_relative() && c.radius(0) == 0.0, "still Relative"); + // Absolute again with no corner cut: a plain path again. + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path again"); + let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let n = steps(&s); + run(&mut s, json!({"ids": [e], "relativeRadii": true})); + assert_eq!(steps(&s), n, "an ellipse: no change"); +} + +/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the +/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a +/// smaller one adds one. +#[test] +fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + let n = steps(&s); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "past the maximum: one undo step"); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0)); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "the same radius again: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max})); + assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max / 2.0})); + assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step"); + // On a large shape a small radius is a fraction below 1e-9, and still a change. + let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap(); + run(&mut s, json!({"ids": [big], "relativeRadii": true})); + let n = steps(&s); + run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001})); + assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step"); +} + /// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round, /// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag. #[test] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ce7f95808d..8831816527 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -78,45 +78,18 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } -/// The selected paths' eligible corners, as document lengths, beside the anchor controls. -/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). -fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, reserve: f32) { - let Some(st) = app.session.active() else { return }; - let mut items = Vec::new(); - let mut radius: Option = None; - let mut mixed = false; - for &id in &st.selection.objects { - let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; - let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); - if corners.is_empty() { - continue; - } - for &k in &corners { - // Keep absolute requested radii, even when their drawing is fitted smaller. Relative - // storage is a fraction, but the field and setLiveShape both consume document lengths. - let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; - if let Some(first) = radius { - mixed |= (first - value).abs() >= 1e-9; - } else { - radius = Some(value); - } - } - items.push(json!({"id": id, "corners": corners})); - } - if items.is_empty() { +/// The Corners link and the radius of the selected paths' picked corners +/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners +/// pop-up for those corners. +fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { + let Some(picked) = crate::panels::picked_corners(app) else { return }; + if ui.available_width() < row_width(ui, &[crate::panels::corners_link_width(ui), INLINE_FIELD_WIDTH]) + reserve { return; } - let label = tl!("Corner Radius:"); - let text = egui::RichText::new(label).size(12.0).color(t.text); - if ui.available_width() < row_width(ui, &[widgets::text_width(ui, text.clone()), INLINE_FIELD_WIDTH]) + reserve { - return; - } - widgets::field_label(ui, text); - let shown = if mixed { None } else { radius }; + crate::panels::corners_link(app, ui, "cb-corners"); let unit = app.session.general_unit(); - if let Some(radius) = widgets::num_field_named(ui, "cb-corner-radius", Some(label), shown, unit, INLINE_FIELD_WIDTH) { - // App::run reports any command failure in the status bar, as the other inline fields do. - app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + if let Some(radius) = widgets::num_field_named(ui, "cb-corner-radius", Some(tl!("Corner Radius:")), picked.radius, unit, INLINE_FIELD_WIDTH) { + crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)})); } } @@ -1083,7 +1056,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); let reserve = transform_reserve(app, ui, count > 0); - corner_radius(app, ui, t, reserve); + corner_radius(app, ui, reserve); } let object_options = group_on(app, "objectOptions"); if object_options { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b6c7a47015 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -4383,6 +4383,47 @@ fn the_anchor_points_group_holds_convert_and_anchors() { assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); } +/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners +/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step. +#[test] +fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { + use vectorcraft_geom::shapes::CornerKind; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame(app, &ctx, events); + let click = |frame: &mut dyn FnMut(&mut crate::VectorcraftApp, Vec) -> Vec, + app: &mut crate::VectorcraftApp, + name: &str| { + let at = node_center(&frame(app, vec![]), name).unwrap_or_else(|| panic!("{name} shows")); + frame(app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(app, vec![press_at(at, false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + assert!(node_center(&nodes, "Chamfer").is_none(), "the pop-up starts closed"); + let nodes = click(&mut frame, &mut app, "Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius:", "Relative", "Absolute"] { + assert!(node_center(&nodes, name).is_some(), "the pop-up has {name}"); + } + let depth = app.session.doc().unwrap().history.undo.len(); + click(&mut frame, &mut app, "Chamfer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); +} + /// Menus stop above a Control bar docked at the bottom when the status bar is hidden, above the /// status and hint bars when they show, and at the bottom of the window when the bar is docked at /// the top or a screen mode hides it. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6c4d7860e7..d7f4c6327a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -216,6 +216,118 @@ pub(crate) fn corner_radius_field(app: &mut VectorcraftApp, ui: &mut Ui, n: &Nod } } +/// The corners that the Corners link, its pop-up and the Corner Radius field beside it edit: +/// [`picked_corners`]. +pub(crate) struct PickedCorners { + /// `object.setLiveShape`'s `items`: `{id, corners}` for each path. + pub items: Vec, + /// The radius the corners share, as a document length; None when they differ. + pub radius: Option, + /// The kind the corners share; None when they differ. + pub kind: Option, + /// Whether their paths store relative radii; None when the paths differ. + pub relative: Option, +} + +/// The picked corners of the selection: for each selected path with Live Corners, the corners +/// holding a Direct-Selected anchor, or every corner of a path selected whole. A path whose +/// selected anchors hold no corner adds none. None when no path adds a corner. +pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option { + fn shared(values: &[T], same: impl Fn(T, T) -> bool) -> Option { + let (&first, rest) = values.split_first()?; + rest.iter().all(|v| same(*v, first)).then_some(first) + } + let st = app.session.active()?; + let (mut items, mut radii, mut kinds, mut relative) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for &id in &st.selection.objects { + let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) else { continue }; + let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); + if corners.is_empty() { + continue; + } + for &k in &corners { + // The radius asked for, even where it draws smaller. A relative radius is stored as a + // fraction of the corner's largest; the field and `object.setLiveShape` take lengths. + radii.push(if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }); + kinds.push(lc.kind(k)); + } + relative.push(lc.radii_relative()); + items.push(json!({"id": id, "corners": corners})); + } + if items.is_empty() { + return None; + } + Some(PickedCorners { + items, + radius: shared(&radii, |a, b| (a - b).abs() < 1e-9), + kind: shared(&kinds, |a, b| a == b), + relative: shared(&relative, |a, b| a == b), + }) +} + +/// Run `object.setLiveShape` with `p` (a `kind`, `radius` or `relativeRadii`) on `picked`'s +/// corners: one undo step, or none when nothing changes. `App::run` reports a failure in the +/// status bar. +pub(crate) fn set_picked_corners(app: &mut VectorcraftApp, picked: &PickedCorners, mut p: Value) { + p["items"] = json!(picked.items); + app.run("object.setLiveShape", p).ok(); +} + +/// The Corners link's text, as [`corners_link`] draws it and [`corners_link_width`] measures it. +fn corners_link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Corners")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The width of [`corners_link`] in `ui`, with the point that the underline can add at its end. +pub(crate) fn corners_link_width(ui: &Ui) -> f32 { + crate::widgets::text_width(ui, corners_link_text(ui)) + 1.0 +} + +/// The Corners link of the Control bar and the Properties panel: a click on it opens or closes +/// [`corners_popup`] under it. `id` tells the two places apart. +pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { + let resp = ui.link(corners_link_text(ui)); + crate::widgets::popover(&resp, resp.clicked(), |ui| corners_popup(app, ui, id)); +} + +/// The Corners pop-up: the corner kind, the radius (blank while the picked corners differ) and +/// the rounding, Relative or Absolute (neither while their paths differ), of the picked corners +/// ([`picked_corners`]). Each change sets them on those corners alone, in one undo step. +fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { + let Some(picked) = picked_corners(app) else { return }; + let unit = app.session.general_unit(); + let mut set = None; + egui::Grid::new((id, "corners-popup")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + dim_label(ui, tl!("Corner:")); + ui.vertical(|ui| { + for k in CornerKind::ALL { + if crate::widgets::radio(ui, crate::dialogs::corners::kind_label(k), picked.kind == Some(k), true) { + set = Some(json!({"kind": k})); + } + } + }); + ui.end_row(); + dim_label(ui, tl!("Radius:")); + if let Some(r) = crate::widgets::num_field_named(ui, (id, "radius"), Some(tl!("Radius:")), picked.radius, unit, 100.0) { + // A negative radius typed in rounds nothing: the command takes 0 or more. + set = Some(json!({"radius": r.max(0.0)})); + } + ui.end_row(); + ui.label(""); + ui.horizontal(|ui| { + for (label, on) in [(tl!("Relative"), true), (tl!("Absolute"), false)] { + if crate::widgets::radio(ui, label, picked.relative == Some(on), true) { + set = Some(json!({"relativeRadii": on})); + } + } + }); + ui.end_row(); + }); + if let Some(p) = set { + set_picked_corners(app, &picked, p); + } +} + /// Number of selected objects. pub(crate) fn selection_len(app: &VectorcraftApp) -> usize { app.session.active().map(|d| d.selection.len()).unwrap_or(0) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 94b4edc638..0c2313c8f0 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -202,38 +202,50 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { }) } -/// The Corners of the one path whose corners Direct Selection has selected: their kind and radius, -/// which `object.setLiveShape` sets on those corners. The Properties panel overview shows the -/// control while the Direct Selection tool is chosen and a corner of an object is selected -/// (). -/// A live rectangle's and a live polygon's own rows already set the selected corners. +/// The Corners of the paths whose corners Direct Selection has selected: their kind, and the +/// Corners link with their radius, which `object.setLiveShape` sets on those corners +/// ([`super::picked_corners`]); the link opens the Corners pop-up for them. The Properties panel +/// overview shows the control while the Direct Selection tool is chosen and a corner of an object +/// is selected +/// (), +/// and the Corners link opens the corner settings +/// (). One live +/// rectangle or live polygon selected alone has its own kind and radius rows, which already set +/// the selected corners: it shows the Corners link alone. fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.tool_id() != "directSelection" { return; } let Some(st) = app.session.active() else { return }; - let [id] = st.selection.objects[..] else { return }; - let Some(n) = st.doc.node(id) else { return }; - if matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })) { + let own_rows = matches!(st.selection.objects[..], [id] + if st.doc.node(id).is_some_and(|n| matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })))); + // A corner of a path is Direct-Selected. + let corner_selected = st.selection.objects.iter().any(|id| { + st.doc.node(*id).and_then(LiveCorners::of).is_some_and(|lc| st.selection.partial(*id).is_some_and(|a| !lc.corners_of(a).is_empty())) + }); + if !corner_selected { return; } - let Some(lc) = LiveCorners::of(n) else { return }; - if st.selection.partial(id).is_none_or(|a| lc.corners_of(a).is_empty()) { + let Some(picked) = super::picked_corners(app) else { return }; + if own_rows { + ui.horizontal(|ui| super::corners_link(app, ui, "props-corners")); return; } - let n = n.clone(); - let kind = super::corner_style(app, &n).1; let kinds: Vec<&str> = vectorcraft_geom::shapes::CornerKind::ALL.iter().map(|k| crate::dialogs::corners::kind_label(*k)).collect(); let fw = super::field_width(ui); + let unit = app.session.general_unit(); egui::Grid::new("props-corners").num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { dim_label(ui, tl!("Corner:")); - let picked = widgets::dropdown_names(ui, ("props-corners", "kind"), kind.map_or("", crate::dialogs::corners::kind_label), &kinds, fw); - if let Some(k) = picked.and_then(|i| vectorcraft_geom::shapes::CornerKind::ALL.get(i)) { - app.run("object.setLiveShape", json!({"kind": k})).ok(); + let kind = widgets::dropdown_names(ui, ("props-corners", "kind"), picked.kind.map_or("", crate::dialogs::corners::kind_label), &kinds, fw); + if let Some(k) = kind.and_then(|i| vectorcraft_geom::shapes::CornerKind::ALL.get(i)) { + super::set_picked_corners(app, &picked, json!({"kind": k})); } ui.end_row(); - dim_label(ui, tl!("Corner Radius:")); - super::corner_radius_field(app, ui, &n, ("props-corners", "radius"), fw); + super::corners_link(app, ui, "props-corners"); + let name = Some(tl!("Corner Radius:")); + if let Some(r) = widgets::num_field_named(ui, ("props-corners", "radius"), name, picked.radius, unit, fw) { + super::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } ui.end_row(); }); } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index bc41fef557..668bb97d2a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1548,14 +1548,14 @@ fn direct_selected_corners_show_their_kind_and_radius() { app.select_tool("directSelection"); app.run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); - assert!(shows(&texts, "Corner:") && shows(&texts, "Corner Radius:"), "{texts:?}"); + assert!(shows(&texts, "Corner:") && shows(&texts, "Corners"), "{texts:?}"); let corners = |app: &VectorcraftApp| { let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(star)).unwrap().clone(); let lc = LiveCorners::of(&n).unwrap(); (lc.radius(0), lc.radius(2), lc.kind(0), lc.kind(2)) }; - // The radius: the field right of its label. - let label = text_at(&texts, "Corner Radius:"); + // The radius: the field right of the Corners link. + let label = text_at(&texts, "Corners"); let field = texts.iter().find(|(t, r)| t == "0 pt" && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0).unwrap().1; press(&mut app, &ctx, field.center()); let depth = undo_depth(&app); @@ -1581,6 +1581,125 @@ fn direct_selected_corners_show_their_kind_and_radius() { let texts = tall(&mut app, &ctx, vec![]); assert_eq!(texts.iter().filter(|(t, _)| t == "Corner:").count(), 1, "{texts:?}"); assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}"); + // And the Corners link, for the pop-up's rounding: Relative on the picked corner's rectangle. + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. +fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { + let id = rect(app, x, 50.0, 100.0, 100.0); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + id.as_u64().unwrap() +} + +/// The radius and kind of each corner of path `id`, from the top-left clockwise. +fn path_corners(app: &VectorcraftApp, id: u64) -> Vec<(f64, vectorcraft_geom::shapes::CornerKind)> { + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let lc = LiveCorners::of(&n).unwrap(); + (0..4).map(|k| (lc.radius(k), lc.kind(k))).collect() +} + +/// Types `text` into the field under `at` and presses Enter → the texts of the frame after. +fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, text: &str) -> Vec<(String, Rect)> { + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + press(app, ctx, at); + tall(app, ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]); + tall(app, ctx, vec![Event::Text(text.into())]); + tall(app, ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]); + tall(app, ctx, vec![]) +} + +/// The Corners link opens a pop-up with the corner kind, the radius and the rounding of the +/// Direct-Selected corners. A radius typed there, or a kind or rounding picked, sets the three +/// picked corners and leaves the fourth as it is, each in one undo step. +#[test] +fn the_corners_link_opens_the_settings_of_the_picked_corners() { + let mut app = new_app(); + let id = square_path(&mut app, 50.0); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(!shows(&texts, "Relative") && !shows(&texts, "Chamfer"), "closed: {texts:?}"); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + for t in ["Inverted Round", "Chamfer", "Radius:", "Relative", "Absolute"] { + assert!(shows(&texts, t), "{t} in {texts:?}"); + } + // The radius field, right of its label in the pop-up. + let label = text_at(&texts, "Radius:"); + let field = texts.iter().find(|(t, r)| t == "0 pt" && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0).unwrap().1; + let depth = undo_depth(&app); + let texts = type_into(&mut app, &ctx, field.center(), "18"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let (round, chamfer) = (vectorcraft_geom::shapes::CornerKind::Round, vectorcraft_geom::shapes::CornerKind::Chamfer); + assert_eq!(path_corners(&app, id), vec![(18.0, round), (18.0, round), (18.0, round), (0.0, round)]); + // A kind, picked in the pop-up. + let texts = press(&mut app, &ctx, text_at(&texts, "Chamfer").center()); + assert_eq!(undo_depth(&app), depth + 2, "one undo step"); + assert_eq!(path_corners(&app, id), vec![(18.0, chamfer), (18.0, chamfer), (18.0, chamfer), (0.0, round)]); + // Relative rounding, for the path the corners are on. + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + assert_eq!(undo_depth(&app), depth + 3, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); +} + +/// With a corner of each of two paths Direct-Selected and their radii different, the pop-up's +/// radius is blank; a radius typed there sets both corners, and no other, in one undo step. +#[test] +fn the_corners_pop_up_sets_picked_corners_across_paths() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + app.run("select.anchors", json!({"id": b, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let label = text_at(&texts, "Radius:"); + // Blank: no value right of the label. + assert!(!texts.iter().any(|(t, r)| t.ends_with("pt") && r.left() > label.right() && (r.center().y - label.center().y).abs() < 6.0), "{texts:?}"); + let depth = undo_depth(&app); + type_into(&mut app, &ctx, egui::pos2(label.right() + 40.0, label.center().y), "7"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&app, a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&app, b), vec![(0.0, round), (7.0, round), (0.0, round), (0.0, round)]); +} + +/// With a corner of one path Direct-Selected and a second path selected whole, the pop-up picks +/// that corner and every corner of the second path. While one path is Relative and the other +/// Absolute, no rounding is chosen; picking Absolute sets both paths in one undo step. +#[test] +fn the_corners_pop_up_takes_every_corner_of_a_whole_path_and_mixed_rounding() { + let mut app = new_app(); + let (a, b) = (square_path(&mut app, 20.0), square_path(&mut app, 200.0)); + app.run("object.setLiveShape", json!({"ids": [a], "corners": [0], "radius": 5})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [a], "relativeRadii": true})).unwrap(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let picked = crate::panels::picked_corners(&app).unwrap(); + assert_eq!(picked.relative, None, "no rounding while the paths differ"); + assert_eq!(picked.items.len(), 2); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let depth = undo_depth(&app); + let texts = press(&mut app, &ctx, text_at(&texts, "Absolute").center()); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + assert_eq!(crate::panels::picked_corners(&app).unwrap().relative, Some(false), "both Absolute"); + let label = text_at(&texts, "Radius:"); + type_into(&mut app, &ctx, egui::pos2(label.right() + 40.0, label.center().y), "7"); + assert_eq!(undo_depth(&app), depth + 2, "one undo step"); + let round = vectorcraft_geom::shapes::CornerKind::Round; + assert_eq!(path_corners(&app, a), vec![(7.0, round), (0.0, round), (0.0, round), (0.0, round)]); + assert_eq!(path_corners(&app, b), vec![(7.0, round); 4], "every corner of the path selected whole"); } /// One effect on the one selected object shows its name and a Delete icon beside the fx button, diff --git a/crates/ui-egui/tests/control_bar_corners.rs b/crates/ui-egui/tests/control_bar_corners.rs index 7386e44a8c..2f7189efdc 100644 --- a/crates/ui-egui/tests/control_bar_corners.rs +++ b/crates/ui-egui/tests/control_bar_corners.rs @@ -127,7 +127,7 @@ fn corner_radius_existing_anchor_controls_and_properties_remain_available() { assert!(bar.has_text("Convert:") && bar.has_text("Anchors:"), "{:?}", bar.texts); assert!(bar.nodes.iter().any(|node| node.label() == Some("Remove Anchor Points"))); let properties = Frames::new(360.0, true).settled(&mut app); - assert!(properties.has_text("Corner Radius:"), "{:?}", properties.texts); + assert!(properties.has_text("Corners"), "{:?}", properties.texts); assert!(properties.texts.iter().any(|(text, _)| text == "0 pt")); } diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..a4b4a75882 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7682,8 +7682,8 @@ polygon's from its first vertex clockwise; a star's from its first tip; an index Each corner keeps its own radius and kind (the shape's `live` in queries has `radii` and, when a corner isn't round, `kinds`); a corner with no radius is one anchor, a cut one two, and Direct-Selected corners stay selected as that changes. A path that isn't a live shape keeps its uncut outline (`live` `{"shape": "path", "base", "radii"}`) so its -corners stay editable, and is a plain path again once no corner is cut; a polygon stays a live polygon, its corners -keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius +corners stay editable, and is a plain path again once no corner is cut, unless its rounding is Relative; a polygon +stays a live polygon, its corners keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform @@ -7702,6 +7702,17 @@ and those shape tools: hidden widgets are not drawn, and those tools do not answ on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. +In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with +Direct Selection, while a corner is selected) opens the Corners pop-up for the picked corners of every selected path: +the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors +hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the +rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the +paths differ). A path without Live Corners is Absolute, and Relative on a path with a corner keeps its outline as the +base of its Live Corners, as a radius does; ellipses and lines are left as they are. Editing a path's anchors (for +example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. With Relative rounding, a radius is +compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius +shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one +`object.setLiveShape` with `items`, one undo step, and the corners that were not picked keep their radius and kind. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"id":12,"corners":[1],"radius":16}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..bf9ca2c662 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1481,6 +1481,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules. Relative rounding also works on a plain path with corners (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_takes_on_a_plain_path`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..c0d8d424ff 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -490,6 +490,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | +| Control bar and Properties panel: Corners link and pop-up for the picked corners (part of #1232) | done | the link opens the corner kind, the radius (blank while the picked corners differ) and the Relative or Absolute rounding; each change sets the picked corners of every selected path in one `object.setLiveShape {items}`, one undo step | | Control bar: numeric Corner Radius for eligible selected ordinary and live corners (part of #7238, request 3 only) | done | Anchor Points visibility group; common/mixed values, general document units and multi-object edits through `object.setLiveShape`, one Undo. A partial selection containing no eligible corners contributes no target. Corner kind and relative mode are retained; existing corner-widget selection, widget visibility and maximum-radius behavior are unchanged. Requests 1/2 remain open. | | Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | From 4daef561c8d148f1a2237c43a9ea85c00741ec47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 05:30:30 -0800 Subject: [PATCH 04/49] Live Corners: a live rectangle or polygon selected whole shows the Corners link With Direct Selection, one live rectangle or live polygon selected whole now shows the Corners link in the Properties panel beside its own rows. Before, the panel showed the link only while an anchor of the shape was selected. The pop-up sets every corner of the shape. A path with Live Corners selected whole still shows no corner rows. --- crates/ui-egui/src/panels/properties.rs | 4 +-- crates/ui-egui/src/panels/properties/tests.rs | 32 +++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 0c2313c8f0..26b4729f8f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -211,7 +211,7 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { /// and the Corners link opens the corner settings /// (). One live /// rectangle or live polygon selected alone has its own kind and radius rows, which already set -/// the selected corners: it shows the Corners link alone. +/// the selected corners: it shows the Corners link alone, also while it is selected whole. fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.tool_id() != "directSelection" { return; @@ -223,7 +223,7 @@ fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { let corner_selected = st.selection.objects.iter().any(|id| { st.doc.node(*id).and_then(LiveCorners::of).is_some_and(|lc| st.selection.partial(*id).is_some_and(|a| !lc.corners_of(a).is_empty())) }); - if !corner_selected { + if !own_rows && !corner_selected { return; } let Some(picked) = super::picked_corners(app) else { return }; diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 668bb97d2a..8d2ef2973e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1588,6 +1588,38 @@ fn direct_selected_corners_show_their_kind_and_radius() { assert!(LiveCorners::of(&n).unwrap().radii_relative()); } +/// With Direct Selection, a live rectangle or live polygon selected whole keeps its own rows and +/// shows the Corners link, whose pop-up sets every corner of the shape. A path with Live Corners +/// selected whole shows no corner rows. +#[test] +fn a_whole_live_shape_with_direct_selection_shows_the_corners_link() { + let mut app = new_app(); + let ctx = egui::Context::default(); + app.select_tool("directSelection"); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + let polygon = app.run("shape.polygon", json!({"cx": 200, "cy": 150, "radius": 50, "sides": 5})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [polygon]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corners").count(), 1, "polygon: {texts:?}"); + app.run("select.set", json!({"ids": [r]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corners").count(), 1, "rectangle: {texts:?}"); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}"); + // The pop-up's rounding: Relative on the rectangle. + let texts = press(&mut app, &ctx, text_at(&texts, "Corners").center()); + let depth = undo_depth(&app); + press(&mut app, &ctx, text_at(&texts, "Relative").center()); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(LiveCorners::of(&n).unwrap().radii_relative()); + // A plain path selected whole: no corner selected. + let path = square_path(&mut app, 200.0); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [path]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(!shows(&texts, "Corner:") && !shows(&texts, "Corners"), "{texts:?}"); +} + /// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { let id = rect(app, x, 50.0, 100.0, 100.0); diff --git a/docs/mcp.md b/docs/mcp.md index a4b4a75882..e3f051ddc4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7703,7 +7703,7 @@ on them. `on`, when given and not `null`, must be `true` or `false` and sets the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with -Direct Selection, while a corner is selected) opens the Corners pop-up for the picked corners of every selected path: +Direct Selection, while a corner is selected or one live rectangle or polygon is selected) opens the Corners pop-up for the picked corners of every selected path: the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the From 073a654e6a3fce3f1b0cda098751f3b3b3ca2900 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:39:07 -0800 Subject: [PATCH 05/49] Packaging Tools: list Set Fold Angle's angle with the angles that are not turns The turn-direction test asks every angle param to say whether it turns clockwise or counter-clockwise. A fold angle folds a panel out of the page; the command's description says a positive angle folds it away from the printed side and a negative one toward it. The test now lists the param with the other angles that are not turns. --- crates/engine/src/tests/turn_direction.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), From 3768dd08291c5463400270ca7f64098102ed26cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:00:47 -0800 Subject: [PATCH 06/49] Packaging Tools: Set Fold Angle's OK changes the lines its dialog opened on The dialog keeps the lines it opened on as the command's ids, with the uid of their document. OK changes those lines even when the selection changes while the dialog is open, and changes nothing once another document is the active one. The split flap raster test now requires a flap at both samples: the right flap at both, or the left flap's inner part at the near sample and its outer part at the far one. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/addons.rs | 2 +- crates/engine/src/cmd/addons/packaging.rs | 2 +- .../engine/src/cmd/addons/packaging/angle.rs | 36 +++++++++++---- crates/three-d/src/fold/raster/tests.rs | 11 ++++- crates/ui-egui/src/addons/packaging.rs | 10 ++-- crates/ui-egui/src/addons/packaging/tests.rs | 46 +++++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 10 +++- 8 files changed, 100 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8622497c6a..c75e06c776 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -844,7 +844,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 32f8cfa645..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 779b044358..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -11,7 +11,7 @@ mod check; mod fold; mod roles; -pub use angle::{FoldAngles, selection_fold_angles}; +pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs index b458a3e410..f38645774f 100644 --- a/crates/engine/src/cmd/addons/packaging/angle.rs +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -216,23 +216,39 @@ pub fn selection_fold_angles(s: &Session) -> FoldAngles { } } +/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes +/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the +/// lines it changes. +pub fn selection_fold_lines(s: &Session) -> Vec { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(), + _ => Vec::new(), + } +} + /// The [`FoldAngles`] of the outermost objects `roots` of `d`. pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { - let table = RoleTable::of(d); - let editable = d.editable(); let mut f = FoldAngles::default(); - for n in role_targets(d, &editable_members(d, roots.to_vec()).0, false).0.iter().filter_map(|id| d.node(*id)) { - // The role first: whether an object can be edited can take its bounds to find out. - if let Some(role) = table.role_of(n) - && folds(role) - && editable(n.id) - { - f.add(n, role); - } + for (n, role) in changeable(d, roots) { + f.add(n, role); } f } +/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change, +/// with their roles, in order. +fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> { + let table = RoleTable::of(d); + let editable = d.editable(); + let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0; + // The role first: whether an object can be edited can take its bounds to find out. + targets + .iter() + .filter_map(|id| d.node(*id)) + .filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r))) + .collect() +} + impl FoldAngles { /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. pub(super) fn add(&mut self, n: &Node, role: Role) { diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index b6251985ca..014cf010d7 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -616,9 +616,16 @@ fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); // From the back the image is mirrored: x on the blank is 140 - x in the image. - let right_flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 90.0).abs() < 1e-6)).expect("the right flap"); + let starting_at = |x0: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x0).abs() < 1e-6)); + let right_flap = starting_at(90.0).expect("the right flap"); + // Folded back about x 30, the left flap's part from 15 to 30 lies at 30 to 45 and its part from + // 0 to 15 at 45 to 60. + let (inner, outer) = (starting_at(15.0).expect("the left flap's inner part"), starting_at(0.0).expect("its outer part")); let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); - assert_eq!(near == Some(right_flap), far == Some(right_flap), "{near:?} {far:?}"); + // Either flap may be in front, but the same one at both samples. + let right = (near, far) == (Some(right_flap), Some(right_flap)); + let left = (near, far) == (Some(inner), Some(outer)); + assert!(right || left, "{near:?} {far:?}: right flap {right_flap}, left flap {inner} and {outer}"); } #[test] diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index e43aed7ec8..01d038bd72 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -269,13 +269,17 @@ fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { } /// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle -/// the selected lines that it can change all fold at, else 90°. The command's reason while it -/// can't change any. +/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK +/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is +/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is +/// the active one. The command's reason while it can't change any. pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result { let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; (command.enabled)(&app.session)?; let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); - Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle })) + let ids: Vec = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect(); + let doc = app.session.active().map(|st| st.uid); + Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle, "__params": { "ids": ids }, "__doc": doc })) } /// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 4ee1334759..81d7338be3 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -324,6 +324,52 @@ fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(30.0)); } +/// Set Fold Angle…'s OK changes the lines the dialog opened on, even when the selection changes +/// while it is open (a remote command can change it): the other crease keeps its angle. +#[test] +fn set_fold_angle_s_ok_changes_the_lines_the_dialog_opened_on() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a, b]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("angle".into(), json!(30.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the dialog"); + let angle = |app: &mut VectorcraftApp, id: u64| { + app.run("select.set", json!({"ids": [id]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + }; + assert_eq!(angle(&mut app, a), Some(30.0), "the line the dialog opened on"); + assert_eq!(angle(&mut app, b), Some(90.0), "the line selected later keeps its role's angle"); +} + +/// Set Fold Angle…'s OK changes nothing once another document is the active one, even a line there +/// with the same id as the line the dialog opened on. +#[test] +fn set_fold_angle_s_ok_changes_nothing_in_another_document() { + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + assert!(app.ui.dialog.is_some(), "the dialog opens"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "the same id in the other document"); + app.run(SET_ROLE, json!({"role": "crease", "ids": [other]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("angle".into(), json!(30.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the dialog"); + let angle = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [a]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + }; + assert_eq!(angle(&mut app), Some(90.0), "the other document's line keeps its role's angle"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(angle(&mut app), Some(90.0), "the first document's line is left as it was"); +} + /// Set Fold Angle… keeps the angle typed into its dialog within -180° to 180°, so OK applies the /// nearest end instead of closing on an angle the command refuses. #[test] diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 16befd8f4b..cca99c9d6c 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -282,8 +282,16 @@ const FIRST_BASELINE: form::Choices = &[ const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; /// Closes before running, so a dialog the command opens stays open. A previewed one keeps its -/// preview as the one undo step. +/// preview as the one undo step. A dialog opened on one document's objects (`__doc`, its uid) +/// closes as Cancel does and runs nothing once another document is the active one, as Delete +/// Brush's question does (`brush_delete.rs`, `confirm`). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if let Some(doc) = d.fields.get("__doc") + && doc.as_u64() != app.session.active().map(|st| st.uid) + { + app.ui.dialog = None; + return Ok(json!({})); + } let (cmd, params) = call(d); if previews(d) { return form::commit_preview(app, &cmd, params); From 6209f84bcfa7a0bf9b9eb201c45dca6a01d4ebf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:03:49 -0800 Subject: [PATCH 07/49] Document Setup: the grid preview test edits the open dialog in one context The grid preview tests drew each edit in a new egui context, so they would pass if an open dialog kept drawing the old colors' texture. A new test draws one context through a color edit, a size edit and a preset edit, and checks the pixels of the texture the preview's mesh draws. --- crates/ui-egui/src/dialogs/document_setup.rs | 51 +++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 575603e926..a27e6cae40 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -1153,32 +1153,50 @@ mod tests { /// The grid preview Document Setup draws, in a fresh context: its rect, the texture /// coordinates of its bottom-right corner (two cells per unit) and the tile's four pixels. fn grid_preview(app: &mut VectorcraftApp) -> (Rect, egui::Vec2, Vec) { + grid_preview_in(app, &preview_context(), &mut Default::default()) + } + + /// A new context with the app's fonts and theme, for drawing the grid preview. + fn preview_context() -> egui::Context { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx, Default::default()); - let (mut mesh, mut pixels) = (None, None); + ctx + } + + /// The grid preview Document Setup draws in `ctx`: its rect, the texture coordinates of its + /// bottom-right corner (two cells per unit) and the four pixels of the texture its mesh draws. + /// `tiles` holds the pixels of each grid texture uploaded so far in `ctx`, so every frame drawn + /// in `ctx` goes through this function. + fn grid_preview_in( + app: &mut VectorcraftApp, + ctx: &egui::Context, + tiles: &mut std::collections::HashMap>, + ) -> (Rect, egui::Vec2, Vec) { + let mut mesh = None; for _ in 0..3 { let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); - let tiles: Vec = + let grids: Vec = ctx.tex_manager().read().allocated().filter(|(_, m)| m.name == crate::canvas::TRANSPARENCY_GRID).map(|(id, _)| *id).collect(); for (id, deltas) in &out.textures_delta.set { - if tiles.contains(id) + if grids.contains(id) && let Some(d) = deltas.last() { let egui::ImageData::Color(img) = &d.image; - pixels = Some(img.pixels.clone()); + tiles.insert(*id, img.pixels.clone()); } } out.textures_delta.clear(); mesh = out.shapes.iter().find_map(|c| match &c.shape { - egui::Shape::Mesh(m) if tiles.contains(&m.texture_id) => Some(m.clone()), + egui::Shape::Mesh(m) if grids.contains(&m.texture_id) => Some(m.clone()), _ => None, }); } let mesh = mesh.unwrap_or_else(|| panic!("no grid preview")); let uv = mesh.vertices.iter().fold(vec2(0.0, 0.0), |a, v| a.max(v.uv.to_vec2())); - (mesh.calc_bounds(), uv, pixels.unwrap_or_else(|| panic!("no tile"))) + let pixels = tiles.get(&mesh.texture_id).cloned().unwrap_or_else(|| panic!("no tile for {:?}", mesh.texture_id)); + (mesh.calc_bounds(), uv, pixels) } /// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells. @@ -1219,6 +1237,27 @@ mod tests { assert_eq!(undo_steps(&app), 0); } + /// In an open dialog, the preview follows each edit of Grid Colors and Grid Size: after a + /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. + #[test] + fn the_grid_preview_follows_edits_in_the_open_dialog() { + let (mut app, _) = transparency_tab(); + let (ctx, mut tiles) = (preview_context(), Default::default()); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!(["#ff0000", "#0000ff"])); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridSize".into(), json!("large")); + let (rect, uv, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("Dark")); + let (_, _, pixels) = grid_preview_in(&mut app, &ctx, &mut tiles); + assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); + } + /// The grid preview sits beside Grid Size, Grid Colors and the color boxes, inside the dialog, /// and covers none of the tab's text or color boxes. #[test] From c6bea78bdf2beca24e46c919c10c613488a42b76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:19 -0800 Subject: [PATCH 08/49] Shapes: Curvature Circle Tool Options set its reach, label, anchors and arc rule Double-clicking the Curvature Circle tool opens Curvature Circle Tool Options (`tool.options {tool: "curvatureCircle"}`, dialog `curvatureCircleOptions`). OK sets the options with `tool.setOption`, and the preferences keep them: - Snap Tolerance (`snapTolerance`, 1 to 40 screen points, 5) is how near a path pulls the pointer; Smart Guides' Snapping Tolerance applies when it is larger. - Snap with Smart Guides Off (`snapWithoutGuides`) unchecked keeps the reach within Selection & Anchor Display's Tolerance while Smart Guides are off. - Annotate Radius (`annotateRadius`) unchecked hides the radius label. - Anchors at Standard Positions (`standardAnchors`) unchecked draws a path with an anchor where the circle touches the path and one every 90 degrees from there (`shape.curvatureCircle {anchors: "touch"}`). - Use the Radius of Circular Arcs (`constantRadius`) unchecked gives the cubic's own curvature on the cubic of a circular arc too (`shape.curvatureCircle {constantRadius: false}`). The range, the default and the Snap with Smart Guides Off rule are VectorCraft's own. Every switch is on by default, so the tool draws as before until an option is changed. The canvas check measures the path drawn, whose cubics reach a little past the circle when its anchors are where it touches. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 27 +++- crates/engine/src/tests/curvature_circle.rs | 83 ++++++++++ crates/geom/src/curvature.rs | 28 +++- crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/curvature_circle.rs | 150 +++++++++++++++--- crates/tools/src/curvature_circle/tests.rs | 95 +++++++++++ crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/curvature_circle_options.rs | 143 +++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 6 +- docs/mcp.md | 27 +++- 13 files changed, 530 insertions(+), 38 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/curvature_circle_options.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..911a24f40e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -144,6 +144,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..90e04db1a6 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Curvature Circle", [], None, - "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + "{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", has_doc, curvature_circle ), @@ -518,7 +518,8 @@ fn selected_anchor_points(s: &Session) -> Result>> { } /// A live ellipse that touches a path at a point with the path's curvature there -/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor +/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is. fn curvature_circle(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.curvatureCircle"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -529,6 +530,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`t` must be from 0 to 1")); } let convex = switch_or(p, "convex", false, C)?; + let arcs = switch_or(p, "constantRadius", true, C)?; + let key = "anchors"; + let at_touch = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("touch")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))), + }; let found = { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -540,7 +548,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { if seg >= sp.segment_count() { return Err(bad(C, "no such segment")); } - curvature::curvature_circle_on(sp, seg, t, convex) + curvature::curvature_circle_on_with(sp, seg, t, convex, arcs) }; let circle = found.map_err(|e| match e { NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), @@ -549,12 +557,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { })?; let (center, radius) = (circle.center, circle.radius); let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + let (path, live) = if at_touch { + (shapes::circle_with_anchors_at(center, radius, &[circle.at]), None) + } else { + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + (live.to_path(), Some(live)) + }; + // The bounds of the path drawn: started where it touches, its cubics reach a little past the + // circle. + if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) { return Err(bad(C, "the circle that matches the path there would reach past the canvas")); } - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays on the path. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index e862a03aaf..a5eed3aed6 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -224,3 +224,86 @@ fn the_next_click_passes_over_the_circle_the_tool_drew() { let third = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); } + +/// The anchors of `id`'s path. +fn anchors_of(s: &Session, id: NodeId) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect() +} + +/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path; +/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle +/// is; anything else is an error that draws nothing. +#[test] +fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap(); + let id = id_of(&v); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}"); + let anchors = anchors_of(&s, id); + assert_eq!(anchors.len(), 4); + assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}"); + assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0))); + + let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap()); + let upright = anchors_of(&s, upright); + s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap(); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(anchors_of(&s, id_of(&v)), upright); + + let count = object_count(&s); + for bad in [json!("points"), json!(4), json!(true)] { + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err()); + } + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err()); + assert_eq!(object_count(&s), count); +} + +/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the +/// circle with standard anchors, or with its anchors where it touches at a standard position, fits, +/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge. +#[test] +fn the_canvas_check_measures_the_path_drawn() { + let mut s = session(); + let edge = vectorcraft_doc::MAX_COORD - 0.05; + let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap(); + let path = id_of(&v); + let count = object_count(&s); + let near_right = json!({"id": path.0, "segment": 1, "t": 0.79}); + assert!(s.execute(C, &near_right).is_ok()); + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok()); + let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err(); + assert!(e.to_string().contains("past the canvas"), "{e}"); + assert_eq!(object_count(&s), count + 2); +} + +/// The tool's options are saved with the preferences and come back in the next session. +#[test] +fn the_tool_options_are_saved_with_the_preferences() { + let mut s = session(); + s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + let changed = + json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false}); + for (k, v) in changed.as_object().unwrap() { + s.set_tool_option(k, v); + } + s.select_tool("selection", ViewInfo::default()).unwrap(); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + assert_eq!(next.tool_options(), changed); +} + +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, larger than +/// the circle's at an anchor, and the result is not nominal. +#[test] +fn without_constant_radius_an_arc_gives_its_own_curvature() { + let mut s = session(); + let path = circle(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap(); + assert_eq!(v["nominal"], json!(false)); + assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}"); +} diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 304f20557e..eec3a72876 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; /// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to /// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + curvature_circle_with(c, t, convex, true) +} + +/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a +/// circular arc too. +pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result { let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); if !finite || !(0.0..=1.0).contains(&t) { return Err(NoCircle::Cusp); } let at = c.eval(t); - let (center, radius, nominal) = match circular_arc(c) { + let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) { Some((center, radius)) => { let out = at - center; let len = out.hypot(); @@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result Result { + curvature_circle_on_with(sp, seg, t, convex, true) +} + +/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`. +pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result { let n = sp.segment_count(); if seg >= n { return Err(NoCircle::Cusp); @@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re if corner { return Err(NoCircle::Corner); } - curvature_circle(c, t, convex) + curvature_circle_with(c, t, convex, arcs) } /// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether @@ -260,6 +271,19 @@ mod tests { } } + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is larger + /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. + #[test] + fn without_arcs_a_circle_segment_gives_its_own_curvature() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let sp = &pd.subpaths[0]; + let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap(); + let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap(); + assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}"); + assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}"); + assert_eq!(own.at, sp.segment(0).eval(0.0)); + } + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..f29ad291ce 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1175,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index b484651181..2df7ef0a48 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -13,21 +13,34 @@ //! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws //! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an //! edit, Undo or Redo is made outside the tool. +//! +//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the +//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); +//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › +//! Tolerance while Smart Guides are off; `annotateRadius` off hides the radius label; +//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every +//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off +//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every +//! switch is on by default. use std::collections::HashSet; -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::{MAX_COORD, NodeId}; -use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with}; +use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes}; +use crate::option_check; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub const ID: &str = "curvatureCircle"; -/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance -/// is larger. -const SNAP_PX: f64 = 5.0; +/// The range of `snapTolerance` (screen points). +pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0); +/// `snapTolerance` by default (screen points). +pub const DEFAULT_SNAP: f64 = 5.0; +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]; /// How far (screen points) the pointer travels from a press before the press counts as a drag. const DRAG_PX: f64 = 2.0; /// Half the length (screen points) of each arm of the cross at the circle's center. @@ -51,8 +64,37 @@ enum Found { Refused(&'static str, Point), } +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Options { + snap_tolerance: f64, + snap_without_guides: bool, + annotate_radius: bool, + standard_anchors: bool, + constant_radius: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "snapWithoutGuides" => &mut self.snap_without_guides, + "annotateRadius" => &mut self.annotate_radius, + "standardAnchors" => &mut self.standard_anchors, + "constantRadius" => &mut self.constant_radius, + _ => return None, + }) + } +} + #[derive(Default)] pub struct CurvatureCircleTool { + options: Options, /// The point under the pointer, and whether Shift was held. hover: Option<(Hit, bool)>, /// The press in progress, where the pointer was pressed: what a release draws. @@ -62,10 +104,20 @@ pub struct CurvatureCircleTool { drawn: HashSet, } -/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides › +/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no +/// further than Selection & Anchor Display › Tolerance. +fn reach(cx: &ToolContext, o: &Options) -> f64 { + let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol()); + if !cx.smart_guides && !o.snap_without_guides { + return snap.min(cx.pick_tol()); + } + snap +} + +/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. -fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { - let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); +fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet) -> Option { let mut best: Option<(Hit, f64)> = None; for id in crate::draw2::candidate_paths(cx) { if skip.contains(&id) { @@ -88,14 +140,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { /// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the /// path or segment is gone. -fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { +fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option { let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; if hit.segment >= sp.segment_count() { return None; } let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); - Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { - Ok(c) if on_canvas(&c) => Found::Circle(c), + Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) { + Ok(c) if on_canvas(&c, o) => Found::Circle(c), Ok(_) => Found::Refused("Circle too large", at), Err(NoCircle::Straight) => Found::Refused("Straight segment", at), Err(NoCircle::Cusp) => Found::Refused("Cusp", at), @@ -103,10 +155,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { }) } -/// Does the circle stay on the canvas? -fn on_canvas(c: &CurvatureCircle) -> bool { +/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors +/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path. +fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData { let (p, r) = (c.center, c.radius); - [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) + if !o.standard_anchors { + return shapes::circle_with_anchors_at(p, r, &[c.at]); + } + shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r)) +} + +/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it? +fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool { + drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) } impl Tool for CurvatureCircleTool { @@ -118,13 +179,14 @@ impl Tool for CurvatureCircleTool { if !ev.pos.is_finite() { return vec![]; } + let (o, tol) = (self.options, reach(cx, &self.options)); match ev.kind { PointerKind::Move => { - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); vec![] } PointerKind::Down => { - self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); self.hover = self.press; self.from = ev.pos; vec![] @@ -139,12 +201,21 @@ impl Tool for CurvatureCircleTool { } PointerKind::Up => { let press = self.press.take(); - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); let Some((hit, convex)) = press else { return vec![] }; - if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) { return vec![]; } - let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + let anchors = if o.standard_anchors { "standard" } else { "touch" }; + let p = json!({ + "id": hit.id.0, + "subpath": hit.subpath, + "segment": hit.segment, + "t": hit.t, + "convex": convex, + "constantRadius": o.constant_radius, + "anchors": anchors, + }); vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -210,10 +281,10 @@ impl Tool for CurvatureCircleTool { let Some((hit, convex)) = self.hover else { return vec![] }; let color = crate::draw2::FEEDBACK; let mut o = vec![]; - match found(cx, hit, convex) { + match found(cx, hit, convex, &self.options) { Some(Found::Circle(c)) => { let r = c.radius; - let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + let path = drawn_path(&c, &self.options).to_bezpath(); // The outline is drawn solid when it is longer than DASHED_PX on screen. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); @@ -222,7 +293,7 @@ impl Tool for CurvatureCircleTool { o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); - if cx.measurement_labels { + if cx.measurement_labels && self.options.annotate_radius { let star = if c.nominal { "*" } else { "" }; o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); } @@ -236,6 +307,39 @@ impl Tool for CurvatureCircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + json!({ + "snapTolerance": o.snap_tolerance, + "snapWithoutGuides": o.snap_without_guides, + "annotateRadius": o.annotate_radius, + "standardAnchors": o.standard_anchors, + "constantRadius": o.constant_radius, + }) + } + + /// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "snapTolerance" { + option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1) + } else if SWITCHES.contains(&key) { + option_check::boolean(key, value) + } else { + Err(option_check::unknown(key)) + } + } + + /// Sets one option; a value the option does not take leaves it as it was. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "snapTolerance" { + if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) { + self.options.snap_tolerance = v; + } + } else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) { + *switch = on; + } + } } #[cfg(test)] diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index d417af58dc..81c88cc4d0 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -284,3 +284,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() { let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); assert_eq!(ids.get(circle + 1), Some(&ID)); } + +/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart +/// Guides off the pointer reaches no further than the selection tolerance, and never further than +/// with the switch on; with Smart Guides on it reaches as far as before. +#[test] +fn the_snap_options_set_how_far_the_pointer_reaches() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]); + t.set_option("snapTolerance", &json!(10)); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2); + t.set_option("snapTolerance", &json!(5)); + t.set_option("snapWithoutGuides", &json!(false)); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2); + let guides = ToolContext { smart_guides: true, ..cx }; + assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2); + let wide = ToolContext { selection_tolerance: 8.0, ..cx }; + assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2); + assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]); +} + +/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius +/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends +/// `anchors: "touch"`. +#[test] +fn the_label_and_circle_options_change_what_is_shown_and_drawn() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let measure = |t: &CurvatureCircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard"))); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + assert!(measure(&t).is_some_and(|m| m.ends_with('*'))); + t.set_option("annotateRadius", &json!(false)); + assert_eq!(measure(&t), None); + t.set_option("annotateRadius", &json!(true)); + let arc = preview(&t.overlays(&cx)).unwrap(); + t.set_option("constantRadius", &json!(false)); + assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t)); + assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width()); + t.set_option("standardAnchors", &json!(false)); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch"))); +} + +/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle, +/// or with `standardAnchors` off starting where the circle touches the path. +#[test] +fn the_preview_follows_the_anchor_options() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let start = |t: &CurvatureCircleTool, cx: &ToolContext| { + t.overlays(cx).iter().find_map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default())); + let upright = start(&t, &cx).unwrap(); + let turned = ToolContext { constrain_angle: 30.0, ..cx }; + assert_eq!(start(&t, &turned), Some(upright)); + assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}"); + t.set_option("standardAnchors", &json!(false)); + let at = start(&t, &cx).unwrap(); + assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}"); +} + +/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are +/// errors, and `set_option` leaves the option as it was for them. +#[test] +fn invalid_options_are_refused() { + let mut t = CurvatureCircleTool::default(); + assert!(t.check_option("snapTolerance", &json!(0)).is_err()); + assert!(t.check_option("snapTolerance", &json!(41)).is_err()); + assert!(t.check_option("snapTolerance", &json!("5")).is_err()); + assert!(t.check_option("annotateRadius", &json!(1)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok()); + let before = t.options(); + t.set_option("snapTolerance", &json!(0)); + t.set_option("annotateRadius", &json!("no")); + assert_eq!(t.options(), before); +} diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..1086dd07aa 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -80,6 +80,8 @@ const ROWS: &[Row] = &[ (&["ellipse"], None, &["anchors"]), // Circle Tool Options (`circle::CircleTool`). (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), + // Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`). + (&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..a50bb4a46d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -34,6 +34,7 @@ mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod curvature_circle_options; pub mod custom_dictionary; pub mod dimension; mod document_setup; @@ -478,6 +479,7 @@ registry! { ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, CircleOptions: [circle_options::KIND] => circle_options::SPEC, + CurvatureCircleOptions: [curvature_circle_options::KIND] => curvature_circle_options::SPEC, ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/curvature_circle_options.rs b/crates/ui-egui/src/dialogs/curvature_circle_options.rs new file mode 100644 index 0000000000..3af2882b7f --- /dev/null +++ b/crates/ui-egui/src/dialogs/curvature_circle_options.rs @@ -0,0 +1,143 @@ +//! Curvature Circle Tool Options (double-click the Curvature Circle tool, or `tool.options`): Snap +//! Tolerance is how near, in screen points, a path pulls the pointer (Smart Guides' Snapping +//! Tolerance applies when it is larger); with Snap with Smart Guides Off unchecked, the pointer +//! reaches no further than the selection tolerance while Smart Guides are off; Annotate Radius +//! off hides the radius label; Anchors at Standard Positions off gives the circle an anchor where +//! it touches the path and one every 90° from there; Use the Radius of Circular Arcs off gives the +//! curve's own curvature on the curve of a circular arc too. OK sets them with +//! `tool.setOption {tool: "curvatureCircle", values}`; they last across tool switches and are saved +//! with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::curvature_circle::{DEFAULT_SNAP, ID as TOOL, SNAP_RANGE}; + +use super::{DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Curvature Circle Tool Options. +pub const KIND: &str = "curvatureCircleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// The switches the dialog edits, in the order it shows them, with their labels. +const SWITCHES: [(&str, &str); 4] = [ + ("snapWithoutGuides", "Snap with Smart Guides Off"), + ("annotateRadius", "Annotate Radius"), + ("standardAnchors", "Anchors at Standard Positions"), + ("constantRadius", "Use the Radius of Circular Arcs"), +]; + +/// Width of the label column. +const LABEL_W: f32 = 100.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// The option keys the dialog edits. +fn keys() -> impl Iterator { + ["snapTolerance"].into_iter().chain(SWITCHES.iter().map(|(key, _)| *key)) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let fields: Map = keys().filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let (min, max) = SNAP_RANGE; + let v = d.f64("snapTolerance", DEFAULT_SNAP); + widgets::label_row(ui, tl!("Snap Tolerance:"), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, "curvature-circle-snap", v, min..=max, "px", 1, 72.0) { + d.fields.insert("snapTolerance".into(), json!(x)); + } + }); + ui.add_space(6.0); + for (key, label) in SWITCHES { + form::check(ui, d, key, tl!(label)); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let values: Map = keys().filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Curvature Circle Tool Options", + "Snap Tolerance:", + "Snap with Smart Guides Off", + "Annotate Radius", + "Anchors at Standard Positions", + "Use the Radius of Circular Arcs", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for (key, _) in SWITCHES { + assert!(d.bool(key), "{key}"); + } + let before = d.f64("snapTolerance", 0.0); + d.fields.insert("snapTolerance".into(), json!(before + 3.0)); + for key in ["annotateRadius", "standardAnchors"] { + d.fields.insert(key.into(), json!(false)); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + assert_eq!(o["snapTolerance"], json!(before + 3.0)); + assert_eq!((&o["annotateRadius"], &o["standardAnchors"], &o["constantRadius"]), (&json!(false), &json!(false), &json!(true))); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("snapWithoutGuides")); + assert_eq!(d.f64("snapTolerance", 0.0), before + 3.0); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for values in [ + json!({"annotateRadius": false, "constantRadius": "no"}), + json!({"annotateRadius": false, "snapTolerance": 0}), + json!({"annotateRadius": false, "size": 3}), + ] { + assert!(app.run("tool.setOption", json!({"tool": TOOL, "values": values})).is_err(), "{values}"); + assert_eq!(app.session.tool_options_of(TOOL)["annotateRadius"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..6818e6ed5a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1176,7 +1176,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a4846cd35b..51a038b376 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -438,7 +438,8 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]), the Circle tool's ([`crate::dialogs::circle_options::open`]) and the +/// Curvature Circle tool's ([`crate::dialogs::curvature_circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -479,6 +480,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(crate::dialogs::circle_options::open(app)), + // The Curvature Circle tool: how near a path pulls the pointer, the radius label, where + // the circle's anchors go and whether a circular arc gives its own radius. + vectorcraft_tools::curvature_circle::ID => Ok(crate::dialogs::curvature_circle_options::open(app)), // The Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..2b4d76f339 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7238,13 +7238,18 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog ## Curvature circle -`shape.curvatureCircle {id, subpath?, segment, t, convex?}` draws the circle that touches path `id` at `t` (0 to 1) on -segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there (its circle of curvature), +`shape.curvatureCircle {id, subpath?, segment, t, convex?, constantRadius?, anchors?}` draws the circle that touches +path `id` at `t` (0 to 1) on segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there +(its circle of curvature), as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with `convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a -circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. The -result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. +circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. With +`constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at `t` instead. The +circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` +(`"standard"` when left out) the circle is a plain path with an anchor where it touches the path and one every 90° from +there. The result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes +the circle. The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle @@ -7264,6 +7269,20 @@ anchor, or where the circle would reach past the canvas, the pointer shows "Stra "Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until another tool is chosen or an edit, Undo or Redo is made outside the tool. +Curvature Circle Tool Options (`tool.options {tool: "curvatureCircle"}`, or a double-click on the tool, dialog +`curvatureCircleOptions`) sets the tool's options, which `tool.setOption {tool: "curvatureCircle", values}` also sets +and the preferences keep. The range, the default and the rule for Snap with Smart Guides Off are VectorCraft's own. +Every switch is on by default, and the tool draws as it did before the options existed until one is changed: + +- `snapTolerance` (Snap Tolerance, 1 to 40 screen points, 5 by default) is how near a path pulls the pointer. Smart + Guides › Snapping Tolerance applies when it is larger. +- `snapWithoutGuides` (Snap with Smart Guides Off) off makes the pointer reach no further than Selection & Anchor + Display › Tolerance while Smart Guides are off. +- `annotateRadius` (Annotate Radius) off hides the radius label. The label also needs Measurement Labels on. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "touch"`. +- `constantRadius` (Use the Radius of Circular Arcs) off draws with `constantRadius: false`, and the label has no + asterisk. + ```json {"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} ``` From c7eadb9656c547afbbae16ba797e284a69e5b05c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:08:47 -0800 Subject: [PATCH 09/49] Shapes: Curvature Circle docs say when Snap with Smart Guides Off has no effect docs/mcp.md and the tool's module comment say that unchecking Snap with Smart Guides Off does not change the reach when Selection & Anchor Display's Tolerance is as large as it. Two test comments now say the cubic's own curvature at the end of a quarter circle is smaller than the circle's, as their assertions check. --- crates/engine/src/tests/curvature_circle.rs | 4 ++-- crates/geom/src/curvature.rs | 2 +- crates/tools/src/curvature_circle.rs | 3 ++- docs/mcp.md | 21 ++++++++++----------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index a5eed3aed6..6290cb853f 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -297,8 +297,8 @@ fn the_tool_options_are_saved_with_the_preferences() { assert_eq!(next.tool_options(), changed); } -/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, larger than -/// the circle's at an anchor, and the result is not nominal. +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than +/// the circle's at an anchor, so a larger radius, and the result is not nominal. #[test] fn without_constant_radius_an_arc_gives_its_own_curvature() { let mut s = session(); diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index eec3a72876..aea7afde1d 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -271,7 +271,7 @@ mod tests { } } - /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is larger + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. #[test] fn without_arcs_a_circle_segment_gives_its_own_curvature() { diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index 2df7ef0a48..6d68f65a7d 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -17,7 +17,8 @@ //! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the //! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); //! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › -//! Tolerance while Smart Guides are off; `annotateRadius` off hides the radius label; +//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach +//! stays the same); `annotateRadius` off hides the radius label; //! `standardAnchors` off draws the circle with an anchor where it touches the path and one every //! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off //! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every diff --git a/docs/mcp.md b/docs/mcp.md index 2b4d76f339..e543ef72c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7240,16 +7240,14 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog `shape.curvatureCircle {id, subpath?, segment, t, convex?, constantRadius?, anchors?}` draws the circle that touches path `id` at `t` (0 to 1) on segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there -(its circle of curvature), -as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with -`convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two -ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a -circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. With -`constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at `t` instead. The -circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` -(`"standard"` when left out) the circle is a plain path with an anchor where it touches the path and one every 90° from -there. The result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes -the circle. +(its circle of curvature), as a live ellipse with the current paint, and selects it. The circle goes on the side the +path bends toward; with `convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc +of 90° or less (its two ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for +an arc of θ) gives a circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the +circle itself. With `constantRadius: false` (true when left out), such a segment gives the cubic's own curvature at +`t` instead. The circle's four anchors are at 0°, 90°, 180° and 270°; with `anchors: "touch"` (`"standard"` when left +out) the circle is a plain path with an anchor where it touches the path and one every 90° from there. The result is +`{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle @@ -7277,7 +7275,8 @@ Every switch is on by default, and the tool draws as it did before the options e - `snapTolerance` (Snap Tolerance, 1 to 40 screen points, 5 by default) is how near a path pulls the pointer. Smart Guides › Snapping Tolerance applies when it is larger. - `snapWithoutGuides` (Snap with Smart Guides Off) off makes the pointer reach no further than Selection & Anchor - Display › Tolerance while Smart Guides are off. + Display › Tolerance while Smart Guides are off. When that tolerance is as large as the reach above, turning the + switch off does not change the reach. - `annotateRadius` (Annotate Radius) off hides the radius label. The label also needs Measurement Labels on. - `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "touch"`. - `constantRadius` (Use the Radius of Circular Arcs) off draws with `constantRadius: false`, and the label has no From fdca4a75f53a564c56ef8bc72cc47fb7995d4614 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:39:25 -0800 Subject: [PATCH 10/49] Live Corners: scrubbing the Properties panel's Corner Radius updates the corners as it moves The field applies each value of the gesture through an undo scope, as the Corners pop-up's Radius field does, so a scrub is one undo step. --- .../src/panels/properties/transform_section.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/transform_section.rs b/crates/ui-egui/src/panels/properties/transform_section.rs index 97d0e14942..86189395b7 100644 --- a/crates/ui-egui/src/panels/properties/transform_section.rs +++ b/crates/ui-egui/src/panels/properties/transform_section.rs @@ -18,6 +18,7 @@ use serde_json::json; use vectorcraft_doc::{LiveCorners, LiveShape, NodeKind}; use crate::VectorcraftApp; +use crate::edits::{EditPath, apply_edits}; use crate::panels::{self, first_selected, transform}; /// The Transform section for the selection: its position and size about the reference point, the @@ -112,17 +113,21 @@ pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { panels::set_picked_corners(app, &picked, json!({"kind": kind})); } let lengths = crate::canvas::general_lengths(app); - let mut typed = None; + let mut edit = None; Field::new(tl!("Corner Radius")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - typed = - NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit.events.committed().copied().flatten(); + edit = Some(NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit); panels::corners_link(app, ui); }); }); - // A negative radius typed in rounds nothing: the command takes 0 or more. - if let Some(r) = typed { - panels::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + if let Some(edit) = edit { + // Every value of a scrub sets the corners; the gesture is one undo step. + apply_edits(app, &edit, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + panels::set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); } } From b081fd0e0d1e1c0447d8a68f883e7aad9968623f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:23:34 -0800 Subject: [PATCH 11/49] Live Corners: the Corner Radius fields show a relative radius as a length A live rectangle or polygon with Relative rounding showed the fraction it stores in its Corner Radius fields, while the Corners pop-up showed the length. The fields now show the length, which object.setLiveShape takes. --- crates/ui-egui/src/panels.rs | 22 ++++++++++++++----- crates/ui-egui/src/panels/properties/tests.rs | 16 ++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 890dc7443b..260e460bef 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -103,10 +103,22 @@ pub(crate) fn corner_radius(app: &VectorcraftApp, n: &Node) -> Option { corner_style(app, n).0 } -/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. +/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. The +/// radius is a document length ([`corner_length`]). pub(crate) fn corner_style(app: &VectorcraftApp, n: &Node) -> (Option, Option) { let partial = app.session.active().and_then(|d| d.selection.partial(n.id)); - LiveCorners::of(n).map_or((None, None), |c| c.style(&c.picked(partial))) + let Some(c) = LiveCorners::of(n) else { return (None, None) }; + let corners = c.picked(partial); + let mut radii = corners.iter().map(|k| corner_length(&c, *k)); + let radius = radii.next().filter(|first| radii.all(|r| (r - first).abs() < 1e-9)); + (radius, c.style(&corners).1) +} + +/// The radius asked for at corner `k`, as a document length, even where it draws smaller. A +/// relative radius is stored as a fraction of the corner's largest; the fields and +/// `object.setLiveShape` take lengths. +pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 { + if c.radii_relative() { c.radius(k) * c.corner(k).map_or(0.0, |c| c.max_radius()) } else { c.radius(k) } } /// One entry per corner kind, labelled as the Corners dialog labels them. @@ -214,7 +226,7 @@ fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { for (k, label, corner) in rectangle_corners() { Field::new(label).show(ui, |ui, _| { Row::new().wrap(true).show(ui, |ui, _| { - radii.push((k, NumberField::length(label, Bind::given(Some(lc.radius(k))), lengths).show(ui).edit)); + radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit)); if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) { kinds.push((k, kind)); } @@ -304,9 +316,7 @@ pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option { continue; } for &k in &corners { - // The radius asked for, even where it draws smaller. A relative radius is stored as a - // fraction of the corner's largest; the field and `object.setLiveShape` take lengths. - radii.push(if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }); + radii.push(corner_length(&lc, k)); kinds.push(lc.kind(k)); } relative.push(lc.radii_relative()); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 6eb2df684d..ea8e28b8bc 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1078,6 +1078,22 @@ fn a_whole_live_shape_with_direct_selection_shows_the_corners_link() { assert!(!panel.shows("Corner") && !panel.shows("Corners")); } +/// A live rectangle with Relative rounding shows its radius as a document length in its Corner +/// Radius field, as the Corners pop-up does, not as the fraction it stores. +#[test] +fn a_relative_live_rectangle_shows_its_radius_as_a_length() { + let mut app = new_app(); + let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "radius": 10})).unwrap(); + app.run("object.setLiveShape", json!({"ids": [r], "relativeRadii": true})).unwrap(); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(r)).unwrap().clone(); + assert!(vectorcraft_doc::LiveCorners::of(&n).unwrap().radii_relative()); + let shown = crate::panels::corner_radius(&app, &n).unwrap(); + assert!((shown - 10.0).abs() < 1e-6, "the field shows {shown}"); + assert_eq!(crate::panels::picked_corners(&app).unwrap().radius.map(|r| (r - 10.0).abs() < 1e-6), Some(true), "as the pop-up does"); +} + /// A square path, not a live shape, its top-left corner at (`x`, 50) → its id. fn square_path(app: &mut VectorcraftApp, x: f64) -> u64 { let id = rect(app, x, 50.0, 100.0, 100.0); From 9860ca3d6ee7cfb899e14af342eb655821c69926 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:46:36 -0800 Subject: [PATCH 12/49] Docs: Curvature Circle overview names the configured snap reach The tool overview in docs/mcp.md said the pointer snaps within 5 screen points. It now names the tool's Snap Tolerance (5 by default) and the limit that Snap with Smart Guides Off sets while Smart Guides are off, as the options section below describes. --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index e7476d4332..6420f4d9e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7509,8 +7509,10 @@ marked smooth), when the circle would reach past the canvas (4,000,000 pt from t origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The -pointer snaps to the nearest path that is not a guide within 5 screen points, or within Smart Guides › Snapping -Tolerance when that is larger, and the tool shows the circle that matches the path there as a dashed outline (solid +pointer snaps to the nearest path that is not a guide within the tool's Snap Tolerance (`snapTolerance` below, 5 +screen points by default), or within Smart Guides › Snapping Tolerance when that is larger; with Snap with Smart +Guides Off turned off, the reach while Smart Guides are off is no more than Selection & Anchor Display › Tolerance. +The tool shows the circle that matches the path there as a dashed outline (solid once it is more than 50,000 screen points around), a small cross at its center, a line from the center to the point it touches and, with Measurement Labels on, its radius by the pointer, followed by an asterisk for an arc's own radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; From 281cee4379b40aa86f37b451d259353754d37792 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:21:19 -0800 Subject: [PATCH 13/49] Live Corners: the Corners pop-up applies its radius after the Stack The pop-up's Radius edits are now collected inside the Stack and applied after it, as the kind and rounding radios already are. relativeRadii no longer turns a plain path into a Live Corners path here; that change goes to its own pull request. relativeRadii on a plain path, an ellipse or a line leaves it as it is and adds no undo step. --- crates/doc/src/corners.rs | 7 +++--- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 27 +++++------------------- crates/engine/src/tests/livecorners.rs | 25 +++++----------------- crates/ui-egui/src/panels.rs | 19 ++++++++++------- docs/mcp.md | 10 ++++----- docs/target-app-parity.md | 2 +- 7 files changed, 31 insertions(+), 61 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 3810bbb1f5..24228604a6 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -205,8 +205,8 @@ impl<'a> LiveCorners<'a> { /// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of /// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again. /// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a -/// plain path again once no corner is cut, unless its rounding is Relative. Ellipses and lines -/// have no corners: they stay as they are. +/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they +/// are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { fn edit( base: &PathData, @@ -268,8 +268,7 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, } match live.as_deref_mut() { - // A path with Relative rounding keeps its record, and with it the rounding. - Some(LiveShape::Path { base, radii, kinds, radii_relative: false }) if radii.is_empty() && kinds.is_empty() => { + Some(LiveShape::Path { base, radii, kinds, .. }) if radii.is_empty() && kinds.is_empty() => { *path = std::mem::take(base); *live = None; } diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 7a03abfb48..b675061f6b 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole path: a live rectangle, a live polygon or any path with a corner, which keeps its outline as the base of its Live Corners; a path without Live Corners is Absolute, and a path whose anchors are edited loses its Live Corners and is Absolute again; ellipses and lines are left as they are), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut, unless its rounding is Relative; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index 24274782d8..12a92b9193 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,15 +99,10 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } -/// Whether `relativeRadii` applies to a path drawn as `path` with live shape `live`: a live -/// rectangle, a live polygon, a path with Live Corners, or a plain path with a corner. A plain -/// path's rounding is Absolute. -fn takes_rounding(path: &PathData, live: Option<&LiveShape>) -> bool { - match live { - Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }) => true, - Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => false, - None => LiveCorners::new(path, None).is_some_and(|c| !c.all().is_empty()), - } +/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live +/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. +fn takes_rounding(live: Option<&LiveShape>) -> bool { + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) } /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about @@ -288,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| takes_rounding(path, live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { + if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -366,23 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *l = new.clone(); *path = l.to_path(); } - // A path with corners and no Live Corners yet keeps its outline as their base, so that - // Relative rounding has a record to go in. - if relative_radii == Some(true) && live.is_none() && takes_rounding(path, None) { - *live = Some(Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![], radii_relative: false })); - } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { convert_radii_relative(l, on); *path = l.to_path(); - // Absolute with no corner cut: a plain path again, as `set_corners` leaves one. - if let LiveShape::Path { radii, kinds, radii_relative: false, .. } = l - && radii.is_empty() - && kinds.is_empty() - { - *live = None; - } } if radius.is_none() && kind.is_none() { continue; diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 479c599124..4641467aa4 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,12 +910,10 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } -/// Relative rounding on a path with corners and no Live Corners yet takes effect in one undo step, -/// a radius set afterwards is stored as a fraction, and the rounding stays when no corner is cut -/// any more. Absolute, which such a path already has, and Relative on an ellipse, which has no -/// corners, add no undo step. +/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them +/// as they are and adds no undo step. #[test] -fn relative_rounding_takes_on_a_plain_path() { +fn relative_rounding_without_live_corners_adds_no_undo_step() { let (mut s, id) = session(); s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); s.execute("object.expandShape", &json!({})).unwrap(); @@ -923,22 +921,9 @@ fn relative_rounding_takes_on_a_plain_path() { let steps = |s: &Session| s.doc().unwrap().history.undo.len(); let n = steps(&s); run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); - assert_eq!(steps(&s), n, "Absolute: no change"); run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); - assert_eq!(steps(&s), n + 1, "Relative: one undo step"); - let node = s.doc().unwrap().doc.node(id).unwrap(); - assert!(LiveCorners::of(node).unwrap().radii_relative()); - let max = LiveCorners::of(node).unwrap().corner(0).unwrap().max_radius(); - run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": max / 2.0})); - let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); - assert!(c.radii_relative() && (c.radius(0) - 0.5).abs() < 1e-9, "stored fraction: {}", c.radius(0)); - // With no corner cut again, the path keeps its Relative rounding. - run(&mut s, json!({"ids": [id.0], "corners": [0], "radius": 0})); - let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); - assert!(c.radii_relative() && c.radius(0) == 0.0, "still Relative"); - // Absolute again with no corner cut: a plain path again. - run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); - assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path again"); + assert_eq!(steps(&s), n, "a plain path: no change"); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path"); let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); let n = steps(&s); run(&mut s, json!({"ids": [e], "relativeRadii": true})); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 132925e362..fb19b8195a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -356,7 +356,7 @@ pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui) { fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(picked) = picked_corners(app) else { return }; let lengths = general_lengths(app); - let mut set = None; + let (mut set, mut radius) = (None, None); Stack::new().show(ui, |ui, _| { Field::new(tl!("Corner")).show(ui, |ui, _| { let group = RadioGroup::new(tl!("Corner"), Bind::given(picked.kind)).show(ui, |ui, _| { @@ -371,13 +371,7 @@ fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { } }); Field::new(tl!("Radius")).show(ui, |ui, _| { - let radius = NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit; - apply_edits(app, &radius, EditPath::Scope, |app, v: &Option, _| { - // A negative radius typed in rounds nothing: the command takes 0 or more. - if let Some(r) = v { - set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); - } - }); + radius = Some(NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit); }); let rounding = RadioGroup::new(tl!("Rounding"), Bind::given(picked.relative)).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { @@ -389,6 +383,15 @@ fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) { set = Some(json!({"relativeRadii": on})); } }); + // Applied after the Stack, whose body runs twice (measure, then real), as the radios' `set`. + if let Some(radius) = radius { + apply_edits(app, &radius, EditPath::Scope, |app, v: &Option, _| { + // A negative radius typed in rounds nothing: the command takes 0 or more. + if let Some(r) = v { + set_picked_corners(app, &picked, json!({"radius": r.max(0.0)})); + } + }); + } if let Some(p) = set { set_picked_corners(app, &picked, p); } diff --git a/docs/mcp.md b/docs/mcp.md index 8b9fb31dd7..57044f4ccf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7989,8 +7989,8 @@ polygon's from its first vertex clockwise; a star's from its first tip; an index Each corner keeps its own radius and kind (the shape's `live` in queries has `radii` and, when a corner isn't round, `kinds`); a corner with no radius is one anchor, a cut one two, and Direct-Selected corners stay selected as that changes. A path that isn't a live shape keeps its uncut outline (`live` `{"shape": "path", "base", "radii"}`) so its -corners stay editable, and is a plain path again once no corner is cut, unless its rounding is Relative; a polygon -stays a live polygon, its corners keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius +corners stay editable, and is a plain path again once no corner is cut; a polygon stays a live polygon, its corners +keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform @@ -8018,9 +8018,9 @@ Direct Selection, while a corner is selected or one live rectangle or polygon is the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the -paths differ). A path without Live Corners is Absolute, and Relative on a path with a corner keeps its outline as the -base of its Live Corners, as a radius does; ellipses and lines are left as they are. Editing a path's anchors (for -example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. With Relative rounding, a radius is +paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no +undo step. Editing a path's anchors (for example `path.moveAnchors`) ends its Live Corners, so it is Absolute again. +With Relative rounding, a radius is compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one `object.setLiveShape` with `items`, one undo step, and the corners that were not picked keep their radius and kind. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b99205fcb..733f42cb74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1525,7 +1525,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules. Relative rounding also works on a plain path with corners (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_takes_on_a_plain_path`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). + - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). From 16710bf8db44632ffa039dfc0ca11e5f205f30cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:59:48 -0800 Subject: [PATCH 14/49] Tests: the grid preview test draws through the shared frame helper drawn_preview now runs each frame with testing::part_frame_uploads instead of its own ctx.run_ui loop. part_frame_uploads is part_frame with the frame's texture uploads kept in the returned FullOutput; part_frame calls it and clears them as before, so its callers see no change. --- crates/ui-egui/src/dialogs/document_setup.rs | 22 ++++++++++++-------- crates/ui-egui/src/testing.rs | 16 ++++++++++++-- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 6d8b492104..4c9a6ae4c7 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -1117,20 +1117,24 @@ mod tests { assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")])); } - /// The grid preview the open dialog draws in `ctx`: its rect, the span of its texture + /// The grid preview the open dialog draws in `ctx`, in frames run as the hosts run them + /// ([`crate::testing::part_frame_uploads`]): its rect, the span of its texture /// coordinates (two cells per unit) and the four pixels of the texture it draws. `tiles` holds /// the pixels of each 2 × 2 texture uploaded so far in `ctx`, so every frame drawn in `ctx` /// goes through this function. The preview is the largest rect drawn with such a texture. fn drawn_preview( - app: &VectorcraftApp, + app: &mut VectorcraftApp, ctx: &egui::Context, tiles: &mut std::collections::HashMap>, ) -> (Rect, egui::Vec2, Vec) { let mut preview = None; for _ in 0..4 { let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; - let dialogs = app.dialogs().unwrap(); - let mut out = ctx.run_ui(raw, |ui| dialogs.with(|h| h.run(ui))); + let mut out = crate::testing::part_frame_uploads(app, ctx, raw, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| h.run(ui)); + } + }); for (id, deltas) in &out.textures_delta.set { if let Some(d) = deltas.last() { let egui::ImageData::Color(img) = &d.image; @@ -1166,19 +1170,19 @@ mod tests { /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. #[test] fn the_grid_preview_follows_edits_in_the_open_dialog() { - let (app, ctx) = setup_open(); + let (mut app, ctx) = setup_open(); let mut tiles = std::collections::HashMap::new(); set(&app, &ctx, "tab", json!("Transparency")); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); set(&app, &ctx, "gridColors", json!(["#ff0000", "#0000ff"])); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); set(&app, &ctx, "gridSize", json!("large")); - let (rect, uv, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); set(&app, &ctx, "gridColors", json!("Dark")); - let (_, _, pixels) = drawn_preview(&app, &ctx, &mut tiles); + let (_, _, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); let st = app.session.active().unwrap(); assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index ac732ae644..a065c31ef8 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -48,6 +48,19 @@ pub(crate) fn app_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, ra /// [`app_frame`] with `draw` showing part of the window in place of the whole app. pub(crate) fn part_frame( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + raw: egui::RawInput, + draw: impl FnMut(&mut crate::VectorcraftApp, &mut egui::Ui), +) -> egui::FullOutput { + let mut out = part_frame_uploads(app, ctx, raw, draw); + out.textures_delta.clear(); + out +} + +/// [`part_frame`] with the frame's texture uploads kept in the output, for a test that reads them. The test clears +/// `textures_delta` once it has read it. +pub(crate) fn part_frame_uploads( app: &mut crate::VectorcraftApp, ctx: &egui::Context, mut raw: egui::RawInput, @@ -56,9 +69,8 @@ pub(crate) fn part_frame( app.adopt_context(ctx); app.raw_input(ctx, &mut raw); embed::before_input(ctx, |out| app.frame_input(out)); - let mut out = ctx.run_ui(raw, |ui| draw(app, ui)); + let out = ctx.run_ui(raw, |ui| draw(app, ui)); run_fired(app, ctx); - out.textures_delta.clear(); out } From 7ece56ec6989a3be48c31df9252cd15367c6436f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:23:15 -0800 Subject: [PATCH 15/49] Packaging tests: use the shared panel harness --- crates/ui-egui/src/addons/packaging/tests.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index d71a98d334..8222b179d5 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_engine::Session; use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show}; use crate::i18n::LangExt as _; +use crate::tests::panel_harness::Panel; use crate::{VectorcraftApp, menus}; /// An app with two rectangles, nothing selected → (app, their ids). @@ -19,16 +20,6 @@ fn app() -> (VectorcraftApp, u64, u64) { (app, a, b) } -/// The values the panel's editable fields show, read from the access tree of its second frame. -fn field_values(app: &mut VectorcraftApp) -> Vec { - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)).textures_delta.clear(); - let out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); - let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - nodes.iter().filter(|(_, n)| n.supports_action(egui::accesskit::Action::SetValue)).filter_map(|(_, n)| n.value().map(str::to_string)).collect() -} - /// The count of each role the panel's rows show. fn counts(app: &mut VectorcraftApp) -> Vec<(String, u64)> { rows(app).into_iter().map(|row| (row.0, row.3)).collect() @@ -190,7 +181,9 @@ fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); let text = crate::tests_labels::painted_text(&mut app, show); assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}"); - let values = field_values(&mut app); + let panel = Panel::new(app, show); + let values = panel.values(); + let mut app = panel.app(); assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}"); let kept = read_rows(&mut app); assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1)); From 59ddb9c3e21c6f054af4928f3142d2089a64210d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:28:05 -0800 Subject: [PATCH 16/49] JavaScript: consume iterators in Promise combinators --- crates/js/src/builtins/promise.rs | 97 +++++++++++-------------------- crates/js/src/iteration.rs | 2 +- crates/js/src/promise_tests.rs | 73 +++++++++++++++++++++-- docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 111 insertions(+), 71 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..1fbbf9c334 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -18,9 +18,9 @@ //! 25.6.1.9); one that still has none when the run ends successfully is reported by //! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. //! -//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object -//! whose `length` is a whole number by index, and a string by code point; other values reject the -//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator +//! when processing a yielded value throws. Noniterable values reject the promise they return +//! with a `TypeError`. The statics need a constructor as `this`, and the //! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` //! are not read. @@ -32,7 +32,6 @@ use crate::LimitKind; use crate::bytecode::Code; use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::string_builtins::flat_charged; use crate::value::Value; /// Where a promise was rejected: the code and the instruction. @@ -1010,67 +1009,41 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe }) } -/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to -/// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. -enum Inputs { - Indexed { object: ObjId, length: f64 }, - CodePoints(Rc<[u16]>), -} - -impl Inputs { - fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { - match input { - Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { - Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { - Ok(Inputs::Indexed { object: *o, length }) - } - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - }, - Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), - _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), - } - } - - /// The input at `index`, which counts code units for a string; `None` past the end. - fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { - match self { - Inputs::Indexed { object, length } => { - let end = match interp.heap.object(*object).map(|o| &o.class) { - Some(Class::Array { length, .. }) => f64::from(*length), - _ => *length, - }; - if *index >= end { - return Ok(None); - } - let v = super::get_at(interp, *object, *index)?; - *index += 1.0; - Ok(Some(v)) - } - Inputs::CodePoints(units) => { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let i = *index as usize; - let Some(&first) = units.get(i) else { return Ok(None) }; - let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); - let n = if pair { 2 } else { 1 }; - let piece = units.get(i..i + n).unwrap_or_default().to_vec(); - *index += n as f64; - let bytes = crate::heap::string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - Ok(Some(Value::String(crate::value::Str::from_units(piece)))) - } - } - } -} - fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { let resolve_fn = interp.get_value(this, &key("resolve"))?; if !interp.is_callable(&resolve_fn) { return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); } root(interp, &resolve_fn); - let inputs = Inputs::new(interp, input, how)?; + let iterator = interp.get_iterator(input)?; + root(interp, &Value::Object(iterator)); + let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject)); + if let Err(Abrupt::Throw(reason)) = &result { + root(interp, reason); + let site = interp.throw_site.clone(); + let mark = interp.thrown_mark; + match interp.iter_close(iterator) { + Ok(()) | Err(Abrupt::Throw(_)) => { + interp.throw_site = site; + interp.thrown_mark = mark; + interp.passing = reason.clone(); + } + Err(other) => return Err(other), + } + } + result +} + +fn combine_iterator( + interp: &mut Interp, + this: &Value, + iterator: ObjId, + how: Combine, + rec: ObjId, + resolve_fn: &Value, + handlers: (&Value, &Value), +) -> JsResult<()> { + let (resolve, reject) = handlers; let combinator = if how == Combine::Race { None } else { @@ -1080,14 +1053,12 @@ fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine root(interp, &Value::Object(c)); Some((c, values)) }; - let mut position = 0.0; let mut index: u32 = 0; loop { - interp.use_fuel()?; let mark = interp.temp_roots.len(); - let Some(next) = inputs.get(interp, &mut position)? else { break }; + let Some(next) = interp.iter_next(iterator)? else { break }; root(interp, &next); - let next_promise = interp.call(&resolve_fn, this, &[next])?; + let next_promise = interp.call(resolve_fn, this, &[next])?; root(interp, &next_promise); match combinator { None => { diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index 49a503f506..eac1d4abe6 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -162,7 +162,7 @@ impl Interp { /// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return` /// method, unless it is done, and checks that it gives an object. - fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { + pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { let r = self.record(rec)?; if r.done { return Ok(()); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..3d1d92769d 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -144,7 +144,73 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { } #[test] -fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { +fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() { + let src = "var input = {}; input[Symbol.iterator] = function () {\n\ + var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\ + };\n\ + Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\ + Promise.race(input).then(function (v) { log.push('race ' + v); });\n\ + var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\ + Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\ + Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });"; + let out = log(src); + for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] { + assert!(out.contains(expected), "{expected} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_close_after_resolve_or_then_throws() { + let src = "function check(name, failure) {\n\ + var closed = 0, input = {};\n\ + input[Symbol.iterator] = function () { return {\n\ + next: function () { return { value: 1, done: false }; },\n\ + return: function () { closed++; throw 'close'; }\n\ + }; };\n\ + Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\ + function () { return { get then() { throw 'then'; } }; };\n\ + Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\ + }\n\ + var original = Promise.resolve;\n\ + for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\ + Promise.resolve = original;"; + let out = log(src); + for name in ["all", "allSettled", "race"] { + for failure in ["resolve", "then"] { + let expected = format!("{name}:{failure}:{failure}:1"); + assert!(out.contains(&expected), "{expected} in {out}"); + } + } +} + +#[test] +fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() { + let src = "var closed = 0;\n\ + function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\ + next: function () { if (failure === 'next') throw failure;\n\ + return { get done() { if (failure === 'done') throw failure; return false; },\n\ + get value() { throw failure; } }; },\n\ + return: function () { closed++; return {}; }\n\ + }; }; return o; }\n\ + for (var i = 0; i < 3; i++) {\n\ + Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\ + }\n\ + var empty = {}; empty[Symbol.iterator] = function () { return {\n\ + next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\ + }; };\n\ + Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\ + Promise.race(empty).then(function () { log.push('race settled'); });\n\ + log.push('closed ' + closed);"; + let out = log(src); + for expected in ["next", "done", "value", "empty 0", "closed 0"] { + assert!(out.contains(expected), "{expected} in {out}"); + } + assert!(!out.contains("race settled"), "{out}"); +} + +#[test] +fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() { // `Promise.resolve` runs once for each input and appends to the input while it is read. let src = "var resolve = Promise.resolve; var input;\n\ Promise.resolve = function (x) {\n\ @@ -152,11 +218,10 @@ fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_t return resolve.call(this, x);\n\ };\n\ input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ - input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });"; + input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });"; let out = log(src); assert!(out.contains("array 1,2,3"), "{out}"); - assert!(out.contains("object 1"), "{out}"); - assert!(!out.contains("object 1,"), "{out}"); + assert!(out.contains("object true"), "{out}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..b2be537836 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2887,8 +2887,12 @@ own rules: stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. -- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one - item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the +- `all`, `allSettled` and `race` read their input through `Symbol.iterator`, including user-defined iterables and + overridden array iterators. In a kept engine with no `Symbol.iterator`, they walk arrays, `arguments` objects and + strings. String iterators keep surrogate pairs together. A noniterable object, including one + with only a `length`, rejects the promise they return with a `TypeError`. When processing a yielded value throws, + the combinator calls the iterator's `return` method if present; the original exception remains the rejection reason + even when `return` throws. An iterator whose step threw or finished is not closed. The promises `then` and the statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. - A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043ae5c403..80bac7dabe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1107,7 +1107,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. From f182ad845be7fc42189402682734c9cb0599391f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:56:36 +0700 Subject: [PATCH 17/49] Text: an over-budget COLR glyph returns no image, raster fallback included A sweep gradient sets unsupported without too_large, so a glyph that later passed the budget still took the raster branch, and Pixels replayed the whole graph with no budget. Check too_large first, as tree.finish() does. Under-budget glyphs are unchanged. Answers CodeRabbit. --- crates/text/src/colr.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 822e1b0972..37c4cefbae 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -73,6 +73,10 @@ pub(crate) fn colour_glyph( return (None, false); } let used = tree.foreground_used; + // Over the budget nothing is drawn, not even the raster fallback: it would replay the graph. + if tree.too_large { + return (None, used); + } if tree.unsupported.is_some() { // What it paints, y up, for a glyph without a clip box. let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b)); From 0983b6dfd50d6b6438b8d196c756975e23cf42f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:57:29 -0800 Subject: [PATCH 18/49] End paused JavaScript runs before compiling replacement source --- crates/js/src/host_tests.rs | 90 +++++++++++++++++++++++++++++++++++++ crates/js/src/realm.rs | 3 ++ docs/mcp.md | 2 + docs/target-app-parity.md | 2 + 4 files changed, 97 insertions(+) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 25265086e5..63032d7aa2 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -75,6 +75,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() { r.end(); } +fn paused_for_replacement(promise: bool) -> Realm { + let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default()); + let pause = r.pause_flag(); + r.define_function("pauseNow", move |_| { + pause.set(true); + Ok(JsValue::Undefined) + }); + let source = if promise { + "var kept = 'yes', after = false, queued = false;\n\ + Promise.resolve().then(function () { pauseNow(); after = true; });\n\ + Promise.resolve().then(function () { queued = true; }); 'old'" + } else { + "var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'" + }; + r.start(source).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.is_running()); + if promise { + assert!(r.interp().promises.draining); + } + r +} + +fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result { + if sliced { + r.start(source)?; + finish(r, 1_000).0 + } else { + r.run(source) + } +} + +#[test] +fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() { + for sliced in [false, true] { + let mut r = paused_for_replacement(true); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_paused_script_discards_its_remaining_code() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_waiting_run_discards_its_host_call() { + for sliced in [false, true] { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var after = false; ask('old'); after = true").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.waits()); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + assert_eq!(calls.get(), 1); + assert!(r.answer(Data::Null).is_err()); + } +} + +#[test] +fn replacing_a_paused_run_with_invalid_source_still_ends_it() { + for promise in [false, true] { + for sliced in [false, true] { + let mut r = paused_for_replacement(promise); + assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } + } +} + +#[test] +fn replacing_a_paused_run_applies_its_pending_language_setting() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + r.set_es2015(true); + assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0)); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + } +} + /// Setting `Folder.current` back for the next run drops what only the last run's uncaught /// exception held, so a full heap from that exception does not stop the next run. #[test] diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index b1273cb760..a3a7c0cc1f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -277,6 +277,7 @@ impl Realm { /// Runs `source` as a script in the global environment, then the promise jobs it queued, and /// returns its completion value (the value of the last expression statement that ran). A realm /// whose built-ins could not be installed runs nothing and gives an internal error. + /// A paused or waiting run ends first; its globals remain available. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); @@ -285,6 +286,7 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.end(); self.script_tag = UNKNOWN_SOURCE; self.rejections = (Vec::new(), 0); let interp = &mut self.interp; @@ -391,6 +393,7 @@ impl Realm { } /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + /// A paused or waiting run ends first; its globals remain available. pub fn start(&mut self, source: &str) -> Result<(), RunError> { let code = self.compile(source)?; match self.interp.enter_global(code, false) { diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..1705b42b38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2883,6 +2883,8 @@ own rules: - The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. A promise still pending when no job is left stays pending, and the run ends. +- In the host API, `Realm::run` and `Realm::start` end a paused or waiting run before compiling the new source. + The earlier run's globals remain available; its remaining code and queued jobs do not run. - The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b564a77730..49104b8aa5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From e3b21ad2bdaa38a202d4347f224a4c85d3b483de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:09:16 -0800 Subject: [PATCH 19/49] Name the undo step when keeping an add-on preview --- crates/ui-egui/src/addons/dialogs.rs | 4 ++-- crates/ui-egui/src/addons/dialogs/tests.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 55ad5dd64d..d29066a126 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -99,8 +99,8 @@ fn pump_commit(app: &mut VectorcraftApp) { let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); - // PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label) - let answer = preview.run(app, *previewing, spec.command, spec.command, params); + let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); + let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 9a24a362eb..eb24e09c37 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -247,6 +247,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() { } } +#[test] +fn keeping_an_add_on_preview_records_the_command_name() { + let mut app = two_rects(); + let undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + + assert!(confirm(&app, id)); + frame(&mut app); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid"); +} + #[test] fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() { let mut app = two_rects(); From bc2162f91c32e82097cae20c53c2eb2d28be236f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:49:28 -0800 Subject: [PATCH 20/49] Use muted body text for Learn step numbers --- crates/ui-egui/src/panels/learn.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs index 985871889c..5753cc3bb5 100644 --- a/crates/ui-egui/src/panels/learn.rs +++ b/crates/ui-egui/src/panels/learn.rs @@ -27,7 +27,7 @@ use craft::ui::contract::{ Bind, CollectionEvent, Gap, LabelKind, MemoProps, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, Sizing, clicked, }; -use craft::ui::display::Text; +use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; @@ -221,8 +221,7 @@ fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::Tuto if let Some(next) = next { marked = Some((i, next)); } - // PLAN: the number should read in the muted ink; the caption role stands in until `Text` names it. - Text::new(format!("{}.", i + 1)).role(TypeRole::Caption).show(ui); + Text::new(format!("{}.", i + 1)).shade(Shade::Muted).show(ui); if step_text(ui, step) { locate = step.tool; } From 4d35a569cbf4c0c12bba6546c5b51742fcc1e83e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:05:38 -0800 Subject: [PATCH 21/49] Make the Production Preflight findings list name translatable --- crates/ui-egui/src/panels/preflight.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index f8ed1f6967..4b4353d8ac 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -302,7 +302,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { let rows = PreflightRows::new(report); let pending = Pending::default(); - let out = FindingsList::new("Findings").show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { + let out = FindingsList::new(tl!("Findings")).show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { Some(Entry_::Heading(c)) => heading_row(&rows.checks[*c], &pending), Some(Entry_::Finding(f)) => finding_row(*key, &rows.findings[*f], &icx.words::(), &pending), None => ListRow::new(String::new()), From a257568cd3e2d028018991e68533d0d7b2fa018b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:07:25 -0800 Subject: [PATCH 22/49] Fix the PDF page options OK footer --- crates/ui-egui/src/dialogs/import_pdf.rs | 11 ++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 44 +++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..99ce30805d 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,14 +372,11 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } - match (out.accepted, out.closed) { - (Some(_), _) => { - self.ok(); - None - } - (None, Some(_)) => Some(DialogResult::Cancel), - (None, None) => None, + if out.picked == Some(0) && !waiting { + self.ok(); + return None; } + out.closed.map(|_| DialogResult::Cancel) } } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..4e9008a734 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -1,6 +1,7 @@ //! The Import PDF dialog: opening and placing multi-page and password-protected PDFs. use craft::ui::dialog::{HeldOk, StackDialog}; +use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; @@ -72,6 +73,37 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } +fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::import_pdf::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(!is_open(h.state())); + h +} + +#[test] +fn pdf_page_footer_ok_opens_the_chosen_range() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); + + let h = click_page_footer_ok(app); + assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); +} + #[test] fn opening_a_multi_page_pdf_asks_for_the_pages() { let mut app = app(); @@ -228,6 +260,18 @@ fn place(app: &mut VectorcraftApp, bytes: &[u8], extra: serde_json::Value) -> Re crate::place::run(app, &p) } +#[test] +fn pdf_page_footer_ok_places_the_chosen_page() { + let mut app = app(); + place(&mut app, &three_pages(), json!({"at": [100, 120], "link": false})).unwrap(); + set(&mut app, "page", json!(2)); + set(&mut app, "cropTo", json!("art")); + + let h = click_page_footer_ok(app); + let (_, bounds) = placed(h.state()); + assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); +} + #[test] fn placing_a_pdf_page_asks_for_the_page_and_crop_box() { let mut app = app(); From 6e190e189aeccde32834bc774878fe1feaacaa0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:07:25 -0800 Subject: [PATCH 23/49] Fix the Graph Column and Marker OK footer --- crates/ui-egui/src/dialogs/graph_design.rs | 34 ++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 2bfdf7b913..f361b5f8c6 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,8 +519,7 @@ impl GraphDesignDialog { } true }); - if let Some(options) = shown.accepted { - self.column = options; + if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); return None; @@ -836,6 +835,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { + use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; use super::GraphDesignDialog; @@ -879,6 +879,36 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_design_footer_ok_applies_column_and_marker_designs() { + for (graph_type, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_type); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(4); + + let app = h.state_mut(); + assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], "New Design"); + } + } + #[test] fn marker_lists_the_designs_and_applies_the_one_picked() { let (mut app, ctx) = app_with_design(); From 70e0dd20de334b0ce04a2790e9ed757129bd45b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:11:37 -0800 Subject: [PATCH 24/49] Reject foreign-document artwork in Asset Export --- crates/ui-egui/src/panels/asset_export.rs | 3 +- .../ui-egui/src/panels/tests_asset_export.rs | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index bfd9867950..36df059b59 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -553,7 +553,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { footer = Some(bar); }); let zone = footed.show(ui, |ui, _| { - DropAction::::new(|p| matches!(p, PanelDrag::Art { .. })).sizing(Sizing::Fill).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |p| matches!(p, PanelDrag::Art { document, .. } if *document == uid)); + drop_art.sizing(Sizing::Fill).show(ui, |ui, _| { if st.doc.assets.is_empty() { Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) .title(tl!("No assets")) diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index bde196ffd2..e14e6c0ea3 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -56,6 +56,56 @@ fn assets(app: &mut VectorcraftApp) -> Vec { app.run("assets.list", json!({})).unwrap()["assets"].as_array().unwrap().clone() } +/// Draws a row carrying the selected artwork's payload above the Asset Export panel. +fn art_and_assets(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + + let st = app.session.active().unwrap(); + let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + super::asset_export::show(app, ui); +} + +#[test] +fn asset_export_accepts_artwork_only_from_its_document() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let mut rectangle = |x| { + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let first = rectangle(10); + let second = rectangle(70); + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + let source = app.session.active().unwrap().uid; + + let mut p = Panel::new(app, art_and_assets); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("No assets").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_some(), "Asset Export accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let drag = craft::ui::runtime::drag::active::(p.ctx()); + assert!(matches!(drag.as_deref(), Some(crate::panel_drag::PanelDrag::Art { document, .. }) if *document == source)); + assert!(craft::ui::runtime::drag::mark(p.ctx()).is_none(), "Asset Export withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert!(assets(&mut p.app()).is_empty(), "the foreign drag must never collect the active document's same-ID artwork"); + + p.drag("Dragged artwork", "No assets", egui::Modifiers::NONE); + let list = assets(&mut p.app()); + assert_eq!(list.len(), 1, "dropping artwork from the active document still collects it"); + assert_eq!(list[0]["nodes"], json!([second])); +} + /// The document's export settings, which the panel and Export for Screens share. fn settings(p: &Panel) -> Value { run(p, "document.exportSettings", json!({}))["settings"].clone() From 40f7f2e0a08a75d01acda014c304b2dfafba3f0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:12:50 -0800 Subject: [PATCH 25/49] Keep Graph Data imports with the sheet that asked --- crates/ui-egui/src/dialogs/graph_data.rs | 55 ++++++++++++++++++++---- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 2ac4764bf5..572f92f664 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -18,6 +18,7 @@ //! empties it). use std::collections::BTreeMap; +use std::sync::Arc; use craft::behavior::{EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; @@ -395,8 +396,12 @@ fn can_import(app: &VectorcraftApp) -> bool { file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() } -/// Import Data's answer: a tab-separated text file's rows into the sheet. -fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { +/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. +fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result { + let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) }; + if !dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) { + return Ok(Value::Null); + } let bytes = match picked { Picked::Paths(paths) => { let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) }; @@ -420,15 +425,14 @@ fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { return Err("the file is larger than 1 MB".into()); } let grid = grid_from_text(&decode(&bytes)); - if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); - } + dialogs.with(|host| host.get_mut::().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid))); Ok(Value::Null) } /// What the window asked of the app since the last [`pump`]. struct Asks { graph: Option, + import_owner: Arc<()>, apply: Option, actions: Vec, } @@ -444,7 +448,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { d.take_asks() }) }); - let Some(Asks { graph, apply: filed, actions }) = asked else { return }; + let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; if let Some(sheet) = filed { if let Err(e) = apply(app, &sheet, graph) { app.status(e); @@ -455,7 +459,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); - file_asks::ask(app, request, Owner::Document, import); + let owner = import_owner.clone(); + file_asks::ask(app, request, Owner::Document, move |app, picked| import(app, &owner, picked)); } Action::Revert => match graph_grid(app, graph) { Ok(grid) => { @@ -636,6 +641,8 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { /// sheet for [`pump`], which sends it to the graph and keeps the window open. pub(crate) struct GraphDataDialog { id: DialogId, + /// Identifies this opening even when another Graph Data dialog reuses `id`. + import_owner: Arc<()>, sheet: Sheet, state: GridState, entry: Entry, @@ -658,6 +665,7 @@ impl GraphDataDialog { load(&sheet, &state, &mut entry); GraphDataDialog { id: dialog_id(KIND), + import_owner: Arc::new(()), sheet, state, entry, @@ -672,7 +680,7 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. @@ -959,6 +967,37 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let files = Arc::new(ScriptedFiles::held()); + app.services.read = Some(Box::new(|_| Err("this picker answers with bytes".into()))); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1); + + let app = h.state_mut(); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + open(app).unwrap(); + let series = |h: &Harness| read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)); + assert!(files.answer(Picked::Contents(vec![("first.txt".into(), b"\tstale\nQ1\t7".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "second"); + + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert!(files.answer(Picked::Contents(vec![("second.txt".into(), b"\timported\nQ2\t8".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "imported"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); From 78aa254ddb7e7c8f2149f1bd9b6325afc1bdbaac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:05:38 -0800 Subject: [PATCH 26/49] Translate the canvas Type editor's accessible name --- crates/ui-egui/src/canvas/tests.rs | 17 +++++++++++++++++ crates/ui-egui/src/type_editing.rs | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..6f90aeba3f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3919,6 +3919,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.active().unwrap().selection.objects[0].0 } +#[test] +fn the_canvas_type_editor_uses_the_interface_language() { + use crate::i18n::LangExt as _; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let former = crate::i18n::current(); + start_typing(&mut app, &ctx); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]); + crate::i18n::set_current(former); + + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte"))); +} + /// Returns a key press and its release. fn tap(key: egui::Key) -> [egui::Event; 2] { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) diff --git a/crates/ui-egui/src/type_editing.rs b/crates/ui-egui/src/type_editing.rs index 346a5854bf..8ee26749a2 100644 --- a/crates/ui-egui/src/type_editing.rs +++ b/crates/ui-egui/src/type_editing.rs @@ -289,7 +289,7 @@ pub(crate) struct TypeEditor<'a> { impl<'a> TypeEditor<'a> { /// A part for the tool's caret at `caret`, the instance of [`TypeEditorCommand`]'s scope while it has the keys. fn new(app: &'a mut VectorcraftApp, caret: Rect, ctx: egui::Context) -> Self { - TypeEditor { common: Common::new(), app, caret, ctx }.label("Type").command_scope(TYPE_EDITOR_SCOPE) + TypeEditor { common: Common::new(), app, caret, ctx }.label(tl!("Type")).command_scope(TYPE_EDITOR_SCOPE) } /// Applies one input of the editor part to the engine tool; a Paste types `pasted`, the text the paste delivered, From 3098ef72d24dfec40e0e52af7854408133017b4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:17:03 -0800 Subject: [PATCH 27/49] Reject foreign-document artwork in Graphic Styles --- crates/ui-egui/src/panels/graphic_styles.rs | 65 ++++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..52b6b2bdf1 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -477,6 +477,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The browser's own state (an open rename field, the scroll position) is kept per document. let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); let list = PresetBrowser::::list_id(browser_id); + let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid).is_some(); // A style dragged from this panel's list. let ours = move |drag: &ListDrag| drag.list == list; let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); @@ -516,8 +517,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) - .takes_drop(PresetDrop::new::(DropPlace::Between, |drag, _| dropped_object(drag).is_some())) - .takes_drop(PresetDrop::new::(DropPlace::Onto, |drag, _| dropped_object(drag).is_some())) + .takes_drop(PresetDrop::new::(DropPlace::Between, takes_object)) + .takes_drop(PresetDrop::new::(DropPlace::Onto, takes_object)) .takes_drop(PresetDrop::new::>( DropPlace::Onto, |drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)), @@ -596,11 +597,11 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent>) { } } -/// The object whose look a dropped payload carries: the first of the art dragged off the canvas, or the Appearance -/// panel's object. -fn dropped_object(drag: &PanelDrag) -> Option { +/// The object whose look a dropped payload carries: the first of the art dragged from this document, or the +/// Appearance panel's object. +fn dropped_object(drag: &PanelDrag, uid: u64) -> Option { match drag { - PanelDrag::Art { ids, .. } => ids.first().copied(), + PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(), PanelDrag::Appearance(id) => Some(*id), _ => None, } @@ -612,7 +613,7 @@ fn dropped(app: &mut VectorcraftApp, at: &DropAt, payload: &DropPayloa DropAt::Onto(name) => Some(name.as_str()), _ => None, }; - let object = payload.get::().and_then(dropped_object); + let object = app.session.active().and_then(|st| dropped_object(payload.get::()?, st.uid)); let style = payload.get::>().map(|drag| drag.grabbed.as_str()); drop_on(app, onto, object, style, alt); } @@ -1319,7 +1320,7 @@ mod tests { let n = names(&app); let document = app.session.active().unwrap().uid; for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] { - drop_on(&mut app, Some("Red"), dropped_object(&payload), None, true); + drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true); let d = doc(&app); assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green); assert_eq!(d.node(oval).unwrap().extras().graphic_style, d.graphic_style("Red").map(|g| g.id)); @@ -1336,6 +1337,54 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), steps); } + #[test] + fn graphic_styles_accepts_artwork_only_from_its_document() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 25, "y": 25, "width": 55, "height": 55})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let second = app.session.active().unwrap().selection.objects[0]; + assert_eq!(first, second, "the two documents have different artwork with the same local ID"); + let before = names(&app); + assert!(app.session.set_active(0)); + + let mut p = PanelHarness::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Drop Target").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphic Styles accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphic Styles withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(names(&p.app()), before, "the foreign drop creates no style from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Drop Target", egui::Modifiers::NONE); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a same-document drop still makes a style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { From 9093809d5dd7eff02798ea25fe644168c912d230 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:18:44 -0800 Subject: [PATCH 28/49] Keep Batch folder picks with the dialog that asked --- crates/ui-egui/src/dialogs/action_batch.rs | 59 ++++++++++++++++++---- crates/ui-egui/src/dialogs/actions.rs | 10 ++-- 2 files changed, 55 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 705913d428..4b2b79a02d 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,6 +8,7 @@ //! empty, or Data Sets without a document, is an error and the dialog stays open. use std::hash::Hash; +use std::sync::Arc; use craft::automation::actions::Action; use craft::host::PickRequest; @@ -131,6 +132,8 @@ pub(crate) enum Folder { /// The Batch dialog on the dialog host. pub struct BatchDialog { id: DialogId, + /// Identifies this opening even when another Batch dialog reuses `id`. + folder_owner: Arc<()>, /// The index of the action's set. pub set: usize, /// The index of the action in its set. @@ -150,13 +153,13 @@ impl BatchDialog { &self.form.values } - /// The Browse presses since the last call. - pub(crate) fn take_asked(&mut self) -> Vec { - std::mem::take(&mut self.asked) + /// The Browse presses since the last call and the opening that made them. + pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec) { + (self.folder_owner.clone(), std::mem::take(&mut self.asked)) } /// Writes the folder the picker answered into its row. - pub(crate) fn set_folder(&mut self, which: Folder, path: String) { + fn set_folder(&mut self, which: Folder, path: String) { match which { Folder::Source => self.form.values.folder = path, Folder::Destination => self.form.values.destination_folder = path, @@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result, which: Folder) { let title = match which { Folder::Source => crate::i18n::t("Source Folder"), Folder::Destination => crate::i18n::t("Destination Folder"), @@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) { if let Some(path) = picked.paths().first() && let Some(dialogs) = app.dialogs() { - let path = path.to_string_lossy().into_owned(); dialogs.with(|host| { - if let Some(dialog) = host.get_mut::() { - dialog.set_folder(which, path); + if let Some(dialog) = host.get_mut::().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) { + dialog.set_folder(which, path.to_string_lossy().into_owned()); } }); } @@ -437,6 +440,44 @@ mod tests { }); } + #[test] + fn batch_folder_answers_belong_to_the_dialog_that_asked() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let mut app = app_with(vec![step]); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let request_folders = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.get_mut::().unwrap().asked.extend([Folder::Source, Folder::Destination])); + pump(app, &ctx); + }; + let folders = || { + dialogs.with(|host| { + let fields = host.get::().unwrap().fields(); + (fields.folder.clone(), fields.destination_folder.clone()) + }) + }; + let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| { + picker.answer(&[destination]); + picker.answer(&[source]); + file_asks::poll(app); + }; + + open(&mut app, 0, 0).unwrap(); + request_folders(&mut app); + assert_eq!(picker.requests().len(), 2); + dialogs.with(|host| host.cancel::(&ctx)); + open(&mut app, 0, 0).unwrap(); + set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]); + answer(&mut app, "old-source", "old-destination"); + assert_eq!(folders(), ("new-source".into(), "new-destination".into())); + + request_folders(&mut app); + assert_eq!(picker.requests().len(), 4); + answer(&mut app, "picked-source", "picked-destination"); + assert_eq!(folders(), ("picked-source".into(), "picked-destination".into())); + } + /// Batch plays an action recorded with a key its command no longer reads, as Play does. #[test] fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() { diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 7d52338be2..8a6de85fe4 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -363,13 +363,13 @@ fn push_app_data(app: &VectorcraftApp) { } } -/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose -/// answer is written into the dialog. +/// Files the folder picks the Batch dialog asked for with the identity of that opening. fn ask_batch_folders(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked).unwrap_or_default()); - for which in asked { - super::action_batch::ask_folder(app, which); + let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked)); + let Some((owner, folders)) = asked else { return }; + for which in folders { + super::action_batch::ask_folder(app, owner.clone(), which); } } From 4020b59c5a2eaf6247a695b916a73cfd545a1420 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:17:05 -0800 Subject: [PATCH 29/49] Reject Swatches pattern drops from another document --- crates/ui-egui/src/panels/swatches.rs | 13 ++++------- crates/ui-egui/src/panels/swatches/dnd.rs | 12 ++++++++++ crates/ui-egui/src/panels/swatches/tests.rs | 25 ++++++++++++++++++++- 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9995752ec1..58f24ed3f5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use craft::color_ui::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchKind use craft::color_ui::ui::{SwatchKey, SwatchesPanel, SwatchesState}; use craft::theme::Srgba; use craft::ui::choice::SwatchFace; -use craft::ui::contract::{Bind, DropAt, DropPlace, ListDrag, MemoProps, SelectMode}; +use craft::ui::contract::{Bind, DropPlace, ListDrag, MemoProps, SelectMode}; use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; @@ -407,6 +407,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { doc: Arc::clone(&st.doc), }; let dragged_doc = Arc::clone(&thumbs.doc); + let document = st.uid; let shown_app: &VectorcraftApp = app; let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) @@ -416,8 +417,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { _ => vec![], }) .row_items(|key| row_items(shown_app, key)) - .takes_drop::(DropPlace::Between, takes) - .takes_drop::(DropPlace::Onto, takes) + .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document)) + .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document)) .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) @@ -467,12 +468,6 @@ fn on_event(app: &mut VectorcraftApp, shown: &[SwatchKey], event: PresetEvent) -> bool { - matches!(d, PanelDrag::Paint { .. } | PanelDrag::Art { .. }) -} - /// A double click or Enter: Swatch Options for a swatch, Edit or Apply Color Group for a group. fn activate(app: &mut VectorcraftApp, key: &SwatchKey) { match key { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index dd3aff50f9..2151357979 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,6 +4,15 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; +/// Swatches take paint payloads and artwork from the current document's canvas. +pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { + match drag { + PanelDrag::Paint { .. } => true, + PanelDrag::Art { document: source, .. } => *source == document, + _ => false, + } +} + /// A drag released on the panel. pub(super) enum Drop { /// Swatches (or colour groups) dropped before or `after` row `target`, into folder `target`, or @@ -75,6 +84,9 @@ fn place(shown: &[SwatchKey], at: &DropAt) -> (Option, bool) /// `drag` dropped onto a swatch or between rows of the `shown` list (ap.AP2 `Dropped`); a gap with no /// row under the pointer is the end of the list. pub(super) fn on_dropped(app: &mut VectorcraftApp, shown: &[SwatchKey], at: &DropAt, drag: &PanelDrag, mods: Mods) { + if !app.session.active().is_some_and(|st| accepts(drag, st.uid)) { + return; + } let (target, after) = place(shown, at); if let Some(drop) = Drop::of(drag, target, after, mods) { apply_drop(app, drop); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index b638b289f5..c770f5094a 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::dialogs::swatch_options::KIND; use crate::tests::picks::{answer_dialog, cancel_dialog, draw_dialogs, open_dialogs}; use craft::keymap::Mods; -use craft::ui::contract::ReorderMove; +use craft::ui::contract::{DropAt, ReorderMove}; use craft::ui::dialog::DialogId; use egui::Pos2; use vectorcraft_color::Color; @@ -602,6 +602,29 @@ fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { assert_eq!(doc(&app).node(vectorcraft_doc::NodeId(id)), before.node(vectorcraft_doc::NodeId(id)), "the art stays as it was"); } +#[test] +fn swatches_ignore_artwork_from_another_document_with_the_same_object_id() { + let mut app = app(); + let shape = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + let source = app.run("shape.rectangle", shape.clone()).unwrap()["id"].as_u64().unwrap(); + let drag = art_drag(&app, vec![vectorcraft_doc::NodeId(source)]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let local = app.run("shape.rectangle", shape).unwrap()["id"].as_u64().unwrap(); + assert_eq!(source, local); + + dropped_below(&mut app, drag.clone(), none()); + assert!(doc(&app).patterns.is_empty(), "foreign artwork cannot create a pattern"); + + let star = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap(); + let local_drag = art_drag(&app, vec![vectorcraft_doc::NodeId(star)]); + dropped_below(&mut app, local_drag, none()); + assert_eq!(doc(&app).patterns.len(), 1, "the same document's artwork can create a pattern"); + let before = doc(&app).patterns[0].clone(); + let name = before.name.clone(); + dropped(&mut app, drag, &name, alt()); + assert_eq!(doc(&app).patterns[0].art, before.art, "foreign artwork cannot replace an existing pattern"); +} + /// Art released with Alt held over a pattern swatch becomes that pattern's tile art in one undo /// step: no pattern or swatch is added and the art stays. With Alt over a color swatch, or without /// Alt over the pattern swatch, the art becomes a new pattern swatch. From 74d23677a60f7f2325731a7813c1c8f2d57775b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:14:25 -0800 Subject: [PATCH 30/49] Translate canvas widget accessibility text --- crates/ui-egui/src/canvas/selection_widgets.rs | 2 +- crates/ui-egui/src/canvas/widgets.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 00abc89bc9..921a9e73e4 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets { impl SelectionWidgets { fn new(layout: Layout) -> Self { - SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets")) } } diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 204853bd98..2545d16761 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -275,7 +275,7 @@ impl ShapeWidgets { } fn new(marks: Vec) -> Self { - ShapeWidgets { common: Common::new(), marks }.label("Shape widgets") + ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets")) } } @@ -334,7 +334,7 @@ impl Component for ShapeWidgets { } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { - access.description("Shape widgets"); + access.description(tl!("Shape widgets")); } fn finish(self, cx: Cx<'_, Self>) -> Response { From 7535fada7b388e3e06114826c6fc2bd98aa710e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:21:38 -0800 Subject: [PATCH 31/49] Keep gradient stop models when dropping onto art --- crates/ui-egui/src/canvas/drops.rs | 6 ++++ crates/ui-egui/src/canvas/drops/tests.rs | 35 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..f2ae87a7a8 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -362,6 +362,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); + if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) { + if cmd == "paint.setStroke" { + gradient.remove("dither"); + } + params["keepModel"] = json!(true); + } run(app, cmd, params) } Payload::Panel(PanelDrag::Appearance(source)) => { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..6fdaf1b7af 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -45,6 +45,41 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + app.session.fill_active = fill; + let mut gradient = GradientPaint::new(Default::default()); + gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0); + gradient.gradient.dither = true; + let start = undo_len(app); + let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient))); + drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(app), start + 1); + id +} + +#[test] +fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, true); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") }; + assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(fill.gradient.dither); +} + +#[test] +fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, false); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") }; + assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(!stroke.gradient.dither); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol From 682cac41bd8a9ea851875c8a139459429c321a60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:22:11 -0800 Subject: [PATCH 32/49] Reject artwork drops from a different document in Libraries --- crates/ui-egui/src/panels/libraries.rs | 68 ++++++++++++-------- crates/ui-egui/src/panels/libraries/tests.rs | 28 ++++++++ 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 655be80fb3..5d1955810a 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -162,21 +162,6 @@ enum Grab { New(ItemKind, Value), } -/// The item of library `library` that `drag` holds, or what it would add, if anything. -fn grabbed(drag: &PanelDrag, library: &str) -> Option { - match drag { - PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), - PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), - PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), - PanelDrag::Art { ids, .. } => { - let ids: Vec = ids.iter().map(|id| id.0).collect(); - Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) - } - PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), - _ => None, - } -} - /// The kind and `library.add` params of what `drag` holds, to add to library `library`: a color /// (not one of that library's own; a spot colour with its swatch's name), or a gradient or pattern /// swatch, by its name. @@ -205,6 +190,7 @@ fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { /// which keep their test, can read it: what a drop into a group, or out of every group, does. struct Membership { library: String, + active_document: Option, /// The group of each grouped item, by its index in the library's groups. index: HashMap<(ItemKind, String), usize>, /// The groups' names, in the library's order. @@ -212,9 +198,25 @@ struct Membership { } impl Membership { - fn of(library: &str, lib: &Library) -> Self { + fn of(library: &str, lib: &Library, active_document: Option) -> Self { let index = lib.group_index().into_iter().map(|((kind, item), group)| ((kind, item.to_string()), group)).collect(); - Membership { library: library.to_string(), index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + Membership { library: library.to_string(), active_document, index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } + } + + /// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document. + fn grabbed(&self, drag: &PanelDrag) -> Option { + let library = &self.library; + match drag { + PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), + PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), + PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), + PanelDrag::Art { document, ids } if Some(*document) == self.active_document => { + let ids: Vec = ids.iter().map(|id| id.0).collect(); + Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) + } + PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), + _ => None, + } } fn group_of(&self, kind: ItemKind, key: &str) -> Option { @@ -232,7 +234,7 @@ impl Membership { /// another group moves in, art or a swatch is added there. `None` when nothing would change, /// as for an item dropped on its own group, so that the target does not take it. fn landing(&self, drag: &PanelDrag, group: Option) -> Option { - let (cmd, mut params) = match grabbed(drag, &self.library)? { + let (cmd, mut params) = match self.grabbed(drag)? { Grab::Item(kind, item) if self.group_of(kind, &item) != group => ("library.moveItem", json!({ "kind": kind_param(kind), "item": item })), Grab::New(_, add) => ("library.add", add), Grab::Item(..) => return None, @@ -303,8 +305,8 @@ struct View<'a> { } impl<'a> View<'a> { - fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, has_doc: bool, can_apply: bool) -> Self { - let membership = Membership::of(library, lib); + fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, active_document: Option, can_apply: bool) -> Self { + let membership = Membership::of(library, lib, active_document); let query = query.trim().to_lowercase(); let searching = !query.is_empty(); let items: Vec> = lib @@ -319,7 +321,20 @@ impl<'a> View<'a> { } } let empty = lib.items().next().is_none() && lib.groups.is_empty(); - View { library, lib, membership: Arc::new(membership), items, counts, query, searching, empty, list, fill_active, has_doc, can_apply } + View { + library, + lib, + membership: Arc::new(membership), + items, + counts, + query, + searching, + empty, + list, + fill_active, + has_doc: active_document.is_some(), + can_apply, + } } /// The list: the ungrouped items, then the groups as sections. A drop anywhere on it away from @@ -387,7 +402,7 @@ impl<'a> View<'a> { /// Whether the drag in progress holds an item of one of this library's groups. fn dragging_grouped(&self, ui: &Ui) -> bool { craft::ui::runtime::drag::active::(ui.ctx()).is_some_and( - |drag| matches!(grabbed(&drag, self.library), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), + |drag| matches!(self.membership.grabbed(&drag), Some(Grab::Item(kind, item)) if self.membership.group_of(kind, &item).is_some()), ) } @@ -476,7 +491,7 @@ impl<'a> View<'a> { let source = keyed(shown, |item: &&Shown<'a>| item.key.to_string()); let takes = DropKind::new::( DropPlace::Between, - move |drag: &PanelDrag, _: &DropAt| matches!(grabbed(drag, self.library), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), + move |drag: &PanelDrag, _: &DropAt| matches!(self.membership.grabbed(drag), Some(Grab::Item(k, _) | Grab::New(k, _)) if k == kind), ); // A graphic is placed by a double click; every other item is used by a click. let activate = if kind == ItemKind::Graphic { ActivateOn::DoubleClick } else { ActivateOn::Click }; @@ -565,7 +580,7 @@ impl<'a> View<'a> { /// `kind` moves there, art or a swatch of that kind is added there. Nothing for an item dropped /// beside itself. fn dropped(&self, drag: &PanelDrag, kind: ItemKind, at: Option<(&'static str, &str)>, group: Option) -> Option { - match grabbed(drag, self.library)? { + match self.membership.grabbed(drag)? { Grab::Item(k, item) if k == kind => (at.is_none_or(|(_, key)| key != item)).then(|| self.moved(kind, &item, at, group)), Grab::New(k, mut params) if k == kind => { if let Some((side, key)) = at { @@ -761,7 +776,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let acts = RefCell::new(Vec::new()); - let has_doc = app.session.active().is_some(); + let active_document = app.session.active().map(|st| st.uid); + let has_doc = active_document.is_some(); { // PLAN: assumed `UiState::{libraries_list_view: bool, library_search: String, library_groups_closed: HashSet<(String, String)>}` (ap.AS17, hub-w1). let (session, state) = (&app.session, &mut app.ui); @@ -769,7 +785,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Whether a character style's Apply Character Style is enabled (looked up only when the library has one). let can_apply = has_doc && !lib.char_styles.is_empty() && vectorcraft_engine::cmd::textstyles::target_style_attrs(session, &json!({}), false).is_some(); - let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, has_doc, can_apply); + let view = View::new(&lib_id, lib, &state.library_search, state.libraries_list_view, session.fill_active, active_document, can_apply); Panel::new(tl!("Libraries")).footer(|ui, _| footer(ui, has_doc, &acts)).show(ui, |ui, _| { let search = (!view.empty).then_some(&mut state.library_search); header(ui, &session.libraries, &lib_id, &mut state.libraries_list_view, search, &acts); diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 4d14dcb8a4..305e8eadbf 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -248,6 +248,34 @@ fn an_empty_library_takes_art_anywhere() { assert_eq!(graphics(&mut panel.app()).len(), 1); } +#[test] +fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() { + let mut app = app(); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + let first = art_drag(&mut app, 10.0); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let second = art_drag(&mut app, 50.0); + assert!(matches!((&first, &second), (PanelDrag::Art { ids: a, .. }, PanelDrag::Art { ids: b, .. }) if a == b)); + assert!(app.session.set_active(0)); + + let mut panel = Harness::new(app, with_source); + let from = panel.rect(SOURCE).center(); + let to = panel.rect("This library is empty").center(); + CARRIED.with(|carried| *carried.borrow_mut() = Some(first.clone())); + panel.drag_hold_role(SOURCE, craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_some()); + assert!(panel.app().session.set_active(1)); + panel.frame(); + let drag = craft::ui::runtime::drag::active::(panel.ctx()); + assert_eq!(drag.as_deref(), Some(&first)); + assert!(craft::ui::runtime::drag::mark(panel.ctx()).is_none()); + panel.release(); + assert!(graphics(&mut panel.app()).is_empty(), "the library never collects the target document's same-ID artwork"); + + drop_at(&mut panel, second, to); + assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added"); +} + fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { let mut app = app(); app.run("library.create", json!({"name": "Brand"})).unwrap(); From 9314ddc4e7a4f21e964b59b2f990861d1259904c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:56:54 -0800 Subject: [PATCH 33/49] Tests: quote script file paths as JavaScript strings --- crates/engine/src/tests/script_dom.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..e3fada4b17 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1347,24 +1347,24 @@ fn editable_measures_a_group_on_a_locked_artboard_once() { #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); - let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + let fixture = vectorcraft_testkit::TempDir::new("script-file-open-quoting"); + let path = fixture.join("quote's open.svg"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = serde_json::to_string(&path.to_string_lossy()).unwrap(); + let other = serde_json::to_string(&format!("{}.other", path.to_string_lossy())).unwrap(); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. - let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + let elsewhere = fixture.join("elsewhere"); std::fs::create_dir_all(&elsewhere).unwrap(); let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); assert_eq!(out, vec![json!(false), json!(false)]); - let _ = std::fs::remove_dir_all(&elsewhere); for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); } assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); - let _ = std::fs::remove_file(path); } #[test] From e6e7d389a47e898c62a309388d7568c7e1c32958 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:25:36 -0800 Subject: [PATCH 34/49] Reject foreign-document artwork in 3D and Materials --- crates/ui-egui/src/dialogs/three_d.rs | 3 ++ .../ui-egui/src/dialogs/three_d_materials.rs | 5 +- crates/ui-egui/src/panels/tests_three_d.rs | 48 +++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 8345aad401..1bf8a87680 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -55,6 +55,8 @@ pub(crate) struct Data { pub bevels_file: bool, /// The active document, for the symbol pictures. pub doc: Option>, + /// The document that owns the object IDs accepted by the Graphics drop target. + pub document_uid: Option, /// The active document's version. pub revision: u64, /// Whether the active document has a selection. @@ -77,6 +79,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map Option { Text::new(tl!("Graphics")).show(ui); let mut action = None; - let (Some(doc), true) = (data.doc.clone(), true) else { return action }; + let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let keys = crate::panels::symbols::document_symbols(&doc, data.revision); let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str())); - let mut dropped = DropAction::::new(|drag| matches!(drag, PanelDrag::Art { .. })).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid)); + let mut dropped = drop_art.show(ui, |ui, _| { TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| { let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) }; let (doc, keys, name) = (doc.clone(), keys.clone(), name.clone()); diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index e13cf649a6..cc1c1593da 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -686,6 +686,54 @@ fn art_can_be_added_as_a_graphic_before_any_3d_effect() { assert!(painted_text(&mut app, show).contains("Add as Single Graphic")); } +#[test] +fn three_d_graphics_accepts_artwork_only_from_its_document() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, ShowCollection as _}; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_artwork(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + show(app, ui); + } + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let first = app.session.active().unwrap().selection.objects[0]; + let add_existing = |app: &mut VectorcraftApp| app.run("threeD.addGraphic", json!({"name": "Existing Graphic"})).unwrap(); + add_existing(&mut app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + add_existing(&mut app); + assert_eq!(first.0, second, "the two documents have different artwork with the same local ID"); + assert!(app.session.set_active(0)); + + let mut p = Panel::new(app, with_artwork); + let from = p.rect("Dragged artwork").center(); + let to = p.rect("Existing Graphic").center(); + p.drag_hold_role("Dragged artwork", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some(), "Graphics accepts the artwork before switching documents"); + assert!(p.app().session.set_active(1)); + p.frame(); + let carried = drag::active::(p.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { document, .. }) if *document == source)); + assert!(drag::mark(p.ctx()).is_none(), "Graphics withdraws the drop indicator when the artwork is foreign"); + p.release(); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 1, "the foreign drop adds no symbol from the active document's same-ID artwork"); + + p.drag("Dragged artwork", "Existing Graphic", egui::Modifiers::NONE); + assert_eq!(p.app().session.active().unwrap().doc.symbols.len(), 2, "a same-document drop still makes a graphic"); +} + #[test] fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { let (mut app, _) = materials_app(); From 909895a6fe35003e0616eebf4fb17862a627d09a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:26:26 -0800 Subject: [PATCH 35/49] Scope Other Library replies to the Recolor opening --- crates/ui-egui/src/dialogs/recolor.rs | 15 ++++++++---- crates/ui-egui/src/tests/recolor.rs | 33 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e9c0760844..3768c182d2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1505,6 +1505,7 @@ impl Feed { /// What the pump works on with the app, out of the host: the values, their steps and what `show` /// asked for. struct Work { + opening: Arc<()>, fields: Fields, steps: Steps, filed: Filed, @@ -1544,7 +1545,7 @@ impl Work { randomize(app, &mut self.fields, sb); } if filed.library { - pick_library(app); + pick_library(app, Arc::clone(&self.opening)); } let d = &mut self.fields; if let Some(before) = filed.edited { @@ -1591,16 +1592,16 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. -fn pick_library(app: &mut VectorcraftApp) { +fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); - // PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| { + // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. + crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("swatch.library.load", json!({ "path": path }))?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { - if let Some(d) = host.get_mut::() { + if let Some(d) = host.get_mut_by_id::(dialog_id(KIND)).filter(|d| Arc::ptr_eq(&opening, &d.opening)) { d.fields.fields.insert("limitTo".into(), library); } }); @@ -1765,6 +1766,8 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { /// commits the recolour. pub(crate) struct RecolorDialog { id: DialogId, + /// The identity of this opening, since Recolor Artwork reuses its dialog ID. + opening: Arc<()>, fields: Fields, steps: Steps, held: HeldAnswer, @@ -1787,6 +1790,7 @@ impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { id: dialog_id(KIND), + opening: Arc::new(()), feed: Feed::of(app, &fields), steps: Steps::opened(snapshot(&fields)), fields, @@ -1803,6 +1807,7 @@ impl RecolorDialog { /// The values, steps and requests, for the pump to work on with the app. fn take_work(&mut self) -> Work { Work { + opening: Arc::clone(&self.opening), fields: std::mem::take(&mut self.fields), steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())), filed: std::mem::take(&mut self.filed), diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index b56303f960..b4fa530205 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -447,6 +447,39 @@ fn a_gray_row_keeps_the_hsb_sliders_while_it_is_edited() { assert_eq!(field(&r, "sliderMode"), json!("hsb")); } +#[test] +fn other_library_picker_only_limits_the_recolor_opening_that_requested_it() { + let path = vectorcraft_testkit::temp_dir("recolor-other-library").join("Recolor Test.gpl"); + std::fs::write(&path, "GIMP Palette\nName: Recolor Test\n#\n12 34 56 Test Color\n").unwrap(); + let path = path.to_str().unwrap(); + for reopen in [true, false] { + let mut r = open(app(), json!({"colors": ["#123456"], "library": "document"})); + let picker = super::picks::scripted(&mut r.app()); + r.settled(); + tap(&mut r, "Other Library…"); + assert_eq!(picker.requests().len(), 1, "the dialog asked for a file"); + if reopen { + r.cancel(); + assert!(!r.is_open(), "the first opening closed while its answer was pending"); + r.app().run("ui.recolorDialog", json!({"colors": ["#abcdef"], "library": "document"})).unwrap(); + r.settled(); + } + assert_eq!(field(&r, "limitTo"), "document"); + + picker.answer(&[path]); + crate::file_asks::poll(&mut r.app()); + r.settled(); + let libraries = r.app().run("swatch.library.list", json!({})).unwrap(); + let imported = libraries["libraries"].as_array().unwrap().iter().find(|lib| lib["category"] == "loaded").expect("the library still loads"); + if reopen { + assert_eq!(field(&r, "limitTo"), "document", "the reopened dialog keeps its own Limit to Library choice"); + } else { + assert_eq!(field(&r, "limitTo"), imported["id"], "an answer for the current opening selects its library"); + } + r.cancel(); + } +} + /// With Limit to Library, a row whose new color is a spot color of the library shows Tint, whose T /// slider sets the row's tint of it; OK links the art to the spot color at that tint. #[test] From 37ec4c7a1a806992481e45b427f882566c533c15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:25 -0800 Subject: [PATCH 36/49] Scope texture replies to the Effect Gallery opening --- crates/ui-egui/src/dialogs/effect_gallery.rs | 42 ++++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6fc5ad7813..3b7116e63a 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,6 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -117,7 +118,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let shown = dialogs.with(|host| { host.get_mut_by_id::(id).map(|dialog| { let visible = dialog.entries(true); - (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), dialog.asked.take()) + let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); + (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) }) }); let Some((on, batch, asked)) = shown else { @@ -127,18 +129,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { // `run` reports a failed preview itself. let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); app.effect_dialogs.gallery = Some(open); - if let Some(layer) = asked { - ask_texture(app, id, layer); + if let Some((opening, layer)) = asked { + ask_texture(app, id, opening, layer); } } -/// Asks for the image Load Texture reads into the layer `layer`. The answer finds the layer by its own id, wherever -/// it moved, and is dropped for a layer deleted since or a gallery that closed (a layer id is never used twice). -fn ask_texture(app: &mut VectorcraftApp, id: DialogId, layer: LayerId) { +/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. +fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { - if let Some(dialog) = host.get_mut_by_id::(id) { + if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { dialog.answer_texture(layer, fields); } }); @@ -234,6 +235,8 @@ fn entries_of(layers: &[EffectLayer], index: &FilterIndex, visible_only: bool) - /// [`FilterGallerySession`], with a preview of the visible layers and OK held for [`commit`]. pub(crate) struct EffectGalleryDialog { id: DialogId, + /// Dialog IDs and layer IDs can both be reused when the gallery opens again. + opening: Arc<()>, open: bool, catalog: Catalog, index: FilterIndex, @@ -255,6 +258,7 @@ impl EffectGalleryDialog { let session = FilterGallerySession::new(&first, &catalog); EffectGalleryDialog { id: dialog_id(KEY), + opening: Arc::new(()), open: true, catalog, index, @@ -652,8 +656,7 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); } - /// Load Texture… in the Settings, answered after the stack changed: the image goes into the layer that asked - /// wherever it moved, and an answer for a deleted layer is dropped. + /// A delayed Load Texture… reply follows its layer when it moves and is dropped when the layer or its gallery closes. #[test] fn settings_load_texture_answers_into_the_gallery() { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; @@ -677,10 +680,13 @@ mod tests { }) .collect() }; - // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the stack before the answer. - let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&VectorcraftApp)| { + let rough_pastels = || { let layer = json!({ "filter": "artistic.roughPastels", "visible": true, "params": {} }); - set(app, &ctx, "effects", json!([layer, layer])); + json!([layer, layer]) + }; + // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the gallery before the answer. + let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&mut VectorcraftApp)| { + set(app, &ctx, "effects", rough_pastels()); set(app, &ctx, "select", json!(row)); // The Texture row's Browse press, as the dialog's pass records it. app.dialogs().unwrap().with(|host| { @@ -696,6 +702,18 @@ mod tests { assert_eq!(ask(&mut app, 1, &|_| {}), [false, true], "the selected layer asked"); assert_eq!(ask(&mut app, 0, &|app| set(app, &ctx, "move", json!({"from": 0, "to": 1}))), [false, true], "the layer that asked moved"); assert_eq!(ask(&mut app, 1, &|app| set(app, &ctx, "delete", json!(true))), [false], "the layer that asked was deleted"); + let reopen = |app: &mut VectorcraftApp| { + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(app, &ctx); + super::open(app, &json!({})).unwrap(); + }; + // Both openings start with identical stacks, which gives their corresponding layers the same session-local IDs. + reopen(&mut app); + let answers = ask(&mut app, 0, &|app| { + reopen(app); + set(app, &ctx, "effects", rough_pastels()); + }); + assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } } From b450c47f7eda2884f7667163491f0f48a49c0e0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:36 -0800 Subject: [PATCH 37/49] Cancel PDF page options when Escape shares the OK frame --- crates/ui-egui/src/dialogs/import_pdf.rs | 6 ++-- .../ui-egui/src/dialogs/tests_import_pdf.rs | 35 +++++++++++++------ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 99ce30805d..f230c01ea3 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,11 +372,13 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } + if out.closed.is_some() { + return Some(DialogResult::Cancel); + } if out.picked == Some(0) && !waiting { self.ok(); - return None; } - out.closed.map(|_| DialogResult::Cancel) + None } } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 4e9008a734..c748aa9d81 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -73,7 +73,7 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } -fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { +fn click_page_footer_ok(app: VectorcraftApp, dismiss: bool) -> egui_kittest::Harness<'static, VectorcraftApp> { let mut fonts = false; let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { @@ -87,21 +87,36 @@ fn click_page_footer_ok(app: VectorcraftApp) -> egui_kittest::Harness<'static, V app, ); h.run_steps(4); - h.get_by_label("OK").click(); + if dismiss { + let pos = h.get_by_label("OK").rect().center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.hover_at(pos); + h.event(button(true)); + h.step(); + h.input_mut().events.extend([ + button(false), + egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + ]); + } else { + h.get_by_label("OK").click(); + } h.run_steps(4); assert!(!is_open(h.state())); h } #[test] -fn pdf_page_footer_ok_opens_the_chosen_range() { - let mut app = app(); - io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); - set(&mut app, "allPages", json!(false)); - set(&mut app, "range", json!("2-3")); +fn pdf_page_footer_ok_opens_the_chosen_range_unless_dismissed() { + for dismiss in [false, true] { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); - let h = click_page_footer_ok(app); - assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); + let h = click_page_footer_ok(app, dismiss); + let expected: &[f64] = if dismiss { &[400.0] } else { &[200.0, 300.0] }; + assert_eq!(artboard_widths(h.state()), expected); + } } #[test] @@ -267,7 +282,7 @@ fn pdf_page_footer_ok_places_the_chosen_page() { set(&mut app, "page", json!(2)); set(&mut app, "cropTo", json!("art")); - let h = click_page_footer_ok(app); + let h = click_page_footer_ok(app, false); let (_, bounds) = placed(h.state()); assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); } From a67e60394404d830ebf65648b24c88cd19d2e4f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:30:36 -0800 Subject: [PATCH 38/49] Cancel a Graph design when Escape shares the OK frame --- crates/ui-egui/src/dialogs/graph_design.rs | 28 +++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index f361b5f8c6..cf0c4dc6e1 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,12 +519,14 @@ impl GraphDesignDialog { } true }); + if shown.closed.is_some() { + return Some(DialogResult::Cancel); + } if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); - return None; } - shown.closed.map(|_| DialogResult::Cancel) + None } } @@ -880,8 +882,8 @@ mod tests { } #[test] - fn graph_design_footer_ok_applies_column_and_marker_designs() { - for (graph_type, command) in [("column", "graph.column"), ("line", "graph.marker")] { + fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { + for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { let (mut app, ctx) = app_with_design(); select_graph(&mut app, graph_type); crate::menus::invoke(&mut app, command, json!({})); @@ -900,12 +902,26 @@ mod tests { app, ); h.run_steps(4); - h.get_by_label("OK").click(); + if dismiss { + let pos = h.get_by_label("OK").rect().center(); + let button = + |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.hover_at(pos); + h.event(button(true)); + h.step(); + h.input_mut().events.extend([ + button(false), + egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + ]); + } else { + h.get_by_label("OK").click(); + } h.run_steps(4); let app = h.state_mut(); assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); - assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], "New Design"); + let expected = if dismiss { Value::Null } else { json!("New Design") }; + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], expected); } } From f4704bb688be422a358207ebb6e6f547e2d3f43d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:35:37 -0800 Subject: [PATCH 39/49] Scripts: reject protected page-item mutations --- crates/engine/src/script/dom.rs | 35 ++++++++++++------- crates/engine/src/tests/script_dom.rs | 48 +++++++++++++++++++++++++++ docs/mcp.md | 6 ++-- docs/target-app-parity.md | 2 ++ 4 files changed, 77 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9c137c96bd..1f54403017 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1599,16 +1599,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in -/// is hidden or locked. Its name and note may still change. -fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { +/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on +/// locked artboards. Names and notes may still change. +fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); - d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) { + Some("a layer it is in is hidden or locked") + } else if on_locked_artboard(h, st, item.id) { + Some("it is on a locked artboard") + } else { + None + }; + why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why)) }); match refused { - Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))), None => Ok(()), } } @@ -1619,7 +1626,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1629,7 +1636,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1657,7 +1664,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { (now, keeps_other) }); if now.is_none() || keeps_other { - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; } set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } @@ -1741,7 +1748,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); @@ -1778,7 +1786,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { @@ -2024,7 +2033,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused, and so is an object in a hidden or locked layer. +/// compound path is refused. The item must be selectable and outside hidden or locked layers and +/// locked artboards. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -2037,7 +2047,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..9687a4a94f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1325,6 +1325,54 @@ fn duplicate_refuses_hidden_or_locked_art() { assert!(order.contains(&a) && order.contains(&b)); } +#[test] +fn setters_refuse_art_on_a_locked_artboard() { + let (mut s, _, _) = doc(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], refused = [];\ + var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\ + function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\ + function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\ + for(var i=0;i