From 54a6a92878b457207a4323613bc0ef00ff9f05fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 04:09:45 -0800 Subject: [PATCH 01/15] Document Tools: Flood Fill Artboards adds an artboard-sized rectangle on its own layer Object > Plug-ins > Document Tools > Flood Fill Artboards... opens a dialog that previews on the canvas and, on OK, runs the new command addon.document.floodFillArtboards as one undo step. The command adds an editable rectangle exactly the size of the active artboard, of listed artboards or of every artboard, painted with the current fill or a given color and no stroke. The rectangles go on top of a top-level layer named "Flood Fill" (or the name given), which is made at the bottom of the layers when the document has none. A layer that already exists keeps its lock and visibility, and the current layer stays as it was. Every given value is checked: null, wrong types, an empty or too long layer name, a color with alpha, unknown artboards, and artboards together with all are errors. A current fill of None without a color is an error. In a preview, the current fill is the one the preview began with. Docs: docs/mcp.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/document.rs | 13 +- .../src/cmd/addons/document/flood_fill.rs | 106 ++++++++++++++ .../engine/src/cmd/addons/document/tests.rs | 131 ++++++++++++++++++ crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/dialogs.rs | 3 +- crates/ui-egui/src/addons/document.rs | 81 ++++++++++- crates/ui-egui/src/addons/document/tests.rs | 108 +++++++++++++++ docs/mcp.md | 16 +++ 9 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/addons/document/flood_fill.rs diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..62474e4b3d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -166,6 +166,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke, on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility. A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 68681b50fa..dd20305a2d 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -2,10 +2,12 @@ //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a //! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces -//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! each image of a folder and saves the results to another ([`batch_trace`], #4921); Flood Fill +//! Artboards puts an artboard-sized rectangle on a layer of its own ([`flood_fill`]). Its submenu //! (Object › Plug-ins › Document Tools) is the UI's. mod batch_trace; +mod flood_fill; #[cfg(test)] mod tests; @@ -60,6 +62,15 @@ pub fn specs() -> Vec { has_doc, symbols_from_layers ), + cmd!( + "addon.document.floodFillArtboards", + "Flood Fill Artboards", + ["Object", "Plug-ins", "Document Tools"], + None, + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused; default: the current fill, in a preview the one the preview began with, an error when that is None), layer?: name (default: \"Flood Fill\"; at most 255 characters)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + super::super::maskedit::outside_mask_editing, + flood_fill::flood_fill_artboards + ), ] } diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs new file mode 100644 index 0000000000..a8214572da --- /dev/null +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -0,0 +1,106 @@ +//! Flood Fill Artboards (`addon.document.floodFillArtboards`): a rectangle exactly the size of each +//! chosen artboard, painted with the current fill or a given color and no stroke, on a layer kept +//! for these rectangles. The rectangles are editable art, unlike an artboard's background color +//! (`artboard.setProps {color}`), which is a property of the artboard. + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; +use vectorcraft_geom::{Affine, FillRule}; + +use super::super::super::layer::make_layer; +use super::super::super::newart::NewArt; +use super::super::super::panelcmds::listed_artboards; +use super::super::super::{bad, color_value}; +use crate::{Result, Session}; + +const COMMAND: &str = "addon.document.floodFillArtboards"; +/// The layer the rectangles go on when `layer` is left out. +const LAYER: &str = "Flood Fill"; +/// The longest layer name taken, in characters. +const MAX_NAME: usize = 255; + +/// `{artboards?, all?, color?, layer?}`: see the command's params text in [`super::specs`]. +pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(COMMAND, "the document has no artboards")); + } + let all = match p.get("all") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(COMMAND, "`all` must be true or false"))?, + }; + let boards = match p.get("artboards") { + Some(_) if all => return Err(bad(COMMAND, "give `artboards` or `all`, not both")), + Some(v) => listed_artboards(d, v, "artboards", COMMAND)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active_artboard(st)], + }; + // The current fill is the one an interaction in progress began with: a preview's selected + // rectangles may have given their color to the new-art paints since. + let current = st.interaction.as_ref().map_or(&s.paint.fill, |it| &it.paint.fill); + let fill = match p.get("color") { + Some(v) => Paint::solid(color_value(v).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), + None => match current { + Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), + paint => paint.clone(), + }, + }; + let name = match p.get("layer") { + None => LAYER.to_string(), + Some(v) => { + let name = v.as_str().map(str::trim).ok_or_else(|| bad(COMMAND, "`layer` must be a string"))?; + if name.is_empty() { + return Err(bad(COMMAND, "`layer` must not be empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(COMMAND, format!("`layer` must be at most {MAX_NAME} characters"))); + } + name.to_string() + } + }; + let rects: Vec<_> = boards.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.rect)).collect(); + let look = NewArt::plain(Appearance::basic(fill, Paint::None, 0.0)); + let (layer, created, ids) = s.edit("Flood Fill Artboards", |d, sel| { + let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())).map(|l| l.id); + let (layer, created) = match found { + Some(id) => (id, false), + // A new layer goes below every other, so the rectangles stay behind the art. + None => { + let n = make_layer(d, Some(&name)); + (d.insert(None, 0, n)?, true) + } + }; + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let live = LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }; + let path = live.to_path(); + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + // A reused layer keeps its lock and visibility; the rectangles on a locked or hidden one are + // not selected. + if d.node(layer).is_some_and(|l| l.visible && !l.locked) { + sel.set(ids.iter().copied()); + } + Ok((layer, created, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) +} + +/// The index of the view's active artboard ([`crate::DocState::active_artboard`]): when the +/// document no longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let at = |id: Option| id.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(st.doc.opened_artboard)).unwrap_or(0) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index d1bd77727d..1642a81196 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -195,6 +195,137 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() { assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); } +const FLOOD: &str = "addon.document.floodFillArtboards"; + +/// A document of three 100 × 80 artboards with one rectangle on `Layer 1`, and a red fill. +fn boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s +} + +/// The children of the layer `id`. +fn kids(s: &Session, id: u64) -> Vec> { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().to_vec() +} + +#[test] +fn flood_fill_covers_the_active_artboard_on_a_new_layer_at_the_bottom() { + let mut s = boards(); + let (current, steps) = (s.doc().unwrap().active_layer, s.doc().unwrap().history.undo.len()); + let before = s.doc().unwrap().doc.clone(); + let second = before.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let r = s.execute(FLOOD, &json!({})).unwrap(); + assert_eq!(r["created"], json!(true), "{r}"); + let st = s.doc().unwrap(); + let layer = &st.doc.layers[0]; + assert_eq!((layer.id.0, layer.name.as_deref()), (r["layer"].as_u64().unwrap(), Some("Flood Fill")), "a new layer below the others"); + assert_eq!(st.doc.layers.len(), 2); + let rects = kids(&s, layer.id.0); + assert_eq!(rects.len(), 1); + let rect = &rects[0]; + assert_eq!(r["ids"], json!([rect.id.0])); + assert_eq!(rect.geometric_bounds(), Some(second.rect), "exactly the active artboard"); + assert!(matches!(&rect.kind, NodeKind::Path { live: Some(live), .. } if matches!(**live, vectorcraft_doc::LiveShape::Rectangle { .. }))); + assert_eq!(rect.appearance.fill_paint(), s.paint.fill, "the current fill"); + assert_eq!(rect.appearance.stroke_paint(), vectorcraft_color::Paint::None, "no stroke"); + let st = s.doc().unwrap(); + assert_eq!((st.selection.objects.clone(), st.active_layer), (vec![rect.id], current), "the rectangle is selected; the current layer stays"); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + assert_eq!(st.history.undo.last().unwrap().label, "Flood Fill Artboards"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "undo removes the layer and the rectangle"); +} + +#[test] +fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { + let mut s = boards(); + let layer = s.execute(FLOOD, &json!({})).unwrap()["layer"].as_u64().unwrap(); + let first = s.doc().unwrap().doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer 1")).unwrap().id.0; + let art = kids(&s, first)[0].id.0; + s.execute("select.set", &json!({"ids": [art]})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "locked": true})).unwrap(); + let selected = s.doc().unwrap().selection.objects.clone(); + assert_eq!(selected.len(), 1); + let r = s.execute(FLOOD, &json!({"all": true, "color": "#00ff00"})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(layer)), "{r}"); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.locked && node.visible, "the layer stays locked"); + assert_eq!(st.doc.layers.len(), 2, "no second layer"); + assert_eq!(st.selection.objects, selected, "art on a locked layer is not selected"); + let rects = kids(&s, layer); + let added: Vec<_> = rects[1..].iter().map(|n| n.geometric_bounds().unwrap()).collect(); + let artboards: Vec<_> = st.doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(added, artboards, "one rectangle per artboard, on top of the layer's art"); + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + assert!(rects[1..].iter().all(|n| n.appearance.fill_paint() == green)); + // Hidden: the layer stays hidden, and listed artboards are filled once each, in order. + s.execute("layer.setProps", &json!({"id": layer, "locked": false, "visible": false})).unwrap(); + let r = s.execute(FLOOD, &json!({"artboards": [2, 0, 2]})).unwrap(); + let bounds = |id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + let new: Vec<_> = r["ids"].as_array().unwrap().iter().map(bounds).collect(); + assert_eq!(new, [artboards[0], artboards[2]]); + assert!(!s.doc().unwrap().doc.node(NodeId(layer)).unwrap().visible); + assert_eq!(s.doc().unwrap().selection.objects, selected, "art on a hidden layer is not selected"); + // A layer named by `layer`, found or made. + let r = s.execute(FLOOD, &json!({"layer": "Layer 1", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(first))); + let r = s.execute(FLOOD, &json!({"layer": " Paper "})).unwrap(); + assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); +} + +#[test] +fn flood_fill_refuses_bad_params_and_a_none_fill() { + let mut s = boards(); + let long = "x".repeat(256); + for p in [ + json!({"color": "#ff000080"}), + json!({"color": "red-ish"}), + json!({"color": null}), + json!({"artboards": [3]}), + json!({"artboards": []}), + json!({"artboards": null}), + json!({"artboards": [0.5]}), + json!({"all": null}), + json!({"all": "yes"}), + json!({"all": true, "artboards": [0]}), + json!({"layer": ""}), + json!({"layer": " "}), + json!({"layer": 5}), + json!({"layer": null}), + json!({"layer": long}), + ] { + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert!(s.execute(FLOOD, &p).is_err(), "{p}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute(FLOOD, &json!({})).unwrap_err().to_string(); + assert!(e.contains("the current fill is None"), "{e}"); + assert!(s.execute(FLOOD, &json!({"color": "#336699"})).is_ok(), "a given color needs no current fill"); +} + +/// With New Art Has Basic Appearance off, a preview in a color selects rectangles whose color the +/// new-art fill takes; a later preview without `color` still uses the fill the interaction began with. +#[test] +fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { + let mut s = boards(); + s.prefs.new_art_basic = false; + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..36d61a7401 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1030,6 +1030,9 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + ("addon.document.floodFillArtboards", json!({"artboards": [1e308, -1, null, u64::MAX], "color": [1e308]})), + ("addon.document.floodFillArtboards", json!({"all": true, "artboards": "x", "layer": {"name": 3}})), + ("addon.document.floodFillArtboards", json!({"color": {"c": f64::MAX, "m": -1e308, "y": 0, "k": 0}, "layer": "\u{0}"})), // Packaging Tools add-on. ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..9a251bd2d2 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -98,8 +98,9 @@ pub(crate) fn open( /// The dialog the menu item of command `id` opens, with no params; `None` for another command. pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option> { - use super::{color, pathtools, select, typetools}; + use super::{color, document, pathtools, select, typetools}; let open: fn(&mut VectorcraftApp) -> Result = match id { + document::FLOOD_FILL => document::open_flood_fill, pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, pathtools::bridge::COMMAND => pathtools::bridge::open, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 9fcf01e5c2..37be0c3cc8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -3,15 +3,20 @@ //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved //! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks //! for the folder the copies go in ([`export_all`], #4920). Batch Trace Folder asks for the folder of -//! images and then the folder the results go in ([`batch_trace`], #4921). +//! images and then the folder the results go in ([`batch_trace`], #4921). Flood Fill Artboards… +//! opens a dialog ([`open_flood_fill`]) that previews on the canvas and runs +//! `addon.document.floodFillArtboards` on OK. use craft::host::{PickRequest, Picked}; use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; +use super::dialogs::Spec; use crate::VectorcraftApp; use crate::file_asks::{Owner, ask}; -use crate::menus::{Sep, cp}; +use crate::menus::{Sep, c, cp}; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; @@ -21,6 +26,14 @@ pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; pub const BATCH_TRACE: &str = "addon.document.batchTraceFolder"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; +/// Flood Fill Artboards. +pub const FLOOD_FILL: &str = "addon.document.floodFillArtboards"; +/// The layer Flood Fill Artboards puts its rectangles on unless another is named. +const FLOOD_LAYER: &str = "Flood Fill"; +/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color. +const GRAY: [f32; 3] = [0.5, 0.5, 0.5]; + +static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None }; /// Object › Plug-ins › Document Tools. pub fn menu() -> Vec { @@ -32,9 +45,73 @@ pub fn menu() -> Vec { Sep, cp("New Symbols from Layers", SYMBOLS, json!({})), cp("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), + Sep, + c("Flood Fill Artboards…", FLOOD_FILL), ] } +/// The rows of the Flood Fill Artboards dialog. +fn flood_rows() -> Vec { + // Each choice opens on its first option. + let choice = |key: &str, label: &'static str, options: [(&str, &'static str); 2]| { + let default = options[0].0.to_string(); + let options = options.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect(); + Param::new(key, tl!(label), ParamKind::choice(options, Some(default))) + }; + vec![ + choice("artboards", "Artboards:", [("active", "Active Artboard"), ("all", "All Artboards")]), + choice("fill", "Fill:", [("current", "Current Fill"), ("color", "Color")]), + Param::new("color", tl!("Color:"), ParamKind::color(Some(GRAY))).enabled_when("fill", "color"), + Param::new("layer", tl!("Layer:"), ParamKind::text(FLOOD_LAYER)), + ] +} + +/// `#rrggbb` of an sRGB color with components from 0 to 1. +fn hex([r, g, b]: [f32; 3]) -> String { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b)) +} + +/// Flood Fill Artboards' params from the dialog: every artboard or the one the dialog opened on (`board`, kept +/// out of sight), the color only when Color is picked, and the layer named. +fn flood_params(fields: &DialogFields) -> Value { + let mut p = match fields.text("artboards") { + Some("all") => json!({ "all": true }), + _ => json!({ "artboards": [fields.int("board").unwrap_or(0)] }), + }; + if fields.text("fill") == Some("color") { + p["color"] = json!(hex(fields.color("color").unwrap_or(GRAY))); + } + p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); + p +} + +/// Opens Flood Fill Artboards' dialog on the active artboard and the current fill, or, when there is no fill, on +/// Color with gray. +pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { + let board = app.view().map_or(0, |v| v.artboard); + let fill = &app.session.paint.fill; + let color = fill.color().map_or(GRAY, |c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b].map(|v| f32::from(v) / 255.0) + }); + let fields = DialogFields::from_pairs([ + ("artboards", FieldValue::Text("active".into())), + ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), + ("color", FieldValue::Color(color)), + ("layer", FieldValue::Text(FLOOD_LAYER.into())), + ("board", FieldValue::Int(board as i64)), + ]); + super::dialogs::open(app, &FLOOD_SPEC, fields, |fields| { + let named = fields.text("layer").is_some_and(|name| !name.trim().is_empty()); + ParamDialog::new(FLOOD_FILL, tl!("Flood Fill Artboards"), flood_rows()) + .ok_enabled(named) + .ok_reason(tl!("Name the layer.").into()) + .values(Bind::bound(fields)) + .previews(true) + }) +} + /// The params as an object, with the picked folder under `key`. fn with_folder(p: &Value, key: &str, picked: &Picked) -> Result { let folder = picked.first_path().ok_or("no folder picked")?; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 1cc56d18cb..40a9985c38 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -4,6 +4,8 @@ use serde_json::json; use vectorcraft_engine::Session; use super::{BATCH_TRACE, EXPORT_ALL, SAVE_COPY}; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::tests::picks::{poll, scripted}; use crate::{VectorcraftApp, menus}; use craft::host::PickKind; @@ -237,3 +239,109 @@ fn batch_trace_folder_asks_for_both_folders() { assert_eq!(picker.requests().len(), asked + 1, "declining the source asks nothing more"); let _ = std::fs::remove_dir_all(&dir); } + +/// A window, a document of three 100 × 80 artboards with the second active, and a red fill. +fn boards() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + app.sync_views(); + if let Some(v) = app.view_mut() { + v.artboard = 1; + } + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app +} + +/// The names of the document's top-level layers, bottom first. +fn layer_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +/// The bounds and fill of each object on the bottom layer. +fn bottom_art(app: &VectorcraftApp) -> Vec<(vectorcraft_geom::Rect, vectorcraft_color::Paint)> { + let doc = &app.session.doc().unwrap().doc; + let art = doc.layers[0].children().map(|c| c.to_vec()).unwrap_or_default(); + art.iter().map(|n| (n.geometric_bounds().unwrap(), n.appearance.fill_paint())).collect() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn flood_fill_typed_layer_name_previews_and_ok_applies_one_step() { + let app = boards(); + let undo = undo_len(&app); + let artboard = app.session.doc().unwrap().doc.artboards[1].rect; + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + panel.click("Layer"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Paper"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + { + let app = panel.app(); + assert_eq!(layer_names(&app)[0], "Paper", "the preview makes the typed layer at the bottom"); + assert_eq!(bottom_art(&app), [(artboard, red.clone())], "the active artboard, in the current fill"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app), ["Paper", "Layer 1"]); + assert_eq!(bottom_art(&app), [(artboard, red)]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Flood Fill Artboards"); +} + +#[test] +fn flood_fill_cancel_rolls_the_preview_back() { + let app = boards(); + let (undo, doc) = (undo_len(&app), app.session.doc().unwrap().doc.clone()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + assert_eq!(layer_names(&panel.app())[0], "Flood Fill", "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!((*app.session.doc().unwrap().doc == *doc, undo_len(&app)), (true, undo), "nothing kept"); +} + +#[test] +fn flood_fill_all_artboards_in_a_chosen_color() { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "artboards", json!("all")); + assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); + host::set(&app, id, "fill", json!("color")); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params, json!({"all": true, "color": "#0000ff", "layer": "Flood Fill"})); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); + let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); + assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); +} + +#[test] +fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); + host::set(&app, id, "layer", json!(" ")); + assert!(!host::confirm(&app, id), "OK is off without a layer name"); + host::set(&app, id, "layer", json!("Back")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Back"); +} diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..287e858648 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17511,6 +17511,22 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` +`addon.document.floodFillArtboards {artboards?, all?, color?, layer?}` adds an editable rectangle exactly the size of +each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active +artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the +colors the paint commands take (`#rrggbbaa` and `#rgba` are refused); without it the rectangles take the current fill +(in a preview, the fill the preview began with), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by +default, at most 255 characters), which is made at the bottom of the layers when the document has none. A layer that +already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and +the current layer stays as it was. Null and values of the wrong type are errors; the command is refused while an +opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the +current fill or a color, and the layer, and previews on the canvas. → `{ids: [rectangle id…], layer, created}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{}}} +{"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{"all":true,"color":"#f4e9d8","layer":"Paper"}}} +``` + ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are From 1e31f9b94ccec4dd64c78dd94914cf62d2607daf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:45:42 -0800 Subject: [PATCH 02/15] Document Tools: Flood Fill Artboards refuses infinite colors and keeps the fill on Cancel - A color component too large for f32 (c: 1e308, [1e39, 0, 0], gray or Lab out of range) read as infinite and reached the rectangles; the command now refuses it with "bad color". - The dialog's Color option opened on the current fill in display sRGB and sent it as working RGB, so a document whose working RGB space is not sRGB got a shifted color. The dialog now opens on the fill's display color and converts the picked color back to working RGB. - With New Art Has Basic Appearance off and nothing selected, a previewed color gave the new rectangles' fill to the new-art paints, and Cancel or a replaced preview kept it. Both now put back the paints the interaction began with. Docs: docs/mcp.md. --- crates/engine/src/cmd/addons/document.rs | 2 +- .../src/cmd/addons/document/flood_fill.rs | 13 ++++- .../engine/src/cmd/addons/document/tests.rs | 42 ++++++++++++++ crates/engine/src/session/edit.rs | 9 ++- crates/ui-egui/src/addons/document.rs | 18 +++--- crates/ui-egui/src/addons/document/tests.rs | 56 ++++++++++++++----- docs/mcp.md | 2 +- 7 files changed, 113 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index dd20305a2d..3dcde0fd38 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused; default: the current fill, in a preview the one the preview began with, an error when that is None), layer?: name (default: \"Flood Fill\"; at most 255 characters)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, in a preview the one the preview began with, an error when that is None), layer?: name (default: \"Flood Fill\"; at most 255 characters)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", super::super::maskedit::outside_mask_editing, flood_fill::flood_fill_artboards ), diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index a8214572da..b4b63cbc19 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -4,7 +4,7 @@ //! (`artboard.setProps {color}`), which is a property of the artboard. use serde_json::{Value, json}; -use vectorcraft_color::Paint; +use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; use vectorcraft_geom::{Affine, FillRule}; @@ -41,7 +41,7 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result // rectangles may have given their color to the new-art paints since. let current = st.interaction.as_ref().map_or(&s.paint.fill, |it| &it.paint.fill); let fill = match p.get("color") { - Some(v) => Paint::solid(color_value(v).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), + Some(v) => Paint::solid(color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), None => match current { Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), paint => paint.clone(), @@ -98,6 +98,15 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) } +/// Whether every component of `c` is finite: a component too large for `f32` reads as infinite. +fn finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|v| v.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|v| v.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + /// The index of the view's active artboard ([`crate::DocState::active_artboard`]): when the /// document no longer has it, the artboard the document opened on, else the first. fn active_artboard(st: &crate::DocState) -> usize { diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 1642a81196..f50b1f26e5 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -303,6 +303,14 @@ fn flood_fill_refuses_bad_params_and_a_none_fill() { assert!(s.execute(FLOOD, &p).is_err(), "{p}"); assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); } + // Components too large for f32 become infinite once read. + for color in [json!({"c": 1e308, "m": 0, "y": 0, "k": 0}), json!([1e39, 0, 0]), json!({"gray": 1e41}), json!({"l": 1e39, "a": 0, "b": 0})] { + let p = json!({ "color": color }); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute(FLOOD, &p).unwrap_err().to_string(); + assert!(e.contains("bad color"), "{p}: {e}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } s.execute("paint.setFill", &json!({"none": true})).unwrap(); let e = s.execute(FLOOD, &json!({})).unwrap_err().to_string(); assert!(e.contains("the current fill is None"), "{e}"); @@ -326,6 +334,40 @@ fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); } +/// With New Art Has Basic Appearance off and nothing selected, a canceled preview in a color puts +/// back the new-art fill that its selected rectangles had given their color to. +#[test] +fn flood_fill_cancel_from_an_empty_selection_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "the cancel puts the new-art fill back"); + assert!(s.doc().unwrap().selection.is_empty()); +} + +#[test] +fn flood_fill_cancel_after_a_rejected_preview_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + assert!(s.doc().unwrap().selection.is_empty()); +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..61e62d0dd8 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -577,6 +577,7 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); + let inherits = !self.prefs.new_art_basic; let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -597,7 +598,8 @@ impl Session { || cmd == "command.batch" || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) - || it.color_mode_paints.is_some(); + || it.color_mode_paints.is_some() + || (inherits && it.preview.is_some() && it.selection.is_empty()); let paint = it.paint.clone(); it.preview_paint = None; it.color_mode_paints = None; @@ -767,6 +769,10 @@ impl Session { // it does a color previewed with `defaultsOnly: true`. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); + // With New Art Has Basic Appearance off, a preview that selected new art from an empty + // selection gave that art's appearance to the new-art paints; after the undo nothing is + // selected to take them from, so the cancel puts back the paints the interaction began with. + let inherits = !self.prefs.new_art_basic; if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -776,6 +782,7 @@ impl Session { || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() + || (inherits && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) { diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 37be0c3cc8..bab56e3edb 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -66,21 +66,22 @@ fn flood_rows() -> Vec { ] } -/// `#rrggbb` of an sRGB color with components from 0 to 1. -fn hex([r, g, b]: [f32; 3]) -> String { - let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b)) +/// The working-RGB components `[r, g, b]` of the dialog's display sRGB color, as the engine reads a +/// color array. +fn working_rgb(srgb: [f32; 3]) -> Value { + let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb(srgb.map(|v| v.clamp(0.0, 1.0))); + json!([r, g, b]) } /// Flood Fill Artboards' params from the dialog: every artboard or the one the dialog opened on (`board`, kept -/// out of sight), the color only when Color is picked, and the layer named. +/// out of sight), the color only when Color is picked (in the document's working RGB), and the layer named. fn flood_params(fields: &DialogFields) -> Value { let mut p = match fields.text("artboards") { Some("all") => json!({ "all": true }), _ => json!({ "artboards": [fields.int("board").unwrap_or(0)] }), }; if fields.text("fill") == Some("color") { - p["color"] = json!(hex(fields.color("color").unwrap_or(GRAY))); + p["color"] = working_rgb(fields.color("color").unwrap_or(GRAY)); } p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); p @@ -91,10 +92,7 @@ fn flood_params(fields: &DialogFields) -> Value { pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { let board = app.view().map_or(0, |v| v.artboard); let fill = &app.session.paint.fill; - let color = fill.color().map_or(GRAY, |c| { - let [r, g, b, _] = c.to_rgba8(1.0); - [r, g, b].map(|v| f32::from(v) / 255.0) - }); + let color = fill.color().map_or(GRAY, |c| c.to_rgb().map(|v| v.clamp(0.0, 1.0))); let fields = DialogFields::from_pairs([ ("artboards", FieldValue::Text("active".into())), ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 40a9985c38..88abf7931b 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -315,20 +315,48 @@ fn flood_fill_cancel_rolls_the_preview_back() { #[test] fn flood_fill_all_artboards_in_a_chosen_color() { - let mut app = boards(); - click(&mut app, "Flood Fill Artboards…"); - let id = host::dialog_id(&app); - host::set(&app, id, "artboards", json!("all")); - assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); - host::set(&app, id, "fill", json!("color")); - host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); - let params = host::read(&app, id, super::flood_params); - assert_eq!(params, json!({"all": true, "color": "#0000ff", "layer": "Flood Fill"})); - assert!(host::confirm(&app, id)); - host::frame(&mut app); - let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); - let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); - assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); + let srgb = std::sync::Arc::new(vectorcraft_color::cms::Cms::new(&Default::default()).unwrap()); + vectorcraft_color::cms::with_active(srgb, || { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "artboards", json!("all")); + assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); + host::set(&app, id, "fill", json!("color")); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params, json!({"all": true, "color": [0.0, 0.0, 1.0], "layer": "Flood Fill"})); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); + let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); + assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); + }); +} + +/// In a working RGB space other than sRGB, switching from Current Fill to Color without editing the +/// color fills the artboards in the current fill's color. +#[test] +fn flood_fill_color_keeps_the_current_fill_in_a_non_srgb_working_space() { + use vectorcraft_color::{Color, cms}; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + assert!(!cms::active().rgb_is_srgb()); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } + }); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 287e858648..c4224bdcdc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17514,7 +17514,7 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la `addon.document.floodFillArtboards {artboards?, all?, color?, layer?}` adds an editable rectangle exactly the size of each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the -colors the paint commands take (`#rrggbbaa` and `#rgba` are refused); without it the rectangles take the current fill +colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite); without it the rectangles take the current fill (in a preview, the fill the preview began with), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by default, at most 255 characters), which is made at the bottom of the layers when the document has none. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and From 6148b9aefdf4493417911b45a4b9e30da4654fd9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:29:54 -0800 Subject: [PATCH 03/15] Document Tools: Flood Fill Artboards keeps its dialog open for a clipping layer - The dialog's OK button stays off, with a reason, when the layer name matches a top-level layer that holds a clipping mask, which the command refuses. - A batch step takes the live fill, so paint.setFill followed by Flood Fill Artboards in one command.batch uses the new fill. - The OK check counts at most 255 characters after trimming, the same limit the command applies. --- ROADMAP.md | 2 +- crates/engine/src/cmd/addons/document.rs | 2 +- .../src/cmd/addons/document/flood_fill.rs | 13 ++++-- .../engine/src/cmd/addons/document/tests.rs | 44 ++++++++++++++++++ crates/ui-egui/src/addons/document.rs | 46 ++++++++++++++----- crates/ui-egui/src/addons/document/tests.rs | 39 ++++++++++++++++ docs/mcp.md | 7 +-- 7 files changed, 132 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 62474e4b3d..4879d6df29 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -166,7 +166,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. -- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke, on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility. A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke, on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 3dcde0fd38..b149a44da2 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, in a preview the one the preview began with, an error when that is None), layer?: name (default: \"Flood Fill\"; at most 255 characters)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", super::super::maskedit::outside_mask_editing, flood_fill::flood_fill_artboards ), diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index b4b63cbc19..3a698aae94 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -37,9 +37,10 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result None if all => (0..d.artboards.len()).collect(), None => vec![active_artboard(st)], }; - // The current fill is the one an interaction in progress began with: a preview's selected - // rectangles may have given their color to the new-art paints since. - let current = st.interaction.as_ref().map_or(&s.paint.fill, |it| &it.paint.fill); + // In Flood Fill's own preview the current fill is the one the interaction began with: a + // preview's selected rectangles may have given their color to the new-art paints since. A + // batch step takes the live fill, as the steps before it left it. + let current = st.interaction.as_ref().filter(|_| s.previewing && s.batch_stash.is_none()).map_or(&s.paint.fill, |it| &it.paint.fill); let fill = match p.get("color") { Some(v) => Paint::solid(color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), None => match current { @@ -60,10 +61,14 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result name.to_string() } }; + let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())); + if found.is_some_and(|l| l.clips()) { + return Err(bad(COMMAND, "the destination layer holds a clipping mask")); + } + let found = found.map(|l| l.id); let rects: Vec<_> = boards.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.rect)).collect(); let look = NewArt::plain(Appearance::basic(fill, Paint::None, 0.0)); let (layer, created, ids) = s.edit("Flood Fill Artboards", |d, sel| { - let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())).map(|l| l.id); let (layer, created) = match found { Some(id) => (id, false), // A new layer goes below every other, so the rectangles stay behind the art. diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index f50b1f26e5..038bffa653 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -278,6 +278,50 @@ fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); } +#[test] +fn flood_fill_in_a_batch_uses_the_fill_set_by_an_earlier_step() { + for none in [false, true] { + for preview in [false, true] { + let mut s = boards(); + if none { + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + } + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + let params = json!({"commands": [ + {"command": "paint.setFill", "params": {"color": "#00ff00"}}, + {"command": FLOOD, "params": {}} + ]}); + let r = if preview { + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview("command.batch", ¶ms).unwrap(); + let r = s.preview("command.batch", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + r + } else { + s.execute("command.batch", ¶ms).unwrap() + }; + let id = NodeId(r["results"][1]["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), green, "initial fill None: {none}, batch preview: {preview}"); + } + } +} + +#[test] +fn flood_fill_rejects_a_destination_layer_with_a_clipping_mask_without_an_edit() { + let mut s = boards(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + let error = s.execute(FLOOD, &json!({"layer": " Layer 1 "})).unwrap_err().to_string(); + assert!(error.contains("destination layer holds a clipping mask"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); +} + #[test] fn flood_fill_refuses_bad_params_and_a_none_fill() { let mut s = boards(); diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index bab56e3edb..0c1d84b015 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -52,15 +52,20 @@ pub fn menu() -> Vec { /// The rows of the Flood Fill Artboards dialog. fn flood_rows() -> Vec { - // Each choice opens on its first option. - let choice = |key: &str, label: &'static str, options: [(&str, &'static str); 2]| { - let default = options[0].0.to_string(); - let options = options.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect(); - Param::new(key, tl!(label), ParamKind::choice(options, Some(default))) - }; vec![ - choice("artboards", "Artboards:", [("active", "Active Artboard"), ("all", "All Artboards")]), - choice("fill", "Fill:", [("current", "Current Fill"), ("color", "Color")]), + Param::new( + "artboards", + tl!("Artboards:"), + ParamKind::choice( + vec![("active".into(), tl!("Active Artboard").into()), ("all".into(), tl!("All Artboards").into())], + Some("active".into()), + ), + ), + Param::new( + "fill", + tl!("Fill:"), + ParamKind::choice(vec![("current".into(), tl!("Current Fill").into()), ("color".into(), tl!("Color").into())], Some("current".into())), + ), Param::new("color", tl!("Color:"), ParamKind::color(Some(GRAY))).enabled_when("fill", "color"), Param::new("layer", tl!("Layer:"), ParamKind::text(FLOOD_LAYER)), ] @@ -100,11 +105,28 @@ pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result ("layer", FieldValue::Text(FLOOD_LAYER.into())), ("board", FieldValue::Int(board as i64)), ]); - super::dialogs::open(app, &FLOOD_SPEC, fields, |fields| { - let named = fields.text("layer").is_some_and(|name| !name.trim().is_empty()); + let mut layer_clips = std::collections::HashMap::new(); + if let Ok(st) = app.session.doc() { + for layer in st.doc.layers.iter().filter(|layer| layer.is_layer()) { + if let Some(name) = &layer.name { + layer_clips.entry(name.clone()).or_insert_with(|| layer.clips()); + } + } + } + super::dialogs::open(app, &FLOOD_SPEC, fields, move |fields| { + let name = fields.text("layer").unwrap_or_default().trim(); + let reason = if name.is_empty() { + Some(tl!("Name the layer.")) + } else if name.chars().count() > 255 { + Some(tl!("Use at most 255 characters for the layer name.")) + } else if layer_clips.get(name) == Some(&true) { + Some(tl!("The layer holds a clipping mask.")) + } else { + None + }; ParamDialog::new(FLOOD_FILL, tl!("Flood Fill Artboards"), flood_rows()) - .ok_enabled(named) - .ok_reason(tl!("Name the layer.").into()) + .ok_enabled(reason.is_none()) + .ok_reason(reason.unwrap_or_default().into()) .values(Bind::bound(fields)) .previews(true) }) diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 88abf7931b..01e23b70f0 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -359,6 +359,45 @@ fn flood_fill_color_keeps_the_current_fill_in_a_non_srgb_working_space() { }); } +#[test] +fn flood_fill_layer_name_limit_counts_characters_after_trimming() { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("é".repeat(256))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + let name = "é".repeat(255); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], name); +} + +#[test] +fn flood_fill_rejects_a_layer_with_a_clipping_mask_and_keeps_the_dialog_open() { + let mut app = boards(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.clippingMask.toggle", json!({"id": layer.0})).unwrap(); + assert!(app.session.doc().unwrap().doc.node(layer).unwrap().clips()); + let name = app.session.doc().unwrap().doc.node(layer).unwrap().name.clone().unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some(format!(" {name} "))); + host::set(&app, id, "layer", json!("Paper")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); +} + #[test] fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { let mut app = boards(); diff --git a/docs/mcp.md b/docs/mcp.md index c4224bdcdc..62dbfc6ba9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17515,12 +17515,13 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite); without it the rectangles take the current fill -(in a preview, the fill the preview began with), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by -default, at most 255 characters), which is made at the bottom of the layers when the document has none. A layer that +(in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by +default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. Null and values of the wrong type are errors; the command is refused while an opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the -current fill or a color, and the layer, and previews on the canvas. → `{ids: [rectangle id…], layer, created}` +current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong +trimmed layer name. → `{ids: [rectangle id…], layer, created}` ```json {"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{}}} From cd4253e52c34a993a84ffaf8ea1ea96801738630 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:44:00 -0800 Subject: [PATCH 04/15] Document Tools: Flood Fill Artboards refuses editing modes and bad params - Flood Fill Artboards is disabled, and refused, while a symbol or a pattern is edited, so the rectangles never land in a definition. - Params that are not an object or null are refused, also when an action.batch step is checked before it runs. - The dialog keeps OK off, with a reason, when Current Fill is chosen and there is no current fill. - With New Art Has Basic Appearance off and nothing selected, a paint preview that is replaced or canceled puts back the starting paints, so two paint.swap previews commit one swap, while a preview that takes its paints from new art it selected is tracked on its own. --- crates/engine/src/cmd/addons/document.rs | 16 +- .../src/cmd/addons/document/flood_fill.rs | 6 + .../engine/src/cmd/addons/document/tests.rs | 165 ++++++++++++++++++ crates/engine/src/cmd/newart.rs | 6 + crates/engine/src/cmd/params.rs | 3 + crates/engine/src/interaction.rs | 2 + crates/engine/src/session/edit.rs | 11 +- crates/ui-egui/src/addons/document.rs | 3 + crates/ui-egui/src/addons/document/tests.rs | 22 +++ docs/mcp.md | 8 +- 10 files changed, 233 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index b149a44da2..1fa433c692 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,13 +67,25 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", - super::super::maskedit::outside_mask_editing, + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + flood_fill_enabled, flood_fill::flood_fill_artboards ), ] } +fn flood_fill_enabled(s: &Session) -> std::result::Result<(), String> { + super::super::maskedit::outside_mask_editing(s)?; + let st = s.active().ok_or("no document open")?; + if st.doc.symbol_edit.is_some() { + return Err("finish editing the symbol before filling artboards".into()); + } + if st.doc.pattern_edit.is_some() { + return Err("finish editing the pattern before filling artboards".into()); + } + Ok(()) +} + /// A document is open and the time can be told. fn has_clock(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index 3a698aae94..b0d63420bb 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -24,6 +24,12 @@ const MAX_NAME: usize = 255; pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let d = &st.doc; + if d.symbol_edit.is_some() { + return Err(bad(COMMAND, "finish editing the symbol before filling artboards")); + } + if d.pattern_edit.is_some() { + return Err(bad(COMMAND, "finish editing the pattern before filling artboards")); + } if d.artboards.is_empty() { return Err(bad(COMMAND, "the document has no artboards")); } diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 038bffa653..c6ce4e6241 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -322,6 +322,95 @@ fn flood_fill_rejects_a_destination_layer_with_a_clipping_mask_without_an_edit() assert_eq!(s.paint, before.3); } +#[test] +fn flood_fill_refuses_symbol_and_pattern_editing_without_an_edit() { + for symbol in [true, false] { + let mut s = boards(); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let st = s.doc().unwrap(); + let layer = if symbol { st.doc.symbol_edit.as_ref().unwrap().layer } else { st.doc.pattern_edit.as_ref().unwrap().layer }; + let name = st.doc.node(layer).unwrap().name.clone().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + for params in [json!({}), json!({"layer": name}), json!({"layer": "Paper"})] { + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" }), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + } +} + +#[test] +fn flood_fill_is_disabled_while_editing_symbols_or_patterns() { + let spec = crate::find_command(FLOOD).unwrap(); + for symbol in [true, false] { + let mut s = boards(); + assert!(spec.info(&s).enabled); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let info = spec.info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" })); + } +} + +#[test] +fn flood_fill_action_batch_rejects_non_object_params_at_preflight() { + let mut s = boards(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let batch = json!({"commands": [{"command": FLOOD, "params": params}]}); + for error in [s.check_params("action.batch", &batch).unwrap_err(), s.execute("action.batch", &batch).unwrap_err()] { + let error = error.to_string(); + assert!(error.contains("action step 1 (`addon.document.floodFillArtboards`)"), "{error}"); + assert!(error.contains("params must be an object or null"), "{error}"); + } + assert_eq!(*s.doc().unwrap().doc, *before.0); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + assert_eq!(s.paint, before.2); + } +} + +#[test] +fn flood_fill_requires_object_or_null_params_directly_and_in_a_batch() { + for batch in [false, true] { + let mut s = boards(); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD, "params": params}]})) + } else { + s.execute(FLOOD, ¶ms) + }; + assert!(result.is_err(), "batch: {batch}, params: {params}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD}]})).unwrap()["results"][0].clone() + } else { + s.execute(FLOOD, &Value::Null).unwrap() + }; + assert_eq!(result["ids"].as_array().unwrap().len(), 1); + } +} + #[test] fn flood_fill_refuses_bad_params_and_a_none_fill() { let mut s = boards(); @@ -378,6 +467,82 @@ fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); } +#[test] +fn paint_swap_previews_from_an_empty_selection_commit_one_swap() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let before = s.paint.clone(); + assert_ne!(before.fill, before.stroke); + s.begin_interaction("Swap").unwrap(); + for _ in 0..2 { + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + } + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_preview_replacement_from_an_empty_selection_uses_the_starting_defaults() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, before.fill); + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_previews_from_an_empty_selection_restore_defaults_on_cancel() { + for (command, params) in [ + ("paint.swap", json!({})), + ("paint.setFill", json!({"color": "#0000ff"})), + ("paint.setStroke", json!({"color": "#0000ff"})), + ] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview(command, ¶ms).unwrap(); + assert_ne!(s.paint, before, "{command}"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint, before, "{command}"); + } +} + +#[test] +fn paint_preview_from_an_empty_selection_keeps_its_fill_for_the_next_step() { + for cancel in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Fill").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + assert!(s.doc().unwrap().selection.is_empty()); + if cancel { + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + } else { + let result = s.preview("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), blue); + assert_eq!(s.paint.fill, blue); + s.commit_interaction().unwrap(); + } + } +} + /// With New Art Has Basic Appearance off and nothing selected, a canceled preview in a color puts /// back the new-art fill that its selected rectangles had given their color to. #[test] diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index f43221120c..09c56e1473 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -235,6 +235,12 @@ impl Session { if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) { return; } + if self.previewing + && let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) + && it.selection.is_empty() + { + it.inherited_preview_paint = true; + } let NewArtSource { appearance, opacity, blend, style, .. } = source; let kept_fill = fill.then(|| self.paint.fill.clone()); let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width)); diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index dcc3eade04..6600530719 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -1089,6 +1089,9 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { /// `command.batch` or `action.batch` step aren't checked (running it reports that), however deep they go. fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; + if id == "addon.document.floodFillArtboards" && !params.is_null() && !params.is_object() { + return Err(bad(id, "params must be an object or null")); + } if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = (id, super::effectcmd::requested_effect(params), params.get("params")) { diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index a2b9417461..5b28071e55 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -20,6 +20,8 @@ pub struct Interaction { /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put /// `paint` back, whichever preview is the latest. pub(crate) used_defaults_only: bool, + /// The preview inherited new-art paints from a selection absent at interaction start. + pub(crate) inherited_preview_paint: bool, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 61e62d0dd8..b7cfe25e0e 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -549,6 +549,7 @@ impl Session { tool: false, paint, used_defaults_only: false, + inherited_preview_paint: false, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -577,7 +578,7 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let inherits = !self.prefs.new_art_basic; + let new_art_basic = self.prefs.new_art_basic; let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -599,8 +600,10 @@ impl Session { || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() - || (inherits && it.preview.is_some() && it.selection.is_empty()); + || it.inherited_preview_paint + || (!new_art_basic && it.selection.is_empty() && it.preview.is_some() && cmd.starts_with("paint.")); let paint = it.paint.clone(); + it.inherited_preview_paint = false; it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -772,7 +775,6 @@ impl Session { // With New Art Has Basic Appearance off, a preview that selected new art from an empty // selection gave that art's appearance to the new-art paints; after the undo nothing is // selected to take them from, so the cancel puts back the paints the interaction began with. - let inherits = !self.prefs.new_art_basic; if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -782,7 +784,8 @@ impl Session { || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() - || (inherits && it.preview.is_some() && it.selection.is_empty()) + || it.inherited_preview_paint + || (!self.prefs.new_art_basic && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) { diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 0c1d84b015..eedb5ef60a 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -97,6 +97,7 @@ fn flood_params(fields: &DialogFields) -> Value { pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { let board = app.view().map_or(0, |v| v.artboard); let fill = &app.session.paint.fill; + let no_current_fill = fill.is_none(); let color = fill.color().map_or(GRAY, |c| c.to_rgb().map(|v| v.clamp(0.0, 1.0))); let fields = DialogFields::from_pairs([ ("artboards", FieldValue::Text("active".into())), @@ -121,6 +122,8 @@ pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result Some(tl!("Use at most 255 characters for the layer name.")) } else if layer_clips.get(name) == Some(&true) { Some(tl!("The layer holds a clipping mask.")) + } else if no_current_fill && fields.text("fill") == Some("current") { + Some(tl!("There is no current fill.")) } else { None }; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 01e23b70f0..4f71e746a6 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -398,6 +398,28 @@ fn flood_fill_rejects_a_layer_with_a_clipping_mask_and_keeps_the_dialog_open() { assert_eq!(layer_names(&app)[0], "Paper"); } +#[test] +fn flood_fill_current_fill_without_a_fill_keeps_the_dialog_open() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("Paper")); + host::set(&app, id, "fill", json!("current")); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some("Paper".to_owned())); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before + 1); +} + #[test] fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { let mut app = boards(); diff --git a/docs/mcp.md b/docs/mcp.md index 62dbfc6ba9..0776548e6a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17518,10 +17518,12 @@ colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a com (in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and -the current layer stays as it was. Null and values of the wrong type are errors; the command is refused while an -opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the +the current layer stays as it was. Params must be an object or null (omitted options). Null option values and values +of the wrong type are errors. The command is refused while a symbol, pattern or opacity mask is edited. +The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong -trimmed layer name. → `{ids: [rectangle id…], layer, created}` +trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. +→ `{ids: [rectangle id…], layer, created}` ```json {"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{}}} From d2c2f669409df883f712f9e73e01bf7d04303c75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:19:09 -0800 Subject: [PATCH 05/15] Document Tools: Flood Fill Artboards respects isolation, color model and template layers - The command is disabled, and refused, while a group is isolated. - A chosen color goes into the document's color model as paint.setFill puts it, so a CMYK document gets a CMYK fill unless keepModel is set. - Rectangles added to a template layer are not selected, as on a locked or hidden layer. --- crates/engine/src/cmd/addons/document.rs | 5 +- .../src/cmd/addons/document/flood_fill.rs | 13 ++-- .../engine/src/cmd/addons/document/tests.rs | 60 +++++++++++++++++++ docs/mcp.md | 8 +-- 4 files changed, 77 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 1fa433c692..a2b5a56f14 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", flood_fill_enabled, flood_fill::flood_fill_artboards ), @@ -83,6 +83,9 @@ fn flood_fill_enabled(s: &Session) -> std::result::Result<(), String> { if st.doc.pattern_edit.is_some() { return Err("finish editing the pattern before filling artboards".into()); } + if st.isolation.is_some() { + return Err("exit isolation mode before filling artboards".into()); + } Ok(()) } diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index b0d63420bb..135a5076b0 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -30,6 +30,9 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result if d.pattern_edit.is_some() { return Err(bad(COMMAND, "finish editing the pattern before filling artboards")); } + if st.isolation.is_some() { + return Err(bad(COMMAND, "exit isolation mode before filling artboards")); + } if d.artboards.is_empty() { return Err(bad(COMMAND, "the document has no artboards")); } @@ -48,7 +51,10 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result // batch step takes the live fill, as the steps before it left it. let current = st.interaction.as_ref().filter(|_| s.previewing && s.batch_stash.is_none()).map_or(&s.paint.fill, |it| &it.paint.fill); let fill = match p.get("color") { - Some(v) => Paint::solid(color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), + Some(v) => { + let color = color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?; + Paint::solid(super::super::super::paint::new_color(s, p, color)) + } None => match current { Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), paint => paint.clone(), @@ -99,9 +105,8 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result look.apply(d, &mut n); ids.push(d.insert(Some(layer), usize::MAX, n)?); } - // A reused layer keeps its lock and visibility; the rectangles on a locked or hidden one are - // not selected. - if d.node(layer).is_some_and(|l| l.visible && !l.locked) { + // Rectangles on a locked, hidden or template layer are not selected. + if d.node(layer).is_some_and(|l| l.visible && !l.locked && !l.is_template()) { sel.set(ids.iter().copied()); } Ok((layer, created, ids)) diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index c6ce4e6241..d05661387c 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -278,6 +278,66 @@ fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); } +#[test] +fn flood_fill_preserves_selection_on_an_unlocked_template_layer() { + let mut s = boards(); + let art = s.doc().unwrap().selection.objects[0]; + let layer = s.execute("layer.new", &json!({"name": "Paper"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "template": true, "locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let st = s.doc().unwrap(); + let selected = st.selection.clone(); + assert!(!selected.objects.is_empty()); + let r = s.execute(FLOOD, &json!({"layer": "Paper", "all": true})).unwrap(); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.is_template() && node.visible && !node.locked); + assert_eq!(r["created"], json!(false)); + assert_eq!(r["layer"].as_u64(), Some(layer)); + assert_eq!(kids(&s, layer).len(), st.doc.artboards.len()); + assert_eq!(st.selection, selected); +} + +#[test] +fn flood_fill_converts_explicit_rgb_to_cmyk_like_set_fill() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let expected = s.paint.fill.clone(); + assert!(matches!(expected.color(), Some(vectorcraft_color::Color::Cmyk { .. }))); + for color in [json!("#ff0000"), json!([1.0, 0.0, 0.0])] { + let r = s.execute(FLOOD, &json!({"color": color})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, expected); + } +} + +#[test] +fn flood_fill_refuses_isolation_without_an_edit_and_is_disabled() { + let mut s = boards(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.isolation, Some(NodeId(group))); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let info = crate::find_command(FLOOD).unwrap().info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains("exit isolation mode")); + for params in [json!({}), json!({"layer": "Layer 1"}), json!({"layer": "Paper", "all": true})] { + let error = super::flood_fill::flood_fill_artboards(&mut s, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(st.isolation, Some(NodeId(group))); + } +} + #[test] fn flood_fill_in_a_batch_uses_the_fill_set_by_an_earlier_step() { for none in [false, true] { diff --git a/docs/mcp.md b/docs/mcp.md index 0776548e6a..a8d17b40da 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17514,12 +17514,12 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la `addon.document.floodFillArtboards {artboards?, all?, color?, layer?}` adds an editable rectangle exactly the size of each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the -colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite); without it the rectangles take the current fill +colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite). Explicit RGB colors convert to the document's color model as `paint.setFill` does. Without `color`, the rectangles take the current fill (in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that -already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and -the current layer stays as it was. Params must be an object or null (omitted options). Null option values and values -of the wrong type are errors. The command is refused while a symbol, pattern or opacity mask is edited. +already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked, hidden or a template, +in which case the prior selection stays. The current layer stays as it was. Params must be an object or null (omitted options). Null option values and values +of the wrong type are errors. The command is refused in isolation mode or while a symbol, pattern or opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. From 9d3d9bde7653650bf00479451e2e231a3c8d24d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:26:32 -0800 Subject: [PATCH 06/15] Document Tools: Flood Fill Artboards takes keepModel - `keepModel: true` keeps an explicit RGB color in RGB in a CMYK document, as paint.setFill does; it is declared in the params text, docs/mcp.md and ROADMAP. - A `keepModel` of null or another non-boolean is an error, and nothing is edited. --- ROADMAP.md | 2 +- crates/engine/src/cmd/addons/document.rs | 2 +- .../src/cmd/addons/document/flood_fill.rs | 6 ++++- .../engine/src/cmd/addons/document/tests.rs | 24 +++++++++++++++---- docs/mcp.md | 4 ++-- 5 files changed, 28 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 4879d6df29..4c6d24971e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -166,7 +166,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. -- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke, on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke (a chosen RGB color goes into the document's color model, or stays RGB with `keepModel`), on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index a2b5a56f14..51f4aad3df 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), keepModel?: bool (as paint.setFill: true keeps an explicit RGB color in RGB), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", flood_fill_enabled, flood_fill::flood_fill_artboards ), diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index 135a5076b0..ad5a5108cb 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -20,7 +20,7 @@ const LAYER: &str = "Flood Fill"; /// The longest layer name taken, in characters. const MAX_NAME: usize = 255; -/// `{artboards?, all?, color?, layer?}`: see the command's params text in [`super::specs`]. +/// `{artboards?, all?, color?, keepModel?, layer?}`: see the command's params text in [`super::specs`]. pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let d = &st.doc; @@ -36,6 +36,10 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result if d.artboards.is_empty() { return Err(bad(COMMAND, "the document has no artboards")); } + if p.get("keepModel").is_some_and(Value::is_null) { + return Err(bad(COMMAND, "`keepModel` must be true or false")); + } + super::super::super::paint::check_keep_model(p, COMMAND)?; let all = match p.get("all") { None => false, Some(v) => v.as_bool().ok_or_else(|| bad(COMMAND, "`all` must be true or false"))?, diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index d05661387c..b4b2ff66e8 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -313,6 +313,22 @@ fn flood_fill_converts_explicit_rgb_to_cmyk_like_set_fill() { } } +#[test] +fn flood_fill_keep_model_keeps_explicit_rgb_in_a_cmyk_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + let r = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert!(matches!(fill.color(), Some(vectorcraft_color::Color::Rgb { .. })), "{fill:?}"); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [json!("yes"), json!(null)] { + let error = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": bad})).unwrap_err().to_string(); + assert!(error.contains("keepModel"), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + #[test] fn flood_fill_refuses_isolation_without_an_edit_and_is_disabled() { let mut s = boards(); @@ -561,11 +577,9 @@ fn paint_preview_replacement_from_an_empty_selection_uses_the_starting_defaults( #[test] fn paint_previews_from_an_empty_selection_restore_defaults_on_cancel() { - for (command, params) in [ - ("paint.swap", json!({})), - ("paint.setFill", json!({"color": "#0000ff"})), - ("paint.setStroke", json!({"color": "#0000ff"})), - ] { + for (command, params) in + [("paint.swap", json!({})), ("paint.setFill", json!({"color": "#0000ff"})), ("paint.setStroke", json!({"color": "#0000ff"}))] + { let mut s = boards(); s.prefs.new_art_basic = false; s.execute("select.none", &json!({})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index a8d17b40da..f57abb7d58 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17511,10 +17511,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` -`addon.document.floodFillArtboards {artboards?, all?, color?, layer?}` adds an editable rectangle exactly the size of +`addon.document.floodFillArtboards {artboards?, all?, color?, keepModel?, layer?}` adds an editable rectangle exactly the size of each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the -colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite). Explicit RGB colors convert to the document's color model as `paint.setFill` does. Without `color`, the rectangles take the current fill +colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite). Explicit RGB colors convert to the document's color model as `paint.setFill` does, and `keepModel: true` keeps them in RGB. Without `color`, the rectangles take the current fill (in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked, hidden or a template, From 07ab97addc476309c964a479136a7bf177c102d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:27:30 -0800 Subject: [PATCH 07/15] Document Tools: Flood Fill Artboards checks params on replay and keeps the defaults on Cancel - Params that are not an object or null are an error on journal and action replay as well as in a batch. - A call without `artboards` or `all` records the artboard it filled as `activeArtboard` for a journal replay; a recorded action leaves it out, so playing the action fills the artboard active then. - The command is disabled when the document has no artboards. - Canceling a Flood Fill preview puts back the new-art paints it began with instead of taking them from the selection. --- crates/engine/src/cmd/addons/document.rs | 5 +- .../src/cmd/addons/document/flood_fill.rs | 16 ++- .../engine/src/cmd/addons/document/tests.rs | 133 ++++++++++++++++++ crates/engine/src/command_sets.rs | 3 +- crates/engine/src/interaction.rs | 3 + crates/engine/src/session/edit.rs | 6 +- docs/mcp.md | 10 +- 7 files changed, 168 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 51f4aad3df..167cc4a9d1 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Flood Fill Artboards", ["Object", "Plug-ins", "Document Tools"], None, - "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), keepModel?: bool (as paint.setFill: true keeps an explicit RGB color in RGB), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option given is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), activeArtboard?: n (0-based index of an existing artboard; the journal records that default here, for a replay; takes precedence over the view's active artboard; ignored when artboards is given or all is true; omitted from recorded actions), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), keepModel?: bool (as paint.setFill: true keeps an explicit RGB color in RGB), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option used is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", flood_fill_enabled, flood_fill::flood_fill_artboards ), @@ -77,6 +77,9 @@ pub fn specs() -> Vec { fn flood_fill_enabled(s: &Session) -> std::result::Result<(), String> { super::super::maskedit::outside_mask_editing(s)?; let st = s.active().ok_or("no document open")?; + if st.doc.artboards.is_empty() { + return Err("the document has no artboards".into()); + } if st.doc.symbol_edit.is_some() { return Err("finish editing the symbol before filling artboards".into()); } diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs index ad5a5108cb..349cb65455 100644 --- a/crates/engine/src/cmd/addons/document/flood_fill.rs +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -20,8 +20,11 @@ const LAYER: &str = "Flood Fill"; /// The longest layer name taken, in characters. const MAX_NAME: usize = 255; -/// `{artboards?, all?, color?, keepModel?, layer?}`: see the command's params text in [`super::specs`]. +/// `{artboards?, all?, activeArtboard?, color?, keepModel?, layer?}`: see the command's params text in [`super::specs`]. pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { + if !p.is_null() && !p.is_object() { + return Err(bad(COMMAND, "params must be an object or null")); + } let st = s.doc()?; let d = &st.doc; if d.symbol_edit.is_some() { @@ -48,7 +51,13 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result Some(_) if all => return Err(bad(COMMAND, "give `artboards` or `all`, not both")), Some(v) => listed_artboards(d, v, "artboards", COMMAND)?, None if all => (0..d.artboards.len()).collect(), - None => vec![active_artboard(st)], + None => vec![match p.get("activeArtboard") { + Some(v) => { + let i = v.as_u64().ok_or_else(|| bad(COMMAND, "`activeArtboard` must be a whole number"))?; + usize::try_from(i).ok().filter(|i| *i < d.artboards.len()).ok_or_else(|| bad(COMMAND, "no such artboard"))? + } + None => active_artboard(st), + }], }; // In Flood Fill's own preview the current fill is the one the interaction began with: a // preview's selected rectangles may have given their color to the new-art paints since. A @@ -115,6 +124,9 @@ pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result } Ok((layer, created, ids)) })?; + if p.get("artboards").is_none() && !all { + s.note_journal("activeArtboard", json!(boards[0])); + } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) } diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index b4b2ff66e8..c0e2e0e894 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -240,6 +240,66 @@ fn flood_fill_covers_the_active_artboard_on_a_new_layer_at_the_bottom() { assert_eq!(*s.doc().unwrap().doc, *before, "undo removes the layer and the rectangle"); } +#[test] +fn flood_fill_journal_replays_the_resolved_active_artboard() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + s.execute(FLOOD, ¶ms).unwrap(); + let (command, params) = s.journal.last().unwrap().clone(); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + let mut replay = boards(); + let first = replay.doc().unwrap().doc.artboards[0].id; + replay.doc_mut().unwrap().active_artboard = Some(first); + let r = replay.replay(&command, ¶ms).unwrap(); + let rects = kids(&replay, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(second.rect)); + } +} + +#[test] +fn flood_fill_action_uses_the_active_artboard_when_played() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let start = s.journal.len(); + s.execute(FLOOD, ¶ms).unwrap(); + let action = s.journal_for_action(start); + assert_eq!(action.len(), 1); + let (command, params) = &action[0]; + assert!(params.get("artboards").is_none()); + assert!(params.get("activeArtboard").is_none()); + let mut playback = boards(); + let third = playback.doc().unwrap().doc.artboards[2].clone(); + playback.doc_mut().unwrap().active_artboard = Some(third.id); + let r = playback.execute(command, params).unwrap(); + let rects = kids(&playback, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(third.rect)); + } +} + +#[test] +fn flood_fill_explicit_targets_override_the_replay_artboard_and_stay_in_actions() { + for params in [json!({"artboards": [2], "activeArtboard": null}), json!({"all": true, "activeArtboard": 99})] { + let mut s = boards(); + let start = s.journal.len(); + let r = s.execute(FLOOD, ¶ms).unwrap(); + let rects = kids(&s, r["layer"].as_u64().unwrap()); + let indices = if params.get("artboards").is_some() { vec![2] } else { vec![0, 1, 2] }; + let expected: Vec<_> = indices.iter().map(|i| s.doc().unwrap().doc.artboards[*i].rect).collect(); + assert_eq!(rects.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(), expected); + let action = s.journal_for_action(start); + assert_eq!(action[0].1.get("artboards"), params.get("artboards")); + assert_eq!(action[0].1.get("all"), params.get("all")); + assert!(action[0].1.get("activeArtboard").is_none()); + } +} + #[test] fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { let mut s = boards(); @@ -442,6 +502,22 @@ fn flood_fill_is_disabled_while_editing_symbols_or_patterns() { } } +#[test] +fn flood_fill_is_disabled_without_artboards() { + let mut s = boards(); + let spec = crate::find_command(FLOOD).unwrap(); + assert!(spec.info(&s).enabled); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + let info = spec.info(&s); + assert!(!info.enabled); + assert_eq!(info.disabled_reason.as_deref(), Some("the document has no artboards")); + let before = s.doc().unwrap().doc.clone(); + for params in [json!({}), json!({"all": true})] { + assert!(s.execute(FLOOD, ¶ms).unwrap_err().to_string().contains("the document has no artboards")); + assert_eq!(*s.doc().unwrap().doc, *before); + } +} + #[test] fn flood_fill_action_batch_rejects_non_object_params_at_preflight() { let mut s = boards(); @@ -487,6 +563,24 @@ fn flood_fill_requires_object_or_null_params_directly_and_in_a_batch() { } } +#[test] +fn flood_fill_replay_rejects_non_object_params_without_an_edit() { + let mut s = boards(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone(), s.journal.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let error = s.replay(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("params must be an object or null"), "{params}: {error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(s.journal, before.4); + } + assert_eq!(s.replay(FLOOD, &Value::Null).unwrap()["ids"].as_array().unwrap().len(), 1); +} + #[test] fn flood_fill_refuses_bad_params_and_a_none_fill() { let mut s = boards(); @@ -499,6 +593,13 @@ fn flood_fill_refuses_bad_params_and_a_none_fill() { json!({"artboards": []}), json!({"artboards": null}), json!({"artboards": [0.5]}), + json!({"activeArtboard": null}), + json!({"activeArtboard": "1"}), + json!({"activeArtboard": true}), + json!({"activeArtboard": -1}), + json!({"activeArtboard": 0.5}), + json!({"activeArtboard": 3}), + json!({"activeArtboard": u64::MAX}), json!({"all": null}), json!({"all": "yes"}), json!({"all": true, "artboards": [0]}), @@ -617,6 +718,38 @@ fn paint_preview_from_an_empty_selection_keeps_its_fill_for_the_next_step() { } } +#[test] +fn flood_fill_cancel_with_a_selection_preserves_the_opening_paint_defaults() { + for resume in [false, true] { + for params in [json!({}), json!({"color": "#00ff00"}), json!({"color": "invalid"})] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("paint.setFill", &json!({"color": "#0000ff", "defaultsOnly": true})).unwrap(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + assert!(!before.1.is_empty()); + assert_ne!(st.doc.node(before.1.objects[0]).unwrap().appearance.fill_paint(), before.3.fill); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#00ff00"})).unwrap(); + let result = s.preview(FLOOD, ¶ms); + assert_eq!(result.is_err(), params["color"] == "invalid"); + s.cancel_interaction().unwrap(); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + if resume { + s.begin_interaction("Flood Fill Artboards").unwrap(); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), before.3.fill); + } + } + } +} + /// With New Art Has Basic Appearance off and nothing selected, a canceled preview in a color puts /// back the new-art fill that its selected rectangles had given their color to. #[test] diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..5e7ef6189a 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -35,7 +35,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 35] = [ +const REPLAY_ONLY: [(&str, &str); 36] = [ ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -63,6 +63,7 @@ const REPLAY_ONLY: [(&str, &str); 35] = [ ("artboard.distribute", "activeArtboard"), ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), + ("addon.document.floodFillArtboards", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 5b28071e55..171f2adba0 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -20,6 +20,9 @@ pub struct Interaction { /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put /// `paint` back, whichever preview is the latest. pub(crate) used_defaults_only: bool, + /// A Flood Fill Artboards preview ran: a cancel puts `paint` back and does not take the + /// selection's appearance as the new-art paints. + pub(crate) preserve_paint_on_cancel: bool, /// The preview inherited new-art paints from a selection absent at interaction start. pub(crate) inherited_preview_paint: bool, /// An accepted batch preview uses these final paints after changing the document color mode. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index b7cfe25e0e..025cbb5258 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -549,6 +549,7 @@ impl Session { tool: false, paint, used_defaults_only: false, + preserve_paint_on_cancel: false, inherited_preview_paint: false, preview_paint: None, color_mode_paints: None, @@ -594,6 +595,7 @@ impl Session { // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); + it.preserve_paint_on_cancel |= cmd == "addon.document.floodFillArtboards"; it.tool_paints |= tool_paints; let restore_paint = it.tool_paints || cmd == "command.batch" @@ -772,6 +774,7 @@ impl Session { // it does a color previewed with `defaultsOnly: true`. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); + let preserve_paint = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preserve_paint_on_cancel); // With New Art Has Basic Appearance off, a preview that selected new art from an empty // selection gave that art's appearance to the new-art paints; after the undo nothing is // selected to take them from, so the cancel puts back the paints the interaction began with. @@ -782,6 +785,7 @@ impl Session { tool_paints || it.tool_paints || it.used_defaults_only + || it.preserve_paint_on_cancel || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() || it.inherited_preview_paint @@ -801,7 +805,7 @@ impl Session { // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. An interaction that changed only the // defaults (`defaultsOnly: true`) leaves the defaults it began with. - if !used_defaults_only { + if !used_defaults_only && !preserve_paint { self.inherit_new_art(); } Ok(()) diff --git a/docs/mcp.md b/docs/mcp.md index f57abb7d58..67a3e4d15a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17511,15 +17511,19 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` -`addon.document.floodFillArtboards {artboards?, all?, color?, keepModel?, layer?}` adds an editable rectangle exactly the size of +`addon.document.floodFillArtboards {artboards?, all?, activeArtboard?, color?, keepModel?, layer?}` adds an editable rectangle exactly the size of each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active -artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the +artboard by default), and `all: true` takes every artboard instead; the two can't be given together. +`activeArtboard?: n` is a 0-based index: the journal records that default here, for a replay. +A given `activeArtboard` takes precedence over the view's active artboard and must name an existing artboard. +It is ignored when `artboards` is given or `all` is true. Recorded actions omit `activeArtboard`; without explicit targets, they use the active artboard when played. +`color` takes the colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite). Explicit RGB colors convert to the document's color model as `paint.setFill` does, and `keepModel: true` keeps them in RGB. Without `color`, the rectangles take the current fill (in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. Params must be an object or null (omitted options). Null option values and values -of the wrong type are errors. The command is refused in isolation mode or while a symbol, pattern or opacity mask is edited. +of the wrong type are errors, except for an ignored `activeArtboard`. The command is refused in isolation mode or while a symbol, pattern or opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. From 07dffc15fdb35bb1a0e46cca383986317148942d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:38:14 -0800 Subject: [PATCH 08/15] Document Tools: Flood Fill Artboards keeps an out-of-sRGB RGB fill when Color is picked The dialog shows the current fill as a display sRGB color, clamped to the sRGB range, and converted that shown color back to working RGB when Color was picked. In a working RGB space wider than sRGB, a saturated fill did not convert back to itself. While the shown color is left unchanged, the dialog now sends an RGB current fill's own working components. Non-RGB fills and edited colors convert as before. --- crates/ui-egui/src/addons/document.rs | 19 ++++++++++++++++++- crates/ui-egui/src/addons/document/tests.rs | 20 ++++++++++++++++++++ docs/mcp.md | 2 ++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index eedb5ef60a..33b96eefe1 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -86,7 +86,13 @@ fn flood_params(fields: &DialogFields) -> Value { _ => json!({ "artboards": [fields.int("board").unwrap_or(0)] }), }; if fields.text("fill") == Some("color") { - p["color"] = working_rgb(fields.color("color").unwrap_or(GRAY)); + let picked = fields.color("color").unwrap_or(GRAY); + // The opening fill, while its shown color is unchanged, keeps its own working components, also + // those outside the displayable sRGB range. + let start = (fields.color("startShown") == Some(picked)) + .then(|| fields.text("startColor").and_then(|t| serde_json::from_str::(t).ok())) + .flatten(); + p["color"] = start.unwrap_or_else(|| working_rgb(picked)); } p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); p @@ -99,12 +105,23 @@ pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result let fill = &app.session.paint.fill; let no_current_fill = fill.is_none(); let color = fill.color().map_or(GRAY, |c| c.to_rgb().map(|v| v.clamp(0.0, 1.0))); + // An RGB opening fill's working components, unclamped, sent when Color keeps the shown color. + let start_color = fill + .color() + .and_then(|c| match c { + vectorcraft_color::Color::Rgb { r, g, b } => Some([r, g, b]), + _ => None, + }) + .filter(|rgb| rgb.iter().all(|v| v.is_finite())) + .map_or_else(String::new, |rgb| json!(rgb).to_string()); let fields = DialogFields::from_pairs([ ("artboards", FieldValue::Text("active".into())), ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), ("color", FieldValue::Color(color)), ("layer", FieldValue::Text(FLOOD_LAYER.into())), ("board", FieldValue::Int(board as i64)), + ("startShown", FieldValue::Color(color)), + ("startColor", FieldValue::Text(start_color)), ]); let mut layer_clips = std::collections::HashMap::new(); if let Ok(st) = app.session.doc() { diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 4f71e746a6..6ceed3da2b 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -359,6 +359,26 @@ fn flood_fill_color_keeps_the_current_fill_in_a_non_srgb_working_space() { }); } +/// A current fill outside the sRGB gamut, whose shown color does not convert back to it, keeps its +/// working components when Color is picked without editing the color. +#[test] +fn flood_fill_color_keeps_an_out_of_srgb_current_fill() { + use vectorcraft_color::cms; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + let shown = vectorcraft_color::Color::rgb(0.0, 1.0, 0.0).to_rgb(); + assert_ne!(super::working_rgb(shown), json!([0.0, 1.0, 0.0]), "{shown:?} does not convert back to the fill"); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.0, 1.0, 0.0]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["color"], json!([0.0, 1.0, 0.0])); + }); +} + #[test] fn flood_fill_layer_name_limit_counts_characters_after_trimming() { let mut app = boards(); diff --git a/docs/mcp.md b/docs/mcp.md index 67a3e4d15a..cb9092a33a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17527,6 +17527,8 @@ of the wrong type are errors, except for an ignored `activeArtboard`. The comman The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. +Color opens on the current fill's color; for an RGB current fill, while that color is left unchanged, the dialog sends +the fill's own working RGB components, also those outside the sRGB gamut. → `{ids: [rectangle id…], layer, created}` ```json From b57a4ff927546eb04fe819b4c0ecbbb7de47fe2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:20:07 -0800 Subject: [PATCH 09/15] Document Tools: Flood Fill Artboards keeps an RGB current fill in a CMYK document Two fixes for review threads on this pull request. The dialog sent an RGB current fill's working components without keepModel, so in a CMYK document the engine converted the fill to CMYK. While the shown color is left unchanged, the dialog now also sends keepModel: true. An edited color converts to the document's model as before. With New Art Has Basic Appearance off and nothing selected, a preview that drew new art took its new-art paints from that art, and the next preview then put back the paints the interaction began with. A second rectangle preview after a fill preview was drawn with the starting fill instead of the previewed one. The interaction now keeps the paints from before the inheritance and the next preview starts from them. A fill chosen during the drag updates them too. After a failed preview, a cancel or a commit puts back the paints the interaction began with. --- .../engine/src/cmd/addons/document/tests.rs | 61 ++++++++++++++ crates/engine/src/cmd/newart.rs | 8 +- crates/engine/src/interaction.rs | 5 +- crates/engine/src/session/edit.rs | 80 ++++++++++++------- .../engine/src/tests/interaction_commands.rs | 19 +++++ crates/ui-egui/src/addons/document.rs | 10 ++- crates/ui-egui/src/addons/document/tests.rs | 20 +++++ docs/mcp.md | 3 +- 8 files changed, 167 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index c0e2e0e894..3114142ba8 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -644,6 +644,67 @@ fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); } +/// With New Art Has Basic Appearance off and nothing selected, rectangle previews that follow a fill +/// preview each draw with that preview's fill, not the fill the interaction began with. +#[test] +fn rectangle_previews_after_a_fill_preview_keep_its_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + for n in 0..2 { + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, blue, "rectangle preview {n} draws with the previewed fill"); + } + s.commit_interaction().unwrap(); +} + +/// A cancel or a commit after a fill preview, a rectangle preview and a failed rectangle preview +/// puts back the fill the interaction began with. +#[test] +fn cancel_or_commit_after_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + +/// A failed fill preview after a fill preview and a rectangle preview leaves the starting fill for +/// the next rectangle preview. +#[test] +fn rectangle_preview_after_a_failed_fill_preview_uses_the_starting_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("paint.setFill", &json!({"color": "not a color"})).is_err()); + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), red); + s.cancel_interaction().unwrap(); +} + #[test] fn paint_swap_previews_from_an_empty_selection_commit_one_swap() { let mut s = boards(); diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 09c56e1473..c10fe26c53 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -236,10 +236,12 @@ impl Session { return; } if self.previewing - && let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) - && it.selection.is_empty() + && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.selection.is_empty() && it.inherited_preview_paint.is_none()) { - it.inherited_preview_paint = true; + let before = self.paint.clone(); + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) { + it.inherited_preview_paint = Some(before); + } } let NewArtSource { appearance, opacity, blend, style, .. } = source; let kept_fill = fill.then(|| self.paint.fill.clone()); diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 171f2adba0..d3b39bf831 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -23,8 +23,9 @@ pub struct Interaction { /// A Flood Fill Artboards preview ran: a cancel puts `paint` back and does not take the /// selection's appearance as the new-art paints. pub(crate) preserve_paint_on_cancel: bool, - /// The preview inherited new-art paints from a selection absent at interaction start. - pub(crate) inherited_preview_paint: bool, + /// The preview inherited new-art paints from a selection absent at interaction start: the + /// new-art paints from before that, which the next preview starts from. + pub(crate) inherited_preview_paint: Option, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 025cbb5258..5195b2df14 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -394,32 +394,34 @@ impl Session { // A change the command made to the new-art paints stays when the next preview or a cancel // puts back the paints the interaction began with (the Live Paint Bucket's colors); the // parts it left alone keep the interaction's. The pattern lists every field, so a field - // added to `PaintDefaults` does not compile until it is handled here. + // added to `PaintDefaults` does not compile until it is handled here. The paints a preview + // took its new-art paints over from take the change as well. let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; - let start = &mut it.paint; - if *fill != paint.fill { - start.fill.clone_from(fill); - } - if *stroke != paint.stroke { - start.stroke.clone_from(stroke); - } - if *stroke_width != paint.stroke_width { - start.stroke_width = *stroke_width; - } - if *appearance != paint.appearance { - start.appearance.clone_from(appearance); - } - if *opacity != paint.opacity { - start.opacity = *opacity; - } - if *blend != paint.blend { - start.blend = *blend; - } - if *style != paint.style { - start.style.clone_from(style); - } - if *inherited != paint.inherited { - start.inherited = *inherited; + for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) { + if *fill != paint.fill { + start.fill.clone_from(fill); + } + if *stroke != paint.stroke { + start.stroke.clone_from(stroke); + } + if *stroke_width != paint.stroke_width { + start.stroke_width = *stroke_width; + } + if *appearance != paint.appearance { + start.appearance.clone_from(appearance); + } + if *opacity != paint.opacity { + start.opacity = *opacity; + } + if *blend != paint.blend { + start.blend = *blend; + } + if *style != paint.style { + start.style.clone_from(style); + } + if *inherited != paint.inherited { + start.inherited = *inherited; + } } let active = self.active().is_some_and(|d| d.uid == uid); let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; @@ -550,7 +552,7 @@ impl Session { paint, used_defaults_only: false, preserve_paint_on_cancel: false, - inherited_preview_paint: false, + inherited_preview_paint: None, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -580,7 +582,7 @@ impl Session { // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let new_art_basic = self.prefs.new_art_basic; - let (paint, restore_paint) = { + let (paint, restore_paint, inherited) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -602,10 +604,11 @@ impl Session { || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() - || it.inherited_preview_paint || (!new_art_basic && it.selection.is_empty() && it.preview.is_some() && cmd.starts_with("paint.")); let paint = it.paint.clone(); - it.inherited_preview_paint = false; + // A preview that took the new-art paints from the art it drew puts back the paints it + // started from, which an earlier paint preview may have set. + let inherited = it.inherited_preview_paint.take(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -622,10 +625,12 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint) + (paint, restore_paint, inherited) }; if restore_paint { self.paint = paint.clone(); + } else if let Some(before) = &inherited { + self.paint.clone_from(before); } self.pending_paint = None; // The previous preview's Assign Profile is undone with it. @@ -651,6 +656,10 @@ impl Session { // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + // After a failed preview a cancel still puts back the paints the interaction began with. + if r.is_err() && !restore_paint && it.inherited_preview_paint.is_none() { + it.inherited_preview_paint.clone_from(&inherited); + } if it.color_mode_paints.is_some() { it.preview_paint = batch_paint.clone(); } @@ -679,6 +688,15 @@ impl Session { if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } + // A failed last preview leaves nothing to commit, so the paints an earlier preview set go too. + if let Some(paint) = self + .active() + .and_then(|st| st.interaction.as_ref()) + .filter(|it| it.preview.is_none() && it.inherited_preview_paint.is_some()) + .map(|it| it.paint.clone()) + { + self.paint = paint; + } self.remember_pending_paint(); cmd::colormgmt::commit_new_art_colors(self)?; let paint = self.paint.clone(); @@ -788,7 +806,7 @@ impl Session { || it.preserve_paint_on_cancel || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() - || it.inherited_preview_paint + || it.inherited_preview_paint.is_some() || (!self.prefs.new_art_basic && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index d0d12cce94..00588ecf0c 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -808,6 +808,25 @@ fn a_fill_chosen_during_a_bucket_drag_stays() { } } +/// With New Art Has Basic Appearance off, a fill chosen during a rectangle drag from an empty +/// selection is the fill the drag's next preview and its release draw with. +#[test] +fn a_fill_chosen_during_a_rectangle_drag_draws_the_rectangle() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, _) = session(real_time); + s.prefs.new_art_basic = false; + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": []})).unwrap(); + let blue = s.paint.fill.clone(); + pointer(&mut s, PointerKind::Drag, 200.0, 180.0); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(s.doc().unwrap().doc.node(drawn).unwrap().appearance.fill_paint(), blue, "{at}"); + } +} + /// A command run during a Quick Pen press still runs inside the press, so it records no undo /// step of its own while the press is held. #[test] diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 33b96eefe1..64833ab120 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -88,11 +88,17 @@ fn flood_params(fields: &DialogFields) -> Value { if fields.text("fill") == Some("color") { let picked = fields.color("color").unwrap_or(GRAY); // The opening fill, while its shown color is unchanged, keeps its own working components, also - // those outside the displayable sRGB range. + // those outside the displayable sRGB range, and stays RGB in a CMYK document. let start = (fields.color("startShown") == Some(picked)) .then(|| fields.text("startColor").and_then(|t| serde_json::from_str::(t).ok())) .flatten(); - p["color"] = start.unwrap_or_else(|| working_rgb(picked)); + match start { + Some(start) => { + p["color"] = start; + p["keepModel"] = json!(true); + } + None => p["color"] = working_rgb(picked), + } } p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); p diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 6ceed3da2b..b8ef41e65b 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -379,6 +379,26 @@ fn flood_fill_color_keeps_an_out_of_srgb_current_fill() { }); } +/// In a CMYK document, an RGB current fill kept by picking Color without editing it stays RGB. +#[test] +fn flood_fill_color_keeps_an_rgb_current_fill_in_a_cmyk_document() { + use vectorcraft_color::Color; + let mut app = boards(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4], "keepModel": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } +} + #[test] fn flood_fill_layer_name_limit_counts_characters_after_trimming() { let mut app = boards(); diff --git a/docs/mcp.md b/docs/mcp.md index cb9092a33a..cdf564d439 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17528,7 +17528,8 @@ The desktop app's Flood Fill Artboards… dialog picks the active artboard or al current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. Color opens on the current fill's color; for an RGB current fill, while that color is left unchanged, the dialog sends -the fill's own working RGB components, also those outside the sRGB gamut. +the fill's own working RGB components, also those outside the sRGB gamut, with `keepModel: true`, so the fill stays RGB +in a CMYK document. → `{ids: [rectangle id…], layer, created}` ```json From a36c8ce509cb7bb83d0a5bf609d78fa8bb40d88b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:29:17 -0800 Subject: [PATCH 10/15] Document Tools: cancel keeps the starting paints after a deselect and a failed preview A preview that started from the paints saved before an earlier preview took the selection's appearance cleared that snapshot. When a later preview then failed, neither the cancel nor the commit after it saw that the new-art paints had changed, and the previewed fill stayed. The interaction now records that such a preview ran, and the cancel and the commit after a failed preview put back the paints it began with. --- .../engine/src/cmd/addons/document/tests.rs | 23 +++++++++++++++++++ crates/engine/src/interaction.rs | 3 +++ crates/engine/src/session/edit.rs | 7 +++++- 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 3114142ba8..4e133eacef 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -687,6 +687,29 @@ fn cancel_or_commit_after_a_failed_rectangle_preview_restores_the_starting_fill( } } +/// A cancel or a commit puts back the fill the interaction began with when a deselect preview +/// started from the rectangle preview's paints and a failed rectangle preview followed it. +#[test] +fn cancel_or_commit_after_a_deselect_and_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.preview("select.none", &json!({})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + /// A failed fill preview after a fill preview and a rectangle preview leaves the starting fill for /// the next rectangle preview. #[test] diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index d3b39bf831..ce3648a59c 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -26,6 +26,9 @@ pub struct Interaction { /// The preview inherited new-art paints from a selection absent at interaction start: the /// new-art paints from before that, which the next preview starts from. pub(crate) inherited_preview_paint: Option, + /// A successful preview started from `inherited_preview_paint`: the new-art paints changed + /// during the interaction, so a cancel, or a commit after a failed preview, puts `paint` back. + pub(crate) inherited_preview_paint_used: bool, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 5195b2df14..a9794438bd 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -553,6 +553,7 @@ impl Session { used_defaults_only: false, preserve_paint_on_cancel: false, inherited_preview_paint: None, + inherited_preview_paint_used: false, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -660,6 +661,9 @@ impl Session { if r.is_err() && !restore_paint && it.inherited_preview_paint.is_none() { it.inherited_preview_paint.clone_from(&inherited); } + if r.is_ok() && !restore_paint && inherited.is_some() { + it.inherited_preview_paint_used = true; + } if it.color_mode_paints.is_some() { it.preview_paint = batch_paint.clone(); } @@ -692,7 +696,7 @@ impl Session { if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| it.preview.is_none() && it.inherited_preview_paint.is_some()) + .filter(|it| it.preview.is_none() && (it.inherited_preview_paint.is_some() || it.inherited_preview_paint_used)) .map(|it| it.paint.clone()) { self.paint = paint; @@ -807,6 +811,7 @@ impl Session { || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() || it.inherited_preview_paint.is_some() + || it.inherited_preview_paint_used || (!self.prefs.new_art_basic && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) From 91469a3d0ea8e91e10c48e9482b42dabac05e98c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 10:17:02 -0800 Subject: [PATCH 11/15] Document Tools: a failed preview puts back the fill an earlier preview set With nothing selected and New Art Has Basic Appearance off, a fill preview followed by a failed Flood Fill preview left the previewed fill in the new-art paints, and a commit kept it. The interaction now keeps the paints from before the previews that build on each other and the paints the last of them left. A failed preview puts back the first, with the fields a command outside the previews changed kept as that command left them. --- .../engine/src/cmd/addons/document/tests.rs | 27 +++++++++ crates/engine/src/interaction.rs | 4 ++ crates/engine/src/session/edit.rs | 60 ++++++++++++++++++- 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 4e133eacef..66cda25344 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -868,6 +868,33 @@ fn flood_fill_cancel_after_a_rejected_preview_keeps_the_new_art_fill() { assert!(s.doc().unwrap().selection.is_empty()); } +/// A commit after a fill preview with nothing selected and a failed flood fill preview puts back +/// the fill the interaction began with. +#[test] +fn flood_fill_commit_after_a_fill_preview_and_a_rejected_preview_restores_the_new_art_fill() { + for stroke_first in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + if stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + if !stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + let stroke = s.paint.stroke.clone(); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + s.commit_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + assert_eq!(s.paint.stroke, stroke, "a command run outside the previews keeps its change (stroke first {stroke_first})"); + } +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index ce3648a59c..74f42c9efd 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -29,6 +29,10 @@ pub struct Interaction { /// A successful preview started from `inherited_preview_paint`: the new-art paints changed /// during the interaction, so a cancel, or a commit after a failed preview, puts `paint` back. pub(crate) inherited_preview_paint_used: bool, + /// The new-art paints before the successful previews that built on each other, with the + /// changes made outside the previews, and the paints the last of them left. A failed preview + /// puts back the first where a field still holds what the previews left. + pub(crate) last_preview_paint: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index a9794438bd..3cf85f4e27 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -554,6 +554,7 @@ impl Session { preserve_paint_on_cancel: false, inherited_preview_paint: None, inherited_preview_paint_used: false, + last_preview_paint: None, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -583,7 +584,7 @@ impl Session { // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let new_art_basic = self.prefs.new_art_basic; - let (paint, restore_paint, inherited) = { + let (paint, restore_paint, inherited, last_preview_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -607,6 +608,7 @@ impl Session { || it.color_mode_paints.is_some() || (!new_art_basic && it.selection.is_empty() && it.preview.is_some() && cmd.starts_with("paint.")); let paint = it.paint.clone(); + let last_preview_paint = it.last_preview_paint.take().filter(|_| it.preview.is_some()); // A preview that took the new-art paints from the art it drew puts back the paints it // started from, which an earlier paint preview may have set. let inherited = it.inherited_preview_paint.take(); @@ -626,13 +628,25 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint, inherited) + (paint, restore_paint, inherited, last_preview_paint) + }; + // The paints before the previews that build on each other: a preview that starts from the + // interaction's paints (or from the inherited ones) starts a new run of them. A field that + // no longer holds what the last preview left was changed outside the previews. + let base = if restore_paint || inherited.is_some() { + None + } else { + last_preview_paint.map(|(mut base, left)| { + take_changed_paints(&mut base, &left, &self.paint); + base + }) }; if restore_paint { self.paint = paint.clone(); } else if let Some(before) = &inherited { self.paint.clone_from(before); } + let base = base.unwrap_or_else(|| self.paint.clone()); self.pending_paint = None; // The previous preview's Assign Profile is undone with it. self.sync_front_profiles(); @@ -651,12 +665,20 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + // A failed preview leaves the document at the snapshot, so the new-art paints that earlier + // previews changed (a `paint.*` preview with nothing selected) go back to the paints from + // before them as well. A change made outside the previews stays. + if r.is_err() { + self.paint.clone_from(&base); + } + let after_paint = r.is_ok().then(|| (base, self.paint.clone())); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + it.last_preview_paint = after_paint; // After a failed preview a cancel still puts back the paints the interaction began with. if r.is_err() && !restore_paint && it.inherited_preview_paint.is_none() { it.inherited_preview_paint.clone_from(&inherited); @@ -839,6 +861,40 @@ impl Session { } } +/// Copy into `target` each field of `now` that differs from `left`. The pattern lists every field, +/// so a field added to `PaintDefaults` does not compile until it is handled here. +fn take_changed_paints( + target: &mut vectorcraft_tools::PaintDefaults, + left: &vectorcraft_tools::PaintDefaults, + now: &vectorcraft_tools::PaintDefaults, +) { + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now; + if left.fill != *fill { + target.fill.clone_from(fill); + } + if left.stroke != *stroke { + target.stroke.clone_from(stroke); + } + if left.stroke_width != *stroke_width { + target.stroke_width = *stroke_width; + } + if left.appearance != *appearance { + target.appearance.clone_from(appearance); + } + if left.opacity != *opacity { + target.opacity = *opacity; + } + if left.blend != *blend { + target.blend = *blend; + } + if left.style != *style { + target.style.clone_from(style); + } + if left.inherited != *inherited { + target.inherited = *inherited; + } +} + /// The selection a drag began with, without the objects that a command run during it removed, /// hid or locked in `doc`. fn drag_selection(began: &Selection, doc: &Document) -> Selection { From 5fbeb88f1d32404f3b75faaaa5dbe2dd6962a3f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:44:27 -0800 Subject: [PATCH 12/15] Docs: Flood Fill Artboards makes its layer when no top-level layer has that name --- ROADMAP.md | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a77af74c91..594adb9e9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -168,7 +168,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. -- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke (a chosen RGB color goes into the document's color model, or stays RGB with `keepModel`), on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke (a chosen RGB color goes into the document's color model, or stays RGB with `keepModel`), on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when no top-level layer has that name and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index 3bba9bd55f..4c403487e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17812,7 +17812,7 @@ It is ignored when `artboards` is given or `all` is true. Recorded actions omit `color` takes the colors the paint commands take (`#rrggbbaa` and `#rgba` are refused, as is a component too large to be finite). Explicit RGB colors convert to the document's color model as `paint.setFill` does, and `keepModel: true` keeps them in RGB. Without `color`, the rectangles take the current fill (in a Flood Fill preview, the fill the preview began with; in a batch step, the live fill after preceding steps), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by -default, trimmed and nonempty, at most 255 characters after trimming), which is made at the bottom of the layers when the document has none. A destination layer that holds a clipping mask is rejected before any edit. A layer that +default, trimmed and nonempty, at most 255 characters after trimming). If no top-level layer has that name, the command makes it at the bottom of the layers and returns `created: true`. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. Params must be an object or null (omitted options). Null option values and values of the wrong type are errors, except for an ignored `activeArtboard`. The command is refused in isolation mode or while a symbol, pattern or opacity mask is edited. From d9262da342a04a4e4f9410c4dd202f7745d765ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:44:30 -0800 Subject: [PATCH 13/15] MCP: ui.menuDialog's params text lists Flood Fill Artboards The gate failed in menu_dialog_params_text_lists_every_command_whose_dialog_it_opens, which main added in 7eda2320: ui.menuDialog opens Flood Fill Artboards' dialog, but its params text did not list addon.document.floodFillArtboards. The command is now in the list in ui_commands.rs and in the generated ui_catalog.rs. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..80e58b68e8 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..7f4e73c8d1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 5e309268d77bb451d8bb85c8afcb7eccb7fca849 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:24:30 -0800 Subject: [PATCH 14/15] Document Tools: Flood Fill Artboards' dialog is refused while its command is off ui.menuDialog opened the Flood Fill Artboards dialog with no document or in an editing mode the command refuses, and OK then failed. The dialog now checks the command first and returns its reason. A reopened dialog also rolled back the open preview only after reading the current fill, so with New Art Has Basic Appearance off it opened on the previewed fill instead of the fill from before; it now rolls the preview back first. The params text and docs/mcp.md say when it is refused. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/addons/dialogs.rs | 2 +- crates/ui-egui/src/addons/document.rs | 4 ++++ crates/ui-egui/src/addons/document/tests.rs | 24 +++++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 ++- 6 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 80e58b68e8..68256eac9b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index fa5ab17b98..ae43d7d563 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -64,7 +64,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { } /// Closes the open add-on dialog without an answer and rolls its preview back. -fn close_open(app: &mut VectorcraftApp) { +pub(crate) fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; app.addon_dialogs.preview_error = None; let id = open.id; diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 64833ab120..c2f44a331c 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -107,6 +107,10 @@ fn flood_params(fields: &DialogFields) -> Value { /// Opens Flood Fill Artboards' dialog on the active artboard and the current fill, or, when there is no fill, on /// Color with gray. pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { + let command = vectorcraft_engine::find_command(FLOOD_FILL).ok_or_else(|| format!("unknown command {FLOOD_FILL}"))?; + (command.enabled)(&app.session)?; + // A reopened dialog reads the fill after the open dialog's preview is rolled back, not the previewed fill. + super::dialogs::close_open(app); let board = app.view().map_or(0, |v| v.artboard); let fill = &app.session.paint.fill; let no_current_fill = fill.is_none(); diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index b8ef41e65b..ebd0ad8c84 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -460,6 +460,30 @@ fn flood_fill_current_fill_without_a_fill_keeps_the_dialog_open() { assert_eq!(app.session.doc().unwrap().history.undo.len(), before + 1); } +#[test] +fn flood_fill_menu_dialog_is_refused_without_a_document() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + assert!(app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).is_err(), "the command is off without a document"); + assert!(!app.any_dialog_open()); +} + +/// With New Art Has Basic Appearance off and no fill, reopening the dialog while a Color preview is +/// showing opens it on the fill from before the preview, not on the previewed rectangles' fill. +#[test] +fn flood_fill_reopened_during_a_color_preview_reads_the_fill_before_it() { + let mut app = boards(); + app.run("appearance.setNewArtBasic", json!({"on": false})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Flood Fill", "previewed"); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); +} + #[test] fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { let mut app = boards(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7f4e73c8d1..4d0c0df036 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{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|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/docs/mcp.md b/docs/mcp.md index 2f5a62bd14..b03da9294f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17839,7 +17839,8 @@ current fill or a color, and the layer, and previews on the canvas. The dialog d trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. Color opens on the current fill's color; for an RGB current fill, while that color is left unchanged, the dialog sends the fill's own working RGB components, also those outside the sRGB gamut, with `keepModel: true`, so the fill stays RGB -in a CMYK document. +in a CMYK document. `ui.menuDialog {command: "addon.document.floodFillArtboards"}` opens the dialog, and is +refused with the command's reason while the command is disabled (with no document open, or in the editing modes above). → `{ids: [rectangle id…], layer, created}` ```json From f2f0af5ab0cb32f9229ddcc4097266c5a9e9ed18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:02:35 -0800 Subject: [PATCH 15/15] Document Tools: Flood Fill Artboards records Active Artboard as a relative target With Active Artboard picked, the dialog sent an explicit artboards list, so a recorded action filled the artboard that was active while recording, or failed in a document with fewer artboards. The dialog now sends activeArtboard, which the preview and journal keep and recorded actions leave out, so playback fills the artboard active then. --- crates/ui-egui/src/addons/document.rs | 2 +- crates/ui-egui/src/addons/document/tests.rs | 31 +++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index c2f44a331c..1e38dcc3d8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -83,7 +83,7 @@ fn working_rgb(srgb: [f32; 3]) -> Value { fn flood_params(fields: &DialogFields) -> Value { let mut p = match fields.text("artboards") { Some("all") => json!({ "all": true }), - _ => json!({ "artboards": [fields.int("board").unwrap_or(0)] }), + _ => json!({ "activeArtboard": fields.int("board").unwrap_or(0) }), }; if fields.text("fill") == Some("color") { let picked = fields.color("color").unwrap_or(GRAY); diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index ebd0ad8c84..fc77f7a4ab 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -298,6 +298,37 @@ fn flood_fill_typed_layer_name_previews_and_ok_applies_one_step() { assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Flood Fill Artboards"); } +#[test] +fn flood_fill_active_artboard_records_a_relative_action_target() { + let mut app = boards(); + let start = app.session.journal.len(); + let opening_board = app.session.doc().unwrap().doc.artboards[1].rect; + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + app.view_mut().unwrap().artboard = 2; + host::set(&app, id, "layer", json!("Paper")); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + let journal = app.session.journal.since(start); + let (_, params) = journal.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert_eq!(params["activeArtboard"], json!(1)); + let steps = app.session.journal_for_action(start); + let (command, params) = steps.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert!(params.get("activeArtboard").is_none()); + assert!(params.get("artboards").is_none()); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + app.sync_views(); + let playback_board = app.session.doc().unwrap().doc.artboards[0].rect; + app.run(command, params.clone()).unwrap(); + assert_eq!(bottom_art(&app)[0].0, playback_board); +} + #[test] fn flood_fill_cancel_rolls_the_preview_back() { let app = boards(); diff --git a/docs/mcp.md b/docs/mcp.md index b03da9294f..900f7357ad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17835,7 +17835,8 @@ already exists keeps its lock and visibility. The rectangles are selected unless in which case the prior selection stays. The current layer stays as it was. Params must be an object or null (omitted options). Null option values and values of the wrong type are errors, except for an ignored `activeArtboard`. The command is refused in isolation mode or while a symbol, pattern or opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the -current fill or a color, and the layer, and previews on the canvas. The dialog disables OK for an empty or overlong +current fill or a color, and the layer, and previews on the canvas. With Active Artboard selected, the dialog previews +and journals the artboard that was active when it opened. Recorded actions fill the artboard active at playback. The dialog disables OK for an empty or overlong trimmed layer name, a destination layer that holds a clipping mask, or Current Fill when there is no current fill. Color opens on the current fill's color; for an RGB current fill, while that color is left unchanged, the dialog sends the fill's own working RGB components, also those outside the sRGB gamut, with `keepModel: true`, so the fill stays RGB