From df0ee01cf254fe7e5aeaf91a7793ee47dcbd50ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:20:18 -0800 Subject: [PATCH 01/45] Unit Converter: reject ambiguous commas in expressions --- crates/doc/src/units.rs | 22 +++++++++++++++++++++ crates/engine/src/cmd/addons/units.rs | 10 +++++----- crates/engine/src/cmd/addons/units/tests.rs | 16 ++++++++++++--- docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 3 +++ 5 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index f65fa1fd10..0544ac1972 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -196,6 +196,15 @@ impl Unit { } parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite()) } + + /// Parse a measurement with decimal points or commas and no input locale. Refuse a + /// number that looks like a grouped integer, even when it is part of an expression. + pub fn parse_with_decimal_comma(self, text: &str) -> Option { + if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) { + return None; + } + self.parse(&decimal_point(text)) + } /// The value naming this unit in the Units preferences (`points`, `millimeters`, /// `feetInches`). pub const fn key(self) -> &'static str { @@ -397,6 +406,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } +/// Does the operand contain a thousands comma? Check both parts of a compact pica value and +/// read a percentage's number without its percent sign. +fn thousands_operand(operand: &str) -> bool { + let operand = operand.trim(); + if let Some((picas, points)) = operand.split_once('p') + && !points.trim().is_empty() + && points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b',')) + { + return thousands(picas) || thousands(points); + } + thousands(operand.strip_suffix('%').unwrap_or(operand)) +} + /// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or /// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at /// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index 4da4f68b79..c79f42919c 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -1,6 +1,6 @@ //! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. -//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and -//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives +//! it in each unit of Preferences › Units › East Asian Type //! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). //! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform //! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result { return Err(bad(CONVERT, "missing `value`")); }; let pt = match v { - Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s), Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), _ => None, }; diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 802fb5dfdf..2557ea3a6c 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() { } #[test] -fn values_read_as_number_fields_read_them() { +fn values_accept_units_arithmetic_and_decimal_commas() { let mut s = session(); let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); @@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); // Each number of a sum reads its own separator. assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); - // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. - assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25)); + assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5)); + assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); // x, X and × multiply as * does, and each counts toward the 128 signs. @@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() { assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } +#[test] +fn a_thousands_comma_in_an_arithmetic_operand_is_refused() { + let mut s = session(); + for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] { + let result = s.execute("addon.units.convert", &json!({"value": value})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}"); + } +} + #[test] fn keys_the_commands_do_not_take_are_refused() { let s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index a12daa1b46..65fdb53acb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16682,10 +16682,11 @@ Unit Converter is a built-in add-on that shows one length in every unit at once `addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. -`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`addon.units.convert {value, unit?}` accepts a number, or text with a unit suffix and `+ - * /` arithmetic, where `x`, `X` and `×` multiply as `*` does (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, -`"3cm*50%"`, `"2x3 mm"`, `"13q"`), a decimal comma read as a point (`"0,5 mm"`) and a single number with a thousands -comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs (each multiplication sign counts). +`"3cm*50%"`, `"2x3 mm"`, `"13q"`). The command reads an unambiguous decimal comma as a point (`"0,5 mm"`). +It refuses numbers that look like grouped integers, whether alone (`"1,000 mm"`) or in arithmetic (`"1,500+2"`). +Text may contain at most 1024 bytes and 128 `+ - * /` signs (each multiplication sign counts). A number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, `centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d56d4fd4cd..71766ff09e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3062,6 +3062,9 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. +The `addon.units.convert` command rejects numbers that look like grouped integers even in expressions such as +`1,500+2`. The panel treats separators according to the input locale. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges. From 45ca3fc955d8ca75e5a70bc86cfd2b89017c2c73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:25:22 -0800 Subject: [PATCH 02/45] Keep Graph Data Apply and Revert in their original drawing --- crates/ui-egui/src/dialogs/graph_data.rs | 99 +++++++++++++++++++++--- 1 file changed, 87 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ffcc511501..a15fd75cd7 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -25,14 +25,16 @@ use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, }; +use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, PaintUi, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field, }; use craft::ui::display::Text; use craft::ui::layout_components::Row; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::primitives::TextRun; use craft::ui::runtime::env::{Env, Label, Units}; @@ -48,6 +50,7 @@ use crate::file_asks::{self, Owner}; /// The dialog kind of Graph Data, the key of its dialog on the host. pub const KIND: &str = "graphData"; +const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet."; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its /// series; the least rows it shows. @@ -68,12 +71,13 @@ const ROW_H: f32 = 19.0; pub fn open(app: &mut VectorcraftApp) -> Result { // The query fails without a graph selected, with the engine's own message. let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?; + let document = app.session.active().ok_or("no document open")?.uid; let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id))); let scatter = graph.is_some_and(|(st, id)| { st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter) }); let id = graph.map(|(_, id)| id.0); - let dialog = GraphDataDialog::new(grid_from_data(&v), id, scatter, can_import(app)); + let dialog = GraphDataDialog::new(grid_from_data(&v), document, id, scatter, can_import(app)); let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; dialogs.with(|host| host.open(dialog)); Ok(Value::Null) @@ -431,6 +435,7 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result, import_owner: Arc<()>, apply: Option, @@ -442,18 +447,28 @@ struct Asks { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let can = can_import(app); + let active = app.session.active().map(|doc| doc.uid); let asked = dialogs.with(|host| { host.get_mut::().map(|d| { d.can_import = can; + if active == Some(d.document) { + d.held.clear_refusal(); + } d.take_asks() }) }); - let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; + let Some(Asks { document, graph, import_owner, apply: filed, actions }) = asked else { return }; + let same_document = active == Some(document); if let Some(sheet) = filed { - if let Err(e) = apply(app, &sheet, graph) { - app.status(e); - } - dialogs.with(|host| host.get_mut::().map(GraphDataDialog::applied)); + let answer = if same_document { + if let Err(e) = apply(app, &sheet, graph) { + app.status(e); + } + Ok(()) + } else { + Err(Label::from(tl!(WRONG_DOCUMENT))) + }; + dialogs.with(|host| host.get_mut::().map(|dialog| dialog.applied(answer))); } for action in actions { match action { @@ -473,6 +488,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { move |app, picked| import(app, &owner, picked), ); } + Action::Revert if !same_document => app.status(tl!(WRONG_DOCUMENT).to_owned()), Action::Revert => match graph_grid(app, graph) { Ok(grid) => { dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); @@ -657,6 +673,7 @@ pub(crate) struct GraphDataDialog { sheet: Sheet, state: GridState, entry: Entry, + document: u64, /// The graph the sheet opened on. graph: Option, scatter: bool, @@ -669,7 +686,7 @@ pub(crate) struct GraphDataDialog { impl GraphDataDialog { /// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph. - fn new(grid: Grid, graph: Option, scatter: bool, can_import: bool) -> Self { + fn new(grid: Grid, document: u64, graph: Option, scatter: bool, can_import: bool) -> Self { let sheet = Sheet { grid, ..Sheet::default() }; let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0); let mut entry = Entry { text: String::new(), at: (0, 1) }; @@ -680,6 +697,7 @@ impl GraphDataDialog { sheet, state, entry, + document, graph, scatter, can_import, @@ -691,12 +709,18 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { + document: self.document, + graph: self.graph, + import_owner: self.import_owner.clone(), + apply: self.held.take(), + actions: std::mem::take(&mut self.actions), + } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. - fn applied(&mut self) { - self.held.answer(Ok(())); + fn applied(&mut self, answer: Result<(), Label>) { + self.held.answer(answer); self.held.finish(); } @@ -727,6 +751,7 @@ impl StackDialog for GraphDataDialog { fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let GraphDataDialog { sheet, state, entry, scatter, can_import, lines, actions, held, .. } = self; let mut pane = Pane { state, entry, lines, actions, scatter: *scatter, can_import: *can_import }; + let refusal = held.refusal().map(|(reason, _)| reason.clone()); let shown = FormDialog::new(tl!("Graph Data"), Bind::bound(&mut *sheet)) .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) @@ -734,7 +759,12 @@ impl StackDialog for GraphDataDialog { // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) - .show(ui, |ui, _, values| body(ui, values, &mut pane)); + .show(ui, |ui, _, values| { + if let Some(reason) = refusal.clone() { + Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); + } + body(ui, values, &mut pane) + }); // The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing. if shown.picked == Some(0) && !held.is_waiting() { commit_text(sheet, pane.entry); @@ -846,6 +876,51 @@ mod tests { pump(app, &ctx); } + fn sheet_with_matching_graphs() -> (VectorcraftApp, u64) { + let (mut app, id) = app_with("1,2\n3,4", "column"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "csv": "7,8\n9,10"})).unwrap(); + assert_eq!(other["id"], id); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([[""], ["", "5", "6"]])).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + (app, id) + } + + #[test] + fn graph_data_apply_cannot_change_the_other_drawings_graph() { + let (mut app, id) = sheet_with_matching_graphs(); + let other = data(&mut app, id); + let undo = app.session.active().unwrap().history.undo.len(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id)["rows"], json!([[5.0, 6.0]])); + } + + #[test] + fn graph_data_revert_keeps_the_draft_in_the_other_drawing() { + let (mut app, id) = sheet_with_matching_graphs(); + let draft = read(&app, |dialog| dialog.sheet.grid.clone()); + let revert = |app: &mut VectorcraftApp| { + edit(app, |dialog| dialog.actions.push(Action::Revert)); + pump(app, &crate::testing::ui_context()); + }; + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let expected = grid_from_data(&data(&mut app, id)); + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected); + } + /// The app with the window drawn each frame as the shell draws it. // PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself. fn harness(app: VectorcraftApp) -> Harness { From c8248ee63019f64bb1700471e2483899d9b497c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:30:48 -0800 Subject: [PATCH 03/45] Keep Graph Column and Marker on their original graph --- crates/ui-egui/src/dialogs/graph_design.rs | 95 +++++++++++++++++++--- 1 file changed, 85 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 348287e7bd..04e5e7f0a8 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -251,9 +251,12 @@ pub(crate) enum Answer { impl Answer { /// Runs the command; the refusal is its error. - fn run(&self, app: &mut VectorcraftApp) -> Result<(), Label> { + fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> { + if !target.in_active_document(app) { + return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog."))); + } let design = |d: &Option| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) }); - let (command, params) = match self { + let (command, mut params) = match self { Answer::Column { design: d, options } => { let mut params = design(d); params["columnType"] = json!(options.column_type.as_str()); @@ -263,10 +266,38 @@ impl Answer { } Answer::Marker { design: d } => ("graph.marker", design(d)), }; + // When selection still describes the opening target, let the command keep its selected series highlighted. + let selected = vectorcraft_engine::graph_type_subject(&app.session).ok(); + if !selected.is_some_and(|selected| selected.id.0 == target.graph && selected.series == target.series) { + params["id"] = json!(target.graph); + if !target.series.is_empty() { + params["seriesIndexes"] = json!(target.series); + } + } app.run(command, params).map(|_| ()).map_err(Label::from) } } +/// The graph and picked series the Column or Marker form opened for. +#[derive(Clone)] +struct GraphTarget { + document: u64, + graph: u64, + series: Vec, +} + +impl GraphTarget { + fn selected(app: &VectorcraftApp) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; + let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?; + Ok(Self { document, graph: selected.id.0, series: selected.series }) + } + + fn in_active_document(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|active| active.uid == self.document) + } +} + /// A loaded library's document, for the thumbnails of its designs. struct LibraryDoc { id: String, @@ -361,6 +392,7 @@ impl Lists { pub(crate) struct GraphDesignDialog { id: DialogId, kind: Kind, + target: Option, lists: Lists, /// The selected rows: any number of designs in Graph Design; one design, or None, in Column and Marker. selection: Selection, @@ -376,14 +408,16 @@ pub(crate) struct GraphDesignDialog { /// What [`pump`] takes from the open dialog to run. struct Work { actions: Vec, - answer: Option, + answer: Option<(Answer, GraphTarget)>, + document: Option, } impl GraphDesignDialog { - fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions) -> Self { + fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions, target: Option) -> Self { let mut dialog = GraphDesignDialog { id: dialog_id(kind.key()), kind, + target, lists, selection: Selection::new(Vec::new(), None, None), name: String::new(), @@ -432,7 +466,9 @@ impl GraphDesignDialog { } fn take_work(&mut self) -> Work { - Work { actions: std::mem::take(&mut self.actions), answer: self.held.take() } + let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target))); + let document = self.target.as_ref().map(|target| target.document); + Work { actions: std::mem::take(&mut self.actions), answer, document } } /// What OK files. @@ -756,7 +792,7 @@ impl StackDialog for GraphDesignDialog { pub fn open_design(app: &mut VectorcraftApp) -> Result { let lists = Lists::read(app)?; let first = lists.designs.first().map(|n| DesignKey::document(n)); - open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default())) + open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default(), None)) } /// Open Column for the selected graph series, on the design and options they draw their columns with (None for plain @@ -769,14 +805,16 @@ pub fn open_column(app: &mut VectorcraftApp) -> Result { fractions: v["fractions"].as_str().and_then(Fractions::parse).unwrap_or_default(), }; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options)) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options, Some(target))) } /// Open Marker for the selected graph series, on the design they draw with (None for the default). pub fn open_marker(app: &mut VectorcraftApp) -> Result { let v = app.session.execute("graph.marker", &json!({})).map_err(|e| e.to_string())?; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default())) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default(), Some(target))) } fn open(app: &VectorcraftApp, dialog: GraphDesignDialog) -> Result { @@ -815,8 +853,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Err(e) => app.status(e), } } - let answered = work.answer.map(|answer| answer.run(app)); - let lists = Lists::read(app).ok(); + let answered = work.answer.map(|(answer, target)| answer.run(app, &target)); + let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| active.uid == document)); + let lists = if same_document { Lists::read(app).ok() } else { None }; dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { if let Some(lists) = lists { @@ -881,6 +920,42 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_column_and_marker_keep_their_opening_graph() { + for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_kind); + let graph = app.session.active().unwrap().selection.objects[0].0; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("graph.design", json!({"new": true})).unwrap(); + select_graph(&mut app, graph_kind); + assert_eq!(app.session.active().unwrap().selection.objects[0].0, graph); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let design = |app: &mut VectorcraftApp, id| app.session.execute(command, &json!({"id": id})).unwrap()["design"].clone(); + + activate(&mut app, 0); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + activate(&mut app, 1); + let undo = app.session.active().unwrap().history.undo.len(); + app.dialogs().unwrap().with(|host| host.confirm::(&ctx)); + super::pump(&mut app, &ctx); + assert_eq!(design(&mut app, graph), Value::Null); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)["selected"], "New Design"); + + activate(&mut app, 0); + select_graph(&mut app, graph_kind); + let selected = app.session.active().unwrap().selection.objects[0].0; + assert_ne!(selected, graph); + ok(&mut app, &ctx); + assert_eq!(design(&mut app, graph), "New Design"); + assert_eq!(design(&mut app, selected), Value::Null); + } + } + #[test] fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { From 4902187d754b52320d2a92e9dfee755fddb76c6d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:00:03 -0800 Subject: [PATCH 04/45] Keep Symbol Options attached to the original drawing --- crates/ui-egui/src/dialogs/symbol_options.rs | 39 ++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 61c702c3e3..470f78e55e 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -100,10 +100,14 @@ fn rows(name: &str) -> Vec { /// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one; /// `opened` are the guides the dialog opened with. fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option, keep_art: bool, opened: [f64; 4]) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let ctx = app.ui_ctx.clone().ok_or("no window")?; let name = fields.text("name").unwrap_or_default().to_string(); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name))); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("This symbol belongs to the document that opened the dialog.").to_owned()); + } let f = &result.fields; let name = f.text("name").unwrap_or_default().trim().to_string(); if name.is_empty() { @@ -187,3 +191,38 @@ fn merge(into: &mut Value, extra: Value) { a.extend(b); } } + +#[cfg(test)] +mod document_tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_engine::Session; + + use super::super::tests_warp::{accept, set, windowed}; + use super::*; + + #[test] + fn editing_symbol_options_does_not_rename_another_drawings_symbol() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + for side in [30, 50] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": side, "height": side})).unwrap(); + app.run("symbol.new", json!({"name": "Badge"})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open_edit(&mut app, Some("Badge")).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Source badge")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(app.session.active().unwrap().doc, other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge")); + } +} From 1508dd8c3936bebd4a59e41a53e9b610839885ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:00:03 -0800 Subject: [PATCH 05/45] Keep Graphic Style Options in its original drawing --- .../src/dialogs/graphic_style_options.rs | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/graphic_style_options.rs b/crates/ui-egui/src/dialogs/graphic_style_options.rs index f72fdbba21..6081982fb2 100644 --- a/crates/ui-egui/src/dialogs/graphic_style_options.rs +++ b/crates/ui-egui/src/dialogs/graphic_style_options.rs @@ -40,13 +40,19 @@ impl Target { /// Open the dialog with `name` in its field; OK runs `target`. fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))]; let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| { ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields)) }); // An `Err` (a name another style has) keeps the dialog open with the reason. - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned()); + } + target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()) + }; host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -132,4 +138,30 @@ mod tests { assert_eq!(names(&app).last().unwrap(), "Halo"); assert!(app.run("ui.graphicStyleOptions", json!({"name": "nope"})).is_err()); } + + #[test] + fn renaming_a_style_does_not_change_a_matching_name_in_another_drawing() { + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = names(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, Some("Twin")).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Source style")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(names(&app), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(options(&app), id); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(names(&app).iter().any(|name| name == "Source style")); + } } From 371fba1735ef18671f9847ea99ee03347cd04ecc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:00:03 -0800 Subject: [PATCH 06/45] Keep Apply SVG Filter in its original drawing --- crates/ui-egui/src/dialogs/svg_filter.rs | 109 ++++++++++++++++++----- 1 file changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index c916cc46d0..ccd6bed543 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -16,6 +16,8 @@ //! `__list` (the filters listed, pushed by [`pump`]), and with an applied effect `__index`, //! `__item` and `missing` (the name of a deleted filter the effect names). +use std::sync::Arc; + use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::host::{PickRequest, Picked}; use craft::ui::buttons::Button; @@ -47,6 +49,19 @@ const LISTING: &str = "__list"; /// The rows the filter list shows before it scrolls. const LIST_ROWS: u16 = 7; +struct Opening { + document: u64, +} + +fn opening_id() -> egui::Id { + egui::Id::unique((KIND, "opening")) +} + +fn opening(app: &VectorcraftApp) -> Option> { + with_dialog(app, |_| ())?; + app.ui_ctx.as_ref()?.data(|d| d.get_temp(opening_id())) +} + /// The dialog's heading. fn heading() -> String { tl!("Apply SVG Filter…").trim_end_matches('…').to_string() @@ -252,9 +267,7 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p /// the default's code or with nothing; when neither has its name, the name shown above the list if /// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - if app.session.active().is_none() { - return Err("no document open".into()); - } + let document = app.session.active().ok_or("no document open")?.uid; let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" }); if let Some(k) = p.get("index").and_then(Value::as_u64) { let mut q = json!({}); @@ -289,7 +302,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone()))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build); - crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields)).ok_or("no window")?; + crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { + if app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("Return to the original drawing to apply this SVG filter").into()); + } + confirm(app, &result.fields) + }) + .ok_or("no window")?; + ctx.data_mut(|d| d.insert_temp(opening_id(), Arc::new(Opening { document }))); Ok(Value::Null) } @@ -337,6 +357,15 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) { /// Each frame: pushes the listed filters into the dialog (the build closure has no app) and runs the /// button pressed, once. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(source) = opening(app) else { return }; + if app.session.active().is_none_or(|st| st.uid != source.document) { + let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default(); + if has_action { + set(app, &[(ACTION, json!(""))]); + app.status(tl!("Return to the original drawing to edit its SVG filters")); + } + return; + } let listing = listing(app); let taken = with_dialog(app, |d| { if json_field(d.fields(), LISTING).as_ref() != Some(&listing) { @@ -374,7 +403,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Ok(()) } "import" => { - ask_import(app); + ask_import(app, Some(source)); Ok(()) } _ => Ok(()), @@ -407,7 +436,7 @@ pub(crate) fn menu_items(names: &[String]) -> Vec { /// `ui.importSvgFilter {}`: add the filters of an SVG file the user picks to the active document. /// The answer is `{pending: "fileDialog"}`; the continuation runs the import. pub fn import_file(app: &mut VectorcraftApp) -> Result { - Ok(ask_import(app)) + Ok(ask_import(app, None)) } /// The extensions of the SVG files Import… reads. @@ -420,24 +449,33 @@ pub(crate) fn pick() -> PickRequest { /// Asks for an SVG file; once picked, its filters are added to the document and the first one /// added is selected in the dialog when it is open. -fn ask_import(app: &mut VectorcraftApp) -> Value { - file_asks::ask(app, pick(), Owner::Document, |app, picked| { - let params = match picked { - // The browser answers with the file's contents, not a path. - Picked::Contents(files) => { - let (_, bytes) = files.first().ok_or("cancelled")?; - json!({ "svg": String::from_utf8_lossy(bytes) }) +fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { + let dialog = source.clone().or_else(|| opening(app).filter(|opening| app.session.active().is_some_and(|st| st.uid == opening.document))); + file_asks::ask_while( + app, + pick(), + Owner::Document, + move |app| source.is_none_or(|source| opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &source))), + move |app, picked| { + let params = match picked { + // The browser answers with the file's contents, not a path. + Picked::Contents(files) => { + let (_, bytes) = files.first().ok_or("cancelled")?; + json!({ "svg": String::from_utf8_lossy(bytes) }) + } + other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), + }; + let r = app.run("svgFilter.import", params)?; + let added = r["added"].as_array().map_or(0, Vec::len); + app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); + if let Some(first) = r["added"].get(0) + && dialog.is_some_and(|dialog| opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &dialog))) + { + set(app, &[(SELECTED, first.clone())]); } - other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), - }; - let r = app.run("svgFilter.import", params)?; - let added = r["added"].as_array().map_or(0, Vec::len); - app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); - if let Some(first) = r["added"].get(0) { - set(app, &[(SELECTED, first.clone())]); - } - Ok(r) - }) + Ok(r) + }, + ) } #[cfg(test)] @@ -493,6 +531,31 @@ mod tests { assert!(open_dialogs(&app).is_empty()); } + #[test] + fn svg_filter_ok_leaves_the_other_drawings_artwork_alone() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let id = rect(&mut app); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + assert_eq!(rect(&mut app), id); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, &json!({})).unwrap(); + activate(&mut app, 1); + let dialog = dialog_id(KIND); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, id).is_empty()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)[SELECTED], "Shift"); + + activate(&mut app, 0); + answer_dialog(&mut app, dialog, &[], true); + assert_eq!(effects(&app, id)[0].params["name"], "Shift"); + } + #[test] fn the_dialog_draws_its_filters_and_buttons() { let mut app = app(); From 231e4452eded5086218d60743cc5f0eead1bc152 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:11:18 -0800 Subject: [PATCH 07/45] Keep shape dialog placement in the clicked document --- crates/ui-egui/src/dialogs/shapes.rs | 87 +++++++++++++++++++++++++--- 1 file changed, 80 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index d031aac572..ccdf07a76e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -35,6 +35,9 @@ pub(crate) const OPTION_TOOLS: [&str; 4] = ["rectangularGrid", "polarGrid", "arc /// link as the Transform panel's, and the next of these dialogs opens with it as this one left it. const SIZE_KINDS: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"]; +const CLICK_DOCUMENT: &str = "__clickDocument"; +const CLICK_ALT: &str = "__clickAlt"; + /// Where a shape tool was clicked: the dialog's shape is drawn there, and with `alt` held a box shape /// is centred on it. #[derive(Clone, Copy, Debug)] @@ -87,10 +90,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { if SIZE_KINDS.contains(&kind) { values.insert("constrain".into(), json!(app.object_dialogs.shape_link)); } - // The click is among the fields (no row shows it), where OK reads it. + // Keep the placement with the draft whose fields OK receives. if let Some(click) = click { + let Some(document) = app.session.active().map(|doc| doc.uid) else { + app.status(tl!("Open a document before drawing a shape").to_string()); + return; + }; values.insert("x".into(), json!(click.at.x)); values.insert("y".into(), json!(click.at.y)); + values.insert(CLICK_DOCUMENT.into(), json!(document.to_string())); + values.insert(CLICK_ALT.into(), json!(click.alt)); } let ink = (kind == "arc" && click.is_none()).then(|| ArcInk::of(&app.session)); let params = shape_params(kind, &values, lengths, ink); @@ -100,7 +109,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { ParamDialog::new(key.clone(), title, params.clone()).values(Bind::bound(fields)) }); let kind_owned = kind.to_owned(); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, click, &result.fields); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, &result.fields); if open_held(app, dialog, ok).is_none() { app.status(format!("no window to show the {kind} dialog")); } @@ -470,18 +479,28 @@ fn option_values(kind: &str, fields: &DialogFields) -> Option /// OK of the `kind` dialog: Tool Options set the tool's options and draw nothing; a click dialog draws at the /// click, then keeps the options and General › Corner Radius. Every refusal comes before the draw, so a refused OK /// draws nothing and the dialog stays open for a second OK. -fn confirm(app: &mut VectorcraftApp, kind: &str, click: Option, fields: &DialogFields) -> Result<(), String> { +fn confirm(app: &mut VectorcraftApp, kind: &str, fields: &DialogFields) -> Result<(), String> { let options = option_values(kind, fields); - let Some(click) = click else { + let Some(document) = fields.text(CLICK_DOCUMENT) else { return match options { Some(options) if OPTION_TOOLS.contains(&kind) => set_options(app, kind, options), _ => Err(format!("the {kind} tool has no options")), }; }; + let document = document.parse::().map_err(|_| tl!("The shape click document is missing").to_string())?; + if app.session.active().is_none_or(|doc| doc.uid != document) { + let reason = if app.session.documents().iter().any(|doc| doc.uid == document) { + tl!("Switch back to the document where you clicked to draw the shape") + } else { + tl!("The document where you clicked to draw the shape has closed") + }; + return Err(reason.into()); + } + let (Some(x), Some(y)) = (fields.number("x"), fields.number("y")) else { + return Err(tl!("The shape click position is missing").into()); + }; + let click = Click { at: Point::new(x, y), alt: fields.bool(CLICK_ALT).unwrap_or(false) }; let corner_radius = if kind == "roundedRectangle" { Some(rounded_radius(app, fields)?) } else { None }; - let at = |key, clicked| fields.number(key).unwrap_or(clicked); - let click = Click { at: Point::new(at("x", click.at.x), at("y", click.at.y)), ..click }; - let (x, y) = (click.at.x, click.at.y); let (width, height) = (length_of(fields, "width", 100.0), length_of(fields, "height", 100.0)); let (bx, by) = box_origin(click, width, height); let (id, params) = match kind { @@ -658,6 +677,60 @@ mod tests { app.session.doc().unwrap().doc.layers[0].children().unwrap().len() } + #[test] + fn rectangle_click_waits_for_its_opening_document() { + let (mut app, mut fx) = shown(); + let opening = app.session.doc().unwrap().uid; + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + set(&app, &fx, "rectangle", "width", json!(32.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + assert_ne!(app.session.doc().unwrap().uid, opening); + + press_ok(&mut app, &mut fx, "rectangle"); + assert_eq!(drawn(&app), 0, "OK must leave the other document unchanged"); + assert!(is_open(&app, "rectangle")); + + app.run("document.activate", json!({"index": 0})).unwrap(); + press_ok(&mut app, &mut fx, "rectangle"); + assert!(!is_open(&app, "rectangle")); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.x0 - 40.0).abs() < 1e-6 && (bounds.y0 - 60.0).abs() < 1e-6); + assert!((bounds.width() - 32.0).abs() < 1e-6); + } + + #[test] + fn a_reopened_rectangle_uses_the_replacement_click_and_modifier() { + let (mut app, mut fx) = shown(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 120.0, "y": 130.0, "alt": true})); + set(&app, &fx, "rectangle", "width", json!(20.0)).unwrap(); + set(&app, &fx, "rectangle", "height", json!(30.0)).unwrap(); + + press_ok(&mut app, &mut fx, "rectangle"); + + assert!(!is_open(&app, "rectangle")); + assert_eq!(drawn(&app), 1); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.center().x - 120.0).abs() < 1e-6 && (bounds.center().y - 130.0).abs() < 1e-6); + } + + #[test] + fn tool_options_can_be_confirmed_after_switching_documents() { + let (mut app, mut fx) = shown(); + open_options(&mut app, "lineSegment").unwrap(); + set(&app, &fx, "lineSegment", "length", json!(72.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + + press_ok(&mut app, &mut fx, "lineSegment"); + + assert!(!is_open(&app, "lineSegment")); + assert_eq!(drawn(&app), 0); + assert_eq!(app.session.tool_options_of("lineSegment")["length"], json!(72.0)); + } + #[test] fn spiral_click_dialog_uses_and_updates_tool_options() { let (mut app, mut fx) = shown(); From fc8575ecfbadc07a6c489ce1f9a890256d4994fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:18:52 -0800 Subject: [PATCH 08/45] Keep Export As attached to the original drawing --- crates/ui-egui/src/dialogs/export_as.rs | 23 +++++++++++++++++----- crates/ui-egui/src/dialogs/export_host.rs | 7 +++++-- crates/ui-egui/src/dialogs/tests_export.rs | 18 +++++++++++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 6e8f8bc1d2..30af709740 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -19,7 +19,7 @@ use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::export_host::{self, After, Export, Open}; +use super::export_host::{self, After, Export}; use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; use crate::{VectorcraftApp, io}; @@ -111,7 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); + let source = app.session.active().ok_or("no document")?; + let document = source.uid; + let n = source.doc.artboards.len(); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { Some((id, _)) => id, @@ -133,12 +135,20 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res }) .ok_label(Label::from("Export…")) }); - export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) + export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) +} + +fn require_source(app: &VectorcraftApp, document: u64) -> Result<(), String> { + if app.session.active().is_none_or(|source| source.uid != document) { + return Err(tl!("Return to the original drawing to export it").into()); + } + Ok(()) } /// Check the artboard range and that there is something to export; the save panel and the format's options or /// the file follow once the dialog has closed. -pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, document: u64, fields: &DialogFields) -> Result { + require_source(app, document)?; if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); } @@ -162,7 +172,10 @@ pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFie } let range = if all { "all".to_string() } else { range }; let pages = Pages { use_artboards, all, range, selection: false }; - Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages))))) + Ok(Some(Box::new(move |app| { + require_source(app, document)?; + io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages)) + }))) } /// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index efdc6c9f6d..2d45ad40ca 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -21,7 +21,10 @@ pub(crate) type After = Option Result Result<(), String> fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { match &open.kind { - Export::As => export_as::confirm(app, open, fields), + Export::As { document } => export_as::confirm(app, *document, fields), Export::Raster { .. } => png_options::confirm(app, open, fields), Export::Svg { .. } => svg_options::confirm(app, open, fields), Export::Eps => eps_options::confirm(app, open, fields), diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 016cf865aa..521cb19043 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -344,6 +344,24 @@ fn a_bad_range_keeps_export_as_open() { assert!(written.borrow().is_empty()); } +#[test] +fn export_as_waits_for_the_drawing_that_opened_it() { + let (mut app, written) = app(2); + app.run("file.exportAs", json!({"format": "png", "useArtboards": true, "range": "1"})).unwrap(); + app.run("file.new", json!({ "width": 200, "height": 100 })).unwrap(); + let error = try_confirm(&mut app).expect_err("Export As must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["range"], "1"); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); + app.run("document.activate", json!({ "index": 0 })).unwrap(); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + confirm(&mut app); + assert_eq!(written.borrow().len(), 1); + assert_eq!(&written.borrow()[0].1[16..20], 60u32.to_be_bytes()); +} + /// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then /// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the /// page size of a PDF of the art's bounds). From 9d6e81a22566632cc1651eec5b1db2342fe34145 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:21:45 -0800 Subject: [PATCH 09/45] Load browser-picked data sources in the Variables panel --- crates/engine/src/cmd/variablecmds.rs | 16 ++++++--- crates/ui-egui/src/panels/variables.rs | 50 +++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index db1a641f2f..c941ccb87e 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -876,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { /// result is that command's, with `format` set to `csv` or `xml`. fn variable_import(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.import"; - let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; - let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (name, input) = if let Some(path) = str_param(p, "path") { + (path, json!({"path": path})) + } else { + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?; + let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?; + (name, json!({"dataBase64": bytes})) + }; + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); let (format, mut out) = match ext.as_deref() { - Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), - Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?), + Some("xml") => ("xml", load_library(s, &input)?), _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), }; out["format"] = json!(format); @@ -1084,7 +1090,7 @@ pub fn specs() -> Vec { "Import…", ["Window", "Variables"], None, - "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + "{path? | name?, dataBase64?} import a data source from a path or from a file name with its bytes, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", has_doc, variable_import ), diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index e08d0bf603..1d32ff4d15 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -695,7 +695,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option fn ask_open(app: &mut VectorcraftApp, filters: &[(&str, &[&str])], command: &'static str) -> Value { let request = filters.iter().fold(PickRequest::open("variables"), |r, (name, exts)| r.filter(*name, exts)); file_asks::ask(app, request, Owner::Document, move |app, picked| match file_asks::open_params(&picked) { - Some(params) => app.run(command, Value::Object(params)), + Some(mut params) => { + // The combined importer uses the file name to choose a reader. The dedicated readers already know the format. + if command != "variable.import" { + params.remove("name"); + } + app.run(command, Value::Object(params)) + } None => Ok(Value::Null), }) } @@ -739,6 +745,48 @@ fn save_library(app: &mut VectorcraftApp) -> Value { #[cfg(test)] mod tests { use super::*; + + fn pick_variable_source(command: fn(&mut VectorcraftApp) -> Value, name: &str, bytes: &[u8]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + assert_eq!(command(&mut app), json!({"pending": "fileDialog"})); + picker.answer_contents(&[(name, bytes)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + app + } + + fn browser_xml() -> String { + let mut source = vectorcraft_engine::Session::new(); + source.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + source.execute("variable.define", &json!({"name": "Caption", "kind": "text"})).unwrap(); + source.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_owned() + } + + #[test] + fn browser_variable_import_reads_csv_and_tsv_from_the_file_name() { + for (name, bytes) in [("rows.CSV", &b"Caption,Other\nHello,World\n"[..]), ("rows.tsv", &b"Caption\tOther\nHello\tWorld\n"[..])] { + let app = pick_variable_source(import_data_source, name, bytes); + let data = &app.session.active().unwrap().doc.variables; + assert_eq!(data.datasets.len(), 1, "{name}"); + assert!(data.variables.iter().any(|v| v.name == "Caption")); + } + } + + #[test] + fn browser_variable_import_reads_xml_from_the_file_name() { + let app = pick_variable_source(import_data_source, "variables.XML", browser_xml().as_bytes()); + assert!(app.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption")); + } + + #[test] + fn browser_dedicated_variable_importers_accept_file_bytes() { + let csv = pick_variable_source(import_datasets, "rows.csv", b"Caption\nHello\n"); + assert_eq!(csv.session.active().unwrap().doc.variables.datasets.len(), 1); + let xml = pick_variable_source(load_library, "variables.xml", browser_xml().as_bytes()); + assert!(xml.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption")); + } use crate::i18n::LangExt; fn app_with_data() -> VectorcraftApp { From 8c552b60823bd6e3ed33f59b918858d637b5d092 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:33:25 -0800 Subject: [PATCH 10/45] Keep the overwrite-loss approval on the opening drawing --- crates/ui-egui/src/io/save.rs | 2 +- crates/ui-egui/src/tests/save.rs | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 98f082b312..1c82a3a7d7 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -877,7 +877,7 @@ pub(super) fn ask_before_losing(app: &mut VectorcraftApp, path: &str, command: & if command != "file.save" { params["path"] = json!(path); } - dialogs::confirm::ask(app, &message, &detail, command, params); + dialogs::confirm::ask_in_document(app, &message, &detail, command, params); Some(json!({ "pending": dialogs::confirm::KIND })) } diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index e92f4bbdf9..973c1f8895 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -515,3 +515,36 @@ fn revert_confirmation_never_discards_another_drawings_changes() { let _ = std::fs::remove_dir_all(d); assert_eq!(result, (count, true), "the second drawing must retain its unsaved edits"); } + +#[test] +fn acknowledging_import_loss_does_not_overwrite_the_source_with_another_drawing() { + let d = dir("lossy-drawing-switch"); + let path = d.join("source.vectorcraft").to_string_lossy().to_string(); + let mut app = app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let saved = std::fs::read(&path).unwrap(); + let st = app.session.doc_mut().unwrap(); + st.imported_from = Some(path.clone()); + st.import_losses = vec!["hidden type".into()]; + rect(&mut app); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + rect(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let params = json!({"path": path, "options": {"compress": true}}); + assert_eq!(app.run("file.saveAs", params.clone()).unwrap()["pending"], confirm::KIND); + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_top(&mut app, true); + crate::background::wait_all(&mut app); + let after_switch = std::fs::read(&path).unwrap(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.saveAs", params).unwrap(); + answer_top(&mut app, true); + crate::background::wait_all(&mut app); + let after_original = std::fs::read(&path).unwrap(); + let _ = std::fs::remove_dir_all(d); + assert!(after_switch == saved, "drawing B must never overwrite A's file"); + assert!(after_original != saved, "approval in drawing A must still save A"); +} From f656b063c8b1354d0d1e825dc5b019c981acf8c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:26:10 -0800 Subject: [PATCH 11/45] Keep Update Modified Links on its opening drawing --- crates/ui-egui/src/dialogs/missing_links.rs | 50 ++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 662cfa8876..baa715e660 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -415,7 +415,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec, one: &str, other: &str) -> Opt return Some(changed_on_disk_status(ids.len())); } let detail = crate::i18n::tn(ids.len() as u64, one, other); - super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); + super::confirm::ask_in_document(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); None } @@ -893,4 +893,52 @@ mod tests { assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); let _ = std::fs::remove_dir_all(dir); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn accepting_a_modified_link_offer_does_not_update_another_drawing() { + let dir = std::env::temp_dir().join(format!("vectorcraft-modified-switch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = drive::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.session.prefs.update_links = "askWhenModified".into(); + let mut ids = vec![]; + for name in ["first.png", "second.png"] { + let path = dir.join(name); + std::fs::write(&path, png([200, 0, 0])).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap(); + let links = app.run("links.list", json!({})).unwrap(); + ids.push(links["links"][0]["id"].as_u64().unwrap()); + let stamp = std::fs::metadata(&path).unwrap().modified().unwrap(); + std::fs::write(&path, png([0, 0, 200])).unwrap(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2))) + .unwrap(); + } + assert_eq!(ids[0], ids[1], "the same ID refers to different files"); + let answer = |app: &mut VectorcraftApp| { + let question = crate::tests::picks::open_dialogs(app).pop().unwrap().id; + crate::tests::picks::answer_dialog(app, question, &[], true); + }; + + app.run("document.activate", json!({"index": 0})).unwrap(); + ask_update_changed(&mut app, vec![json!(ids[0])]); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + answer(&mut app); + let foreign_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + ask_update_changed(&mut app, vec![json!(ids[0])]); + answer(&mut app); + let original_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(foreign_modified, 1, "the second drawing's link still needs approval"); + assert_eq!(original_modified, 0, "approval updates the first drawing's link"); + } } From a2b5c8cde2ac6e5c6f58ee47f2da1ad7a723328b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:38:01 -0800 Subject: [PATCH 12/45] Color Picker: keep artboard background edits in their document --- crates/ui-egui/src/dialogs/color_picker.rs | 47 ++++++++---- .../ui-egui/src/dialogs/color_picker/tests.rs | 74 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 1 + docs/target-app-parity.md | 2 +- 5 files changed, 109 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index e0ad66addf..f9649382bf 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -3,7 +3,7 @@ //! as one undo step through `paint.setFill` / `paint.setStroke` and makes the colour the Color //! Guide's base colour; Cancel puts the art back. Opened for an artboard (Properties › Artboards › //! Fill), it shows the colour on the artboard's paper and OK keeps it through -//! `artboard.setProps {index, color}`. +//! `artboard.setProps {index, color}`. Preview and OK require the opening document to be active. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog //! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor @@ -43,11 +43,18 @@ pub(crate) enum Target { /// The stroke proxy. Stroke, /// The background colour of this artboard. - Artboard(usize), + Artboard { document: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, } +impl Target { + fn in_active_document(&self, app: &VectorcraftApp) -> bool { + let Self::Artboard { document, .. } = self else { return true }; + app.session.active().is_some_and(|st| st.uid == *document) + } +} + /// One open Color Picker: what the dialog itself does not know. pub(crate) struct Open { /// The dialog's id on the window's host. @@ -150,14 +157,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => { let index = v.as_u64().and_then(|i| usize::try_from(i).ok()); - let found = index.and_then(|i| Some((i, app.session.active()?.doc.artboards.get(i)?.color))); - let (i, color) = found.ok_or("no such artboard")?; - Some((i, color.unwrap_or(Color::WHITE))) + let found = index.and_then(|i| { + let st = app.session.active()?; + let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE); + Some((st.uid, i, color)) + }); + Some(found.ok_or("no such artboard")?) } }; let color = match (p.get("color"), artboard) { (Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?, - (None, Some((_, c))) => c, + (None, Some((_, _, c))) => c, (None, None) => proxy_color(app, stroke), }; let dialogs = app.dialogs().ok_or("no window")?; @@ -184,9 +194,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { dialog = dialog.kept(model_values(&color)); } - // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. - if let Some((i, _)) = artboard { - dialog = dialog.instance(i); + // The host replaces a picker only for the same document and artboard. + if let Some((document, index, _)) = artboard { + dialog = dialog.instance((document, index)); } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. @@ -196,7 +206,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let _ = app.session.cancel_interaction(); } let target = match artboard { - Some((i, _)) => Target::Artboard(i), + Some((document, index, _)) => Target::Artboard { document, index }, None if stroke => Target::Stroke, None => Target::Fill, }; @@ -274,6 +284,13 @@ fn finish( open: &mut Open, result: Option>, ) { + // Switching documents rolls back the source preview. Do not settle it against the new drawing. + if !open.target.in_active_document(app) { + if matches!(result, Some(DialogResult::Ok(_))) { + app.status("The active document changed while the Color Picker was open"); + } + return; + } let preview = std::mem::take(&mut open.preview); match (result, &open.target) { (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { @@ -293,7 +310,7 @@ fn finish( /// The command that applies colour `c` to the picker's target, and its params. fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { - Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), + Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } @@ -314,18 +331,18 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); let untouched = !app.session.in_interaction() && picked.color == open.start; - let artboard = matches!(open.target, Target::Artboard(_)); + let artboard = matches!(open.target, Target::Artboard { .. }); let selected = artboard || app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); if untouched || !selected { return; } let label = match open.target { - Target::Artboard(_) => "Artboard Options", + Target::Artboard { .. } => "Artboard Options", Target::Stroke => "Stroke Color", _ => "Fill Color", }; @@ -342,7 +359,7 @@ fn commit(app: &mut VectorcraftApp, open: &Open, preview: LivePreview, picked: & let (cmd, params) = paint_command(&open.target, c); preview.commit(app, cmd, params)?; // A color picked for the fill or stroke also becomes the Color Guide's base color. - if !matches!(open.target, Target::Artboard(_)) { + if !matches!(open.target, Target::Artboard { .. }) { crate::panels::color_guide::choose_base(app, c); } Ok(()) diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 47b1ad268f..26e3bf486b 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -52,6 +52,15 @@ fn artboard_color(app: &VectorcraftApp) -> Option { app.session.doc().unwrap().doc.artboards[1].color } +fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = app(); + app.run("artboard.new", json!({})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("artboard.new", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx) +} + /// The selected art takes each colour as it is picked; OK keeps the last as one undo step and /// Cancel puts the art back. #[test] @@ -101,6 +110,71 @@ fn an_artboard_shows_its_background_color_live() { assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err()); } +#[test] +fn the_artboard_picker_previews_only_in_its_opening_document() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let before = undo_len(&app); + set_hex(&mut app, &ctx, "#00ff00"); + assert_eq!(artboard_color(&app), None, "the other document never previews the color"); + assert!(!app.session.in_interaction()); + assert_eq!(undo_len(&app), before); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None, "leaving the source rolled its preview back"); + let before = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + assert_eq!(undo_len(&app), before + 1); +} + +#[test] +fn confirming_an_artboard_picker_in_another_document_leaves_both_unchanged() { + let (mut app, ctx) = two_documents_with_artboards(); + let source_undo = undo_len(&app); + app.run("ui.colorPicker", json!({"artboard": 1, "color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx); + app.run("document.activate", json!({"index": 1})).unwrap(); + let destination_undo = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(app.ui.status, "The active document changed while the Color Picker was open"); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), destination_undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), source_undo); +} + +#[test] +fn canceling_an_artboard_picker_preserves_the_other_documents_interaction() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("artboard.setProps", &json!({"index": 1, "color": "#445566"})).unwrap(); + + cancel(&mut app, &ctx); + assert!(app.session.in_interaction(), "the current document keeps its own interaction"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#445566")); +} + +#[test] +fn artboard_pickers_for_the_same_index_in_different_documents_have_separate_instances() { + let (mut app, _) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + let first = id(&app); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + assert_ne!(id(&app), first); + assert_eq!(app.color_dialogs.pickers.len(), 2); +} + /// OK on an untouched picker for an artboard without a color leaves it without one and adds no /// undo step; a white the opener passes as `color` is set. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4da3dcdc16..e4d6d5d1c1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1097,7 +1097,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active", ), ( "ui.sampleScreenColor", diff --git a/docs/mcp.md b/docs/mcp.md index 6f567df149..3e32a1be83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10194,6 +10194,7 @@ layer of its own below the others; files that carry the editing data (Preserve E Export for Screens) keep it as the artboard's color, not as art. `includeArtboardFill: false` on `document.export`, `document.serialize`, `document.exportForScreens` (Include Artboard Fill) or `file.print` leaves it out. `inspect_document` lists it as the artboard's `color` (`#rrggbb`), and `ui.colorPicker {artboard: index}` opens the Color Picker for it. +The artboard preview and confirmation require the opening document to be active. Artboard Options' Show Center Mark and Show Cross Hairs: `artboard.setProps {index, showCenterMark?: bool, showCrossHairs?: bool}` (or each entry of `artboards`) turns them on or off for that artboard in one undo step, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df69c18888..73a7b616d6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -970,7 +970,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). -- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). +- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard preview and confirmation require its opening document to be active. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). - **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. From 854bc6430f3b63fa17d41e0fd143abc32d052642 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:39:33 -0800 Subject: [PATCH 13/45] Confirm the mounted SVG Filter opening after replacement --- crates/ui-egui/src/dialogs/svg_filter.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index ccd6bed543..9f7a412b9a 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -302,8 +302,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone()))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build); - crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { - if app.session.active().is_none_or(|st| st.uid != document) { + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let source = opening(app).ok_or("the SVG Filter dialog is gone")?; + if app.session.active().is_none_or(|st| st.uid != source.document) { return Err(tl!("Return to the original drawing to apply this SVG filter").into()); } confirm(app, &result.fields) @@ -556,6 +557,23 @@ mod tests { assert_eq!(effects(&app, id)[0].params["name"], "Shift"); } + #[test] + fn reopened_svg_filter_uses_the_replacement_openings_drawing() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let first = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let second = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog_id(KIND), &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, second).first().map(|f| f.params["name"].clone()), Some(json!("Shift"))); + assert!(open_dialogs(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(effects(&app, first).is_empty()); + } + #[test] fn the_dialog_draws_its_filters_and_buttons() { let mut app = app(); From 20677e3ec83cfcf5de59ada568c68d242d6de221 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:48:25 -0800 Subject: [PATCH 14/45] Exercise Bullets and Numbering after switching drawings --- .../ui-egui/src/dialogs/bullets_numbering.rs | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index b371adb13b..96989cdf6d 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -641,6 +641,79 @@ mod tests { with_dialog(app, |d| params(d)) } + fn other_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let id = app + .run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + id + } + + #[test] + fn bullets_preview_pauses_in_another_drawing() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + let other = other_drawing(&mut app); + let before = first(&app, other); + + frame(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + + #[test] + fn bullets_ok_does_not_change_the_other_drawings_type() { + let (mut app, id) = app(); + let opening = first(&app, id); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "number", Some("arabic")); + let other = other_drawing(&mut app); + let before = first(&app, other); + let undo = app.session.doc().unwrap().history.undo.len(); + + ok(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + } + + #[test] + fn bullets_cancel_keeps_the_other_drawings_pending_edit() { + let (mut app, id) = app(); + let opening = first(&app, id); + let other = other_drawing(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + frame(&mut app); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other paragraph edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap(); + let editing = first(&app, other); + assert_eq!(editing.1, 41.0); + cancel(&mut app); + + assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(first(&app, other), editing); + app.session.commit_interaction().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + } + /// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the /// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo /// takes back. From 5de9c949a006037d2ab458b2977e705ceb0a4157 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:53:39 -0800 Subject: [PATCH 15/45] Keep Tate-chu-yoko Settings in the opening drawing --- crates/ui-egui/src/dialogs/tate_chu_yoko.rs | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index 8111cfe239..edb0fb5bf6 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -38,6 +38,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Tate-chu-yoko Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; let (up, right) = crate::panels::character::shared_tcy_offsets(app); let mut fields = DialogFields::new(); for (key, v) in KEYS.into_iter().zip([up, right]) { @@ -52,6 +53,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned()); + } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; @@ -133,6 +137,42 @@ mod tests { assert_eq!(offsets(&app, id), [(0.0, 0.0)]); } + #[test] + fn tate_chu_yoko_settings_refuses_confirmation_in_another_drawing() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, source_id) = app(); + let source_before = offsets(&app, source_id); + let source_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app"); + + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [target_id]})).unwrap(); + let target_before = offsets(&app, target_id); + let target_undo = app.session.active().unwrap().history.undo.len(); + driver::pump(&mut app); + assert_eq!( + (offsets(&app, target_id), app.session.active().unwrap().history.undo.len()), + (target_before, target_undo), + "the other drawing's text and undo history stay untouched" + ); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(driver::fields(&app).number("tcyUpDown"), Some(7.0)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [source_id]})).unwrap(); + assert_eq!(offsets(&app, source_id), source_before); + assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing"); + assert_eq!(offsets(&app, source_id), [(7.0, 0.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + /// While the Type tool edits text, OK sets the selected characters. #[test] fn tate_chu_yoko_settings_dialog_sets_the_range_the_type_tool_selects() { From 82d4d41a26190782a717270b812b2b652c67f190 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:53:39 -0800 Subject: [PATCH 16/45] Keep Warichu Settings in the opening drawing --- crates/ui-egui/src/dialogs/warichu.rs | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/ui-egui/src/dialogs/warichu.rs b/crates/ui-egui/src/dialogs/warichu.rs index cbce874539..123d52f407 100644 --- a/crates/ui-egui/src/dialogs/warichu.rs +++ b/crates/ui-egui/src/dialogs/warichu.rs @@ -68,6 +68,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Warichu Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; let shared = crate::panels::character::shared_warichu(app); let mut fields = DialogFields::new(); set_shared(&mut fields, KEYS[0], shared.lines.map(i64::from)); @@ -83,6 +84,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Warichu Settings can only change the document where it was opened.").to_owned()); + } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; @@ -260,6 +264,42 @@ mod tests { assert_eq!(params(&fields, &initial).get("warichuGap"), Some(&json!(MAX_WARICHU_GAP))); } + #[test] + fn warichu_settings_refuses_confirmation_in_another_drawing() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, source_id) = app(); + let source_before = settings(&app, source_id); + let source_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.warichuSettings", json!({})).unwrap(); + driver::set(&mut app, "warichuLines", json!(4)); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app"); + + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [target_id]})).unwrap(); + let target_before = settings(&app, target_id); + let target_undo = app.session.active().unwrap().history.undo.len(); + driver::pump(&mut app); + assert_eq!( + (settings(&app, target_id), app.session.active().unwrap().history.undo.len()), + (target_before, target_undo), + "the other drawing's text and undo history stay untouched" + ); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(driver::fields(&app).number("warichuLines"), Some(4.0)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [source_id]})).unwrap(); + assert_eq!(settings(&app, source_id), source_before); + assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing"); + assert_eq!(settings(&app, source_id), [(false, 4, 0.0, 50.0, WarichuAlign::Auto)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + /// While the Type tool edits text, OK sets the selected characters. #[test] fn warichu_settings_dialog_sets_the_range_the_type_tool_selects() { From f0a6102277ab6e8a97f9b1720b333c8bd1e33938 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:56:49 -0800 Subject: [PATCH 17/45] Keep Dimension Properties color edits in their source drawing --- crates/ui-egui/src/dialogs/dimension.rs | 55 +++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index b53bab2351..60ff63e67f 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -143,13 +143,15 @@ struct Edited { pick: Option, } -/// The Properties section's colour picker: the dialog it opened, the colour it answers for and the dimension it edits. +/// The Properties section's colour picker and the swatch, document and dimension it edits. #[derive(Clone, Debug)] pub(crate) struct Pick { /// The open colour picker. pub id: DialogId, /// The key of the swatch that asked. pub key: String, + /// The document that contains the dimension. + pub document: u64, /// The dimension the colour goes to. pub target: NodeId, } @@ -340,8 +342,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { let Some(pick) = app.object_dialogs.dimension.clone() else { return }; let Some(finished) = dialogs.with(|host| host.take_by_id::(pick.id)) else { return }; app.object_dialogs.dimension = None; - if let Some(ColorPickerResult { picked, .. }) = finished.ok() - && let Some(mut o) = options_of(app, pick.target) + let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return }; + if app.session.active().map(|st| st.uid) != Some(pick.document) { + app.status("The active document changed while the Color Picker was open"); + return; + } + if let Some(mut o) = options_of(app, pick.target) && set_color(&mut o, &pick.key, picked.color) { update(app, pick.target.0, &o); @@ -715,12 +721,13 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if let Some(request) = edited.pick + && let Some(document) = app.session.active().map(|st| st.uid) && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); let picker = dialogs.with(|host| host.open(picker)); - app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); + app.object_dialogs.dimension = Some(Pick { id: picker, key, document, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { if Button::new(tl!("Apply to All")).show(ui).clicked() @@ -775,6 +782,46 @@ mod tests { serde_json::from_value(app.borrow().session.tool_options_of("dimension")["style"].clone()).unwrap() } + #[test] + fn dimension_properties_picker_keeps_its_source_document() { + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut add_dimension = |line_color: [u8; 3]| { + app.run("file.new", json!({"width":200,"height":200})).unwrap(); + let created = app.run("dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"lineColor":line_color}})).unwrap(); + let id = created["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids":[id]})).unwrap(); + NodeId(id) + }; + let source = add_dimension([17, 34, 51]); + let other = add_dimension([51, 34, 17]); + assert_eq!(source, other, "each drawing allocates its own object ids"); + app.run("document.activate", json!({"index":0})).unwrap(); + + let mut panel = Panel::new(app, properties_section); + let ctx = panel.ctx().clone(); + let host = WindowDialogs::of(&ctx, &WindowKey::main()); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + panel.app().run("document.activate", json!({"index":1})).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), other).unwrap().line_color, [51, 34, 17]); + + panel.app().run("document.activate", json!({"index":0})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [18, 52, 86]); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + } + /// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head /// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate /// cannot be saved. From b71cab6473f460893f8e72e65f17c278248659fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:53:47 -0800 Subject: [PATCH 18/45] Keep Bullets and Numbering edits in the opening drawing --- .../ui-egui/src/dialogs/bullets_numbering.rs | 215 ++++++++++++++---- crates/ui-egui/src/lib.rs | 2 +- 2 files changed, 173 insertions(+), 44 deletions(-) diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 96989cdf6d..2b85bb6394 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -25,18 +25,21 @@ //! . use std::borrow::Cow; +use std::sync::{Arc, Weak}; use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; -use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::pickers::Select; use craft::ui::primitives::{HAlign, IconSpec, TextRun}; -use craft::ui::runtime::env::{Env, LengthUnits}; +use craft::ui::runtime::env::{Env, Label, LengthUnits}; +use craft::ui::runtime::measure; +use craft::ui::runtime::overlay::CloseReason; use craft::ui::runtime::words::CommonWords; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::tabs::{Tab, TabKind, TabStrip}; @@ -44,11 +47,14 @@ use craft::ui::text::NumberField; use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid}; use egui::{Context, Ui}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use crate::VectorcraftApp; use crate::panels::paragraph::BulletGlyph; +use super::preview::LivePreview; + /// The dialog kind of Bullets and Numbering. pub const KIND: &str = "bulletsAndNumbering"; @@ -122,9 +128,70 @@ pub(crate) struct BulletsDialog { hanging: bool, /// The General unit the indent fields show; the pump keeps it current. lengths: LengthUnits, + active_document: bool, + held: HeldAnswer>, open: bool, } +/// The preview from the opening drawing and the interaction that owns its undo snapshot. +pub(crate) struct Preview { + document: u64, + live: LivePreview, + selection: Option>, +} + +impl Preview { + fn owns_interaction(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn update(&mut self, app: &mut VectorcraftApp, fields: Map) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return }; + if !self.owns_interaction(app) { + self.live = LivePreview::default(); + self.selection = None; + if state.interaction.is_some() { + return; + } + } + let on = changes(&fields); + let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some(); + if !on { + self.selection = None; + } else if ran { + self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } + } + + fn apply(&mut self, app: &mut VectorcraftApp, fields: Map) -> Result<(), String> { + if !changes(&fields) { + if self.owns_interaction(app) { + std::mem::take(&mut self.live).cancel(app); + self.selection = None; + } + return Ok(()); + } + if app.session.active().is_none_or(|state| state.uid != self.document) { + return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned()); + } + if app.session.in_interaction() && !self.owns_interaction(app) { + return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned()); + } + self.selection = None; + std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_interaction(app) { + self.live.cancel(app); + } + } +} + /// The kind of list `list` is, as the `list` field names it. fn kind(list: Option) -> &'static str { match list { @@ -144,8 +211,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), }; crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; // A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own. - std::mem::take(&mut app.bullets_preview).cancel(app); + if let Some(old) = app.bullets_preview.take() { + old.cancel(app); + } // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { @@ -192,9 +262,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { targets, hanging: false, lengths: crate::canvas::general_lengths(app), + active_document: true, + held: HeldAnswer::default(), open: true, }; host.with(|h| h.open(dialog)); + app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None }); Ok(Value::Null) } @@ -468,8 +541,7 @@ fn changes(p: &Map) -> bool { } impl StackDialog for BulletsDialog { - /// The `text.setFormat` parameters OK runs. - type Result = Value; + type Result = (); fn id(&self) -> DialogId { dialog_id(KIND) @@ -479,20 +551,46 @@ impl StackDialog for BulletsDialog { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let common = Env::of(ui).words::(); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let finish = self.held.is_accepted(); + let refusal = self.held.refusal().map(|(reason, _)| reason.clone()); + let buttons = [ + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()), + FooterButton::new(common.cancel.clone(), DialogRole::Cancel), + ]; let mut open = self.open; - let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)); - let shown = dialog.show(ui, |ui, _| self.body(ui)); + let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone()); + let shown = dialog.show(ui, |ui, cx| { + if finish && !measure::active(ui.ctx()) { + cx.request_close_as(CloseReason::Activated); + } + self.body(ui); + }); self.open = open; let DialogOutput { closed, picked, .. } = shown.output; - closed?; - Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel }) + if picked == Some(OK) && !self.held.is_waiting() { + self.held.file(params(self)); + } + match closed { + Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())), + Some(_) => Some(DialogResult::Cancel), + None => None, + } } - fn confirm(&mut self, _: &Context) -> Option { - Some(Value::Object(params(self))) + fn confirm(&mut self, _: &Context) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(drop); + } + if !self.held.is_waiting() { + self.held.file(params(self)); + } + None + } + + fn held_state(&self) -> Option { + self.held.state() } fn json_fields(&self) -> Option { @@ -515,38 +613,41 @@ impl StackDialog for BulletsDialog { } } -/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change -/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box -/// too) and an OK that changes nothing put the type back. +/// Shows the draft on its opening drawing and answers OK before the dialog closes. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let Some(host) = app.dialogs() else { return }; - if let Some(result) = host.with(|h| h.take::()) { - let live = std::mem::take(&mut app.bullets_preview); - match result { - DialogResult::Ok(Value::Object(p)) if changes(&p) => { - if let Err(e) = live.commit(app, CMD, Value::Object(p)) { - app.status(e); - // The dialog is gone: a preview the refused OK left running goes with it. Nothing runs - // when the refusal came before the interaction began, which is the right outcome too. - let _ = app.session.cancel_interaction(); - } - } - _ => live.cancel(app), - } - } + let Some(mut preview) = app.bullets_preview.take() else { return }; + let active_document = app.session.active().is_some_and(|state| state.uid == preview.document); let lengths = crate::canvas::general_lengths(app); - // The host's lock is released before the preview runs: a command never runs inside `with`. - let Some(p) = host.with(|h| { + let Some((fields, answer)) = host.with(|h| { h.get_mut::().map(|d| { d.lengths = lengths; - params(d) + let fields = params(d); + if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) { + d.held.clear_refusal(); + } + d.active_document = active_document; + (fields, d.held.take()) }) }) else { + preview.cancel(app); return; }; - let mut live = std::mem::take(&mut app.bullets_preview); - let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p)); - app.bullets_preview = live; + if let Some(answer) = answer { + let result = preview.apply(app, answer).map_err(Label::from); + let accepted = result.is_ok(); + host.with(|h| { + if let Some(dialog) = h.get_mut::() { + dialog.held.answer(result); + } + }); + if accepted { + return; + } + } else { + preview.update(app, fields); + } + app.bullets_preview = Some(preview); } #[cfg(test)] @@ -618,13 +719,23 @@ mod tests { crate::dialogs::host::pump(app, &ctx); } - /// OK on the open dialog, as automation answers it, then the frame's pump. - fn ok(app: &mut VectorcraftApp) { + fn press_ok(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); - assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled"); + let host = app.dialogs().unwrap(); + host.with(|h| { + assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first"); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); frame(app); } + /// Files OK and closes with the accepted answer, as the view or automation does. + fn ok(app: &mut VectorcraftApp) { + press_ok(app); + let (ctx, (id, _)) = (window(app), top(app)); + assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK"); + } + /// Cancel on the open dialog, as Esc gives it, then the frame's pump. fn cancel(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); @@ -643,9 +754,7 @@ mod tests { fn other_drawing(app: &mut VectorcraftApp) -> u64 { app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); - let id = app - .run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})) - .unwrap()["id"] + let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"] .as_u64() .unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); @@ -681,12 +790,18 @@ mod tests { let before = first(&app, other); let undo = app.session.doc().unwrap().history.undo.len(); - ok(&mut app); + press_ok(&mut app); assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK"); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_))))); + assert_eq!(fields(&app)["number"], "arabic"); app.run("document.activate", json!({"index": 0})).unwrap(); assert_eq!(first(&app, id), opening); + frame(&mut app); + assert!(with_dialog(&app, |d| d.held.state().is_none())); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic))); } #[test] @@ -714,6 +829,20 @@ mod tests { assert_eq!(first(&app, id), opening); } + #[test] + fn accepted_bullets_close_on_the_next_view_pass() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + press_ok(&mut app); + let ctx = window(&app); + + crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]); + + assert!(!is_open(&app)); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + /// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the /// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo /// takes back. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a9b143e397..d6b89d08af 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -317,7 +317,7 @@ pub struct VectorcraftApp { /// The Justification dialog, while it is open. pub(crate) justification: Option, /// The Bullets and Numbering dialog's live preview. - pub(crate) bullets_preview: dialogs::preview::LivePreview, + pub(crate) bullets_preview: Option, /// The paste that waits for the answer to its colour profile question. pub(crate) pending_paste: Option, /// The missing links' questions, while they are asked. From 833bdff60d0c9c3830f7c6d56b042bbdfae3d881 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:03:18 -0800 Subject: [PATCH 19/45] Keep justification on its opening drawing and text --- crates/ui-egui/src/dialogs/justification.rs | 85 ++++++++++++++++++++- 1 file changed, 82 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 378c5bbe21..5b97daaedd 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -36,6 +36,8 @@ const CMD: &str = "text.setFormat"; pub(crate) struct Open { /// The dialog on the host. pub id: DialogId, + /// The drawing that owns the text IDs and the preview. + document: u64, /// The preview on the canvas. pub preview: LivePreview, /// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on. @@ -47,6 +49,12 @@ pub(crate) struct Open { initial: DialogFields, } +impl Open { + fn in_opening_document(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| st.uid == self.document) + } +} + /// The three spacing rows: (`text.setFormat` key, field prefix, range). const ROWS: [(&str, &str, (f64, f64)); 3] = [ ("wordSpacing", "word", JustificationOptions::WORD_SPACING), @@ -108,6 +116,7 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> { /// Open Justification on the paragraph attributes the Paragraph panel shows. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document open")?.uid; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; @@ -136,20 +145,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off(); let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; + if !open.in_opening_document(app) { + app.justification = Some(open); + return Err(tl!("This dialog was opened in a different document.").to_owned()); + } let p = params(app, &result.fields, &open); if !changes(&p) { // Nothing to apply: end the preview as production's OK did. open.preview.cancel(app); return Ok(()); } - let Open { id, preview, targets, story, initial } = open; + let Open { id, document, preview, targets, story, initial } = open; preview.commit(app, CMD, Value::Object(p)).map(|_| ()).inspect_err(|_| { // The dialog stays open on the refusal, with a preview of its own again. - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial }); }) }) .ok_or("no window")?; - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial: fields }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial: fields }); Ok(Value::Null) } @@ -200,6 +213,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.justification.take() else { return }; let shown = app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); + // A document switch ends that document's preview. The active drawing may have started a different one. + if !open.in_opening_document(app) { + if shown.is_some() { + open.preview = LivePreview::default(); + app.justification = Some(open); + } + return; + } // The host lock is released: a command never runs inside `DialogHost::with`. let Some((on, fields)) = shown else { open.preview.cancel(app); @@ -433,4 +454,62 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame"); } + + fn two_drawings() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(id, second, "local text IDs may match between drawings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, id) + } + + #[test] + fn justification_approval_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::ok(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(driver::is_open(&app)); + assert_eq!(driver::fields(&app).number("autoLeading"), Some(180.0)); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::ok(&mut app); + assert!(!driver::is_open(&app)); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + } + + #[test] + fn justification_preview_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + } + + #[test] + fn cancelling_justification_keeps_the_other_drawings_new_interaction() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("New text edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [id], "autoLeading": 190})).unwrap(); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0); + assert!(app.session.in_interaction()); + } } From 0ee52788c36479babdf01eb7f2f2e254a8747bdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:06:36 -0800 Subject: [PATCH 20/45] Actions: refuse Options confirmations on a changed library --- .../ui-egui/src/dialogs/action_set_options.rs | 29 ++++++++++++------- .../ui-egui/src/panels/actions/tests_edits.rs | 23 +++++++++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 8bf20b57c9..29fe71991d 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -6,8 +6,8 @@ //! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`, //! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one, //! renames the set, or changes the action's name, function key and color (`ui.action.options`). -//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK -//! then changes no set or action, and the dialog stays open. +//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a +//! library change while editing an existing set or action. The dialog stays open with the error. use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id}; @@ -67,12 +67,14 @@ pub struct SetOptionsDialog { pub set: Option, /// The index of the action in its set; only for Action Options. pub action: Option, + /// The action library revision these addresses described when Options opened. + revision: Option, form: Form, } impl SetOptionsDialog { - fn new(kind: SetOptionsKind, set: Option, action: Option, fields: SetOptionsFields) -> Self { - SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) } + fn new(kind: SetOptionsKind, set: Option, action: Option, revision: Option, fields: SetOptionsFields) -> Self { + SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) } } } @@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) { let sets = app.ui.actions.sets(); let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1); let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields)); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, None, fields)); } /// Open Set Options for the set at `set`, if there is one. pub fn open(app: &mut VectorcraftApp, set: usize) { if let Some(name) = model::set_name(&app.ui.actions, set) { let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields)); } } @@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { automatic_align_to: model::automatic_align_to(a), }; let fields = SetOptionsFields { name: a.name.clone(), options }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields)); } impl ActionDialog for SetOptionsDialog { - /// What OK files, with the kind and place the dialog had. - type Answer = (SetOptionsKind, Option, Option, SetOptionsFields); + /// What OK files, with the kind, place and library revision the dialog had. + type Answer = (SetOptionsKind, Option, Option, Option, SetOptionsFields); fn take_ok(&mut self) -> Option { - self.form.take().map(|fields| (self.kind, self.set, self.action, fields)) + self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { self.form.answer(answer); } - fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> { + fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> { + if revision.is_some_and(|revision| app.ui.actions.revision() != revision) { + return Err("The action library changed. Reopen Options to edit it.".into()); + } match kind { SetOptionsKind::NewSet => edits::new_set(app, &fields.name), SetOptionsKind::Set => { diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index a2f5247c91..d83e306f05 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -203,6 +203,29 @@ fn options_with_a_field_that_is_not_an_index_change_nothing() { } } +#[test] +fn stale_action_options_do_not_rename_the_copy_that_took_its_index() { + let mut app = app_with_sets(); + crate::dialogs::action_set_options::open_action(&mut app, 1, 1); + set_dialog::(&mut app, "name", json!("Wrong target")); + assert_eq!(app.run(DUPLICATE, json!({"set": 1, "action": 0})).unwrap(), json!({"set": 1, "action": 1})); + let before = action_names(&app, 1); + assert!(confirm_dialog::(&mut app).is_err(), "an index taken by a copy must refuse OK"); + assert!(is_open::(&app)); + assert_eq!(action_names(&app, 1), before); +} + +#[test] +fn stale_set_options_do_not_rename_the_set_that_took_its_index() { + let mut app = app_with_sets(); + crate::dialogs::action_set_options::open(&mut app, 1); + set_dialog::(&mut app, "name", json!("Wrong target")); + app.ui.actions.delete_set("Mine").unwrap(); + assert!(confirm_dialog::(&mut app).is_err(), "an index taken by the next set must refuse OK"); + assert!(is_open::(&app)); + assert_eq!(set_names(&app), ["Default Actions", "Other"]); +} + /// `ui.actionSet.delete` moves the panel's selected action down with its set, and clears it /// when its set is deleted. #[test] From 68a709ca6753b1fe1a9b280c77d6c0725d92e753 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:06:48 -0800 Subject: [PATCH 21/45] Keep web export artboards visible when the dialog opens --- .../ui-egui/src/dialogs/export_for_screens.rs | 5 +++ crates/ui-egui/src/dialogs/tests_screens.rs | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 0211830949..3011330cf5 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -45,6 +45,7 @@ use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleS use craft::ui::patterns::form_dialogs::{FormDialog, PathRow}; use craft::ui::primitives::{ContentPainterCx, fit_rect}; use craft::ui::runtime::env::Label; +use craft::ui::runtime::focus::Initial; use craft::ui::tabs::{Tab, TabKind, TabStrip}; use craft::ui::text::TextField; use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent}; @@ -958,6 +959,10 @@ impl StackDialog for ExportForScreensDialog { let mut held = std::mem::take(&mut self.held); let mut dialog = FormDialog::new(tl!("Export for Screens"), Bind::bound(&mut fields)).ok_label(ok).ok_enabled(chosen.is_none()).held(&mut held); + if self.web { + // Keep the first artboard visible when the web dialog opens in a short viewport. + dialog = dialog.shaped(|surface| surface.initial_focus(Initial::First)); + } if let Some(reason) = chosen { dialog = dialog.ok_reason(reason); } diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index af68809f46..1648e86648 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -61,6 +61,51 @@ fn open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn the_first_artboard_is_clickable_on_open_in_a_short_web_viewport() { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + app.run("artboard.rename", json!({"indices": [0], "name": "First audit board"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 500.0)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.2; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + open(&mut app); + set(&mut app, "view", json!(view)); + for _ in 0..5 { + draw(&mut app, vec![]); + } + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let bounds = nodes + .iter() + .find_map(|(_, node)| { + if node.role() == Role::CheckBox && node.label().is_some_and(|label| label.contains("First audit board")) { + node.bounds() + } else { + None + } + }) + .expect("the first artboard has a checkbox"); + let pos = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + + assert_eq!(field(&app, "boards"), json!([true, true])); + draw(&mut app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + assert_eq!(field(&app, "boards"), json!([false, true]), "the first {view} checkbox should be clickable without scrolling"); + assert!(log.borrow().is_empty()); + } +} + /// Presses OK, which the dialog refuses or does not offer: it stays open. fn stays_open(app: &mut VectorcraftApp) { let _ = try_confirm(app); From c94629e98d8a97ea6d1f4e388416f871a6484d2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:16 -0800 Subject: [PATCH 22/45] Dismiss Simplify and Smooth sliders when leaving their drawing --- crates/ui-egui/src/dialogs/simplify_slider.rs | 40 ++++++++++++++++--- crates/ui-egui/src/dialogs/tests_modal.rs | 28 +++++++++++++ 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index e0040bb228..23ed5cfa85 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -85,6 +85,8 @@ impl StripKind { pub(crate) struct Strip { /// Which command the strip previews. pub kind: StripKind, + /// The drawing whose selection and preview the strip uses. + document: Option, /// The slider's value, 0 to 100. pub level: f64, /// The selection's document bounds when the strip opened, so the strip stays put while the @@ -99,6 +101,18 @@ pub(crate) struct Strip { } impl Strip { + fn in_source(&self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|doc| doc.uid) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.in_source(app) + && app.session.active().and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == self.kind.cmd()) + { + self.preview.cancel(app); + } + } + /// The slider's level, a whole number from 0 to 100. fn level(&self) -> f64 { if self.level.is_finite() { self.level.round().clamp(0.0, 100.0) } else { self.kind.default_level() } @@ -124,10 +138,17 @@ pub(crate) fn opening_level(app: &VectorcraftApp, kind: StripKind) -> f64 { /// Opens the strip of `kind`, replacing (and cancelling the preview of) one that is open. pub(crate) fn open(app: &mut VectorcraftApp, kind: StripKind) { if let Some(old) = app.object_dialogs.strip.take() { - old.preview.cancel(app); + old.cancel(app); } - let strip = - Strip { kind, level: opening_level(app, kind), bounds: app.selection_bounds(), open: true, auto: None, preview: LivePreview::default() }; + let strip = Strip { + kind, + document: app.session.active().map(|doc| doc.uid), + level: opening_level(app, kind), + bounds: app.selection_bounds(), + open: true, + auto: None, + preview: LivePreview::default(), + }; app.object_dialogs.strip = Some(strip); } @@ -158,6 +179,9 @@ pub(super) fn auto_of(app: &mut VectorcraftApp, kind: StripKind) -> Result Result { return Err(not_open(StripKind::Simplify)); } let Some(strip) = app.object_dialogs.strip.take() else { return Err(not_open(StripKind::Simplify)) }; + if !strip.in_source(app) { + return Err(not_open(StripKind::Simplify)); + } let tolerance = simplify_level_tolerance(strip.level()); - strip.preview.cancel(app); + strip.cancel(app); // PLAN: assumed `path_ops::open_simplify(app: &mut VectorcraftApp, tolerance: f64)` returning `()`. super::path_ops::open_simplify(app, tolerance); Ok(json!({ "tolerance": tolerance })) @@ -202,6 +229,9 @@ fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { /// the canvas body. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasView) { let Some(mut strip) = app.object_dialogs.strip.take() else { return }; + if !strip.in_source(app) { + return; + } let kind = strip.kind; let anchor = anchor_rect(view, strip.bounds); let (mut level, mut open) = (strip.level, strip.open); @@ -226,7 +256,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasVie strip.open = open; let result = match shown.output.closed { Some(CloseReason::Escape) => { - strip.preview.cancel(app); + strip.cancel(app); return; } Some(_) => { diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e551e71627..8fd5193074 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -179,6 +179,34 @@ fn simplify_slider_escape_puts_the_paths_back() { assert_eq!(anchor_count(&app), 20); } +#[test] +fn path_sliders_close_on_a_drawing_switch() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let original = app.session.doc().unwrap().doc.clone(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 120.0 + (i % 2) as f64 * 0.2})).collect(); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap(); + let second = app.session.doc().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(simplify_slider::auto_of(&mut app, kind).is_err(), "Auto must not use the second drawing"); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind)); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, second); + assert_eq!(app.session.documents()[0].doc, original); + } +} + /// The Simplify slider stays where it opened, under the paths as they were, while the preview changes their bounds, so a /// drag doesn't move the rail under the pointer. #[test] From 41fe00e938f46648ece86d27abb3a5bd96d82582 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:46 -0800 Subject: [PATCH 23/45] Keep Recolor with Preset in the opening drawing --- crates/ui-egui/src/dialogs/recolor_preset.rs | 43 ++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index 0d3020abb5..61dfc60d6f 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -24,6 +24,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if st.selection.is_empty() { return Err("select artwork to recolor".into()); } + let document = st.uid; if p.get("group").is_some_and(|g| !g.is_null()) { return Err("`group` does not apply to a preset".into()); } @@ -39,6 +40,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Open the original drawing to continue with Recolor with Preset.").to_owned()); + } let mut p = serde_json::Map::new(); if let Some(n) = colors { p.insert("colors".into(), json!(n)); @@ -59,3 +63,42 @@ fn count(v: Option<&Value>) -> Result, String> { Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()), } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, dialog_id}; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn recolor_preset_does_not_open_artwork_in_another_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for color in ["#ff0000", "#0000ff"] { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [shape], "color": color})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + host.with(|h| h.set_json_field(&ctx, id, "limitTo", json!("document"))).unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the preset waits for the app"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let target_undo = app.session.active().unwrap().history.undo.len(); + super::super::host::pump(&mut app, &ctx); + assert!(app.color_dialogs.recolor.is_none(), "the held answer must not open Recolor Artwork on the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), target_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(super::super::tests::confirm(&mut app), "the original preset draft can open Recolor Artwork"); + assert!(app.color_dialogs.recolor.is_some()); + let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND)); + assert_eq!(limit.as_deref(), Some("document")); + } +} From 4b670b1d53fbfd22581d9aeca992cc45e15f443d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:46 -0800 Subject: [PATCH 24/45] Keep the Find and Replace match line in sync --- crates/ui-egui/src/dialogs/find_replace.rs | 20 ++++++++++-- .../ui-egui/src/dialogs/find_replace/tests.rs | 31 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 560c64605a..61bba50596 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -293,6 +293,22 @@ fn shown_match(app: &VectorcraftApp, at: &Value, found: &Value) -> Option (bool, Option) { + let Some(last) = app.ui.last_find.as_ref() else { return (false, None) }; + let Some(found) = last.get("found") else { return (false, None) }; + let at = place(app, last, query); + let matched = at.is_some(); + if found["visible"].as_bool().unwrap_or(true) == matched { + return (matched, None); + } + let message = at.and_then(|at| shown_match(app, at, found)).unwrap_or_default(); + if let Some(found) = app.ui.last_find.as_mut().and_then(|last| last.get_mut("found")) { + found["visible"] = json!(matched); + } + (matched, Some(message)) +} + /// Runs the request the dialog made this frame, then tells the dialog its message and whether a /// match is current. The match is evaluated in every pump, so a changed Find text or switch /// disables Replace and Replace & Find at once; a pass that has no request only refreshes it. @@ -309,10 +325,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }; Some(ran.unwrap_or_else(|e| said(&e))) }); - let matched = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let (matched, match_message) = refresh_match(app, &form.query); dialogs.with(|host| { if let Some(d) = host.get_mut::() { - if let Some(message) = message { + if let Some(message) = message.or(match_message) { d.set_message(message); } d.set_matched(matched); diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 2f633e0d25..d773e5a99b 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -296,6 +296,37 @@ fn a_changed_search_starts_again() { assert_eq!(matched(&p), Some((bottom, 4, 7)), "the same search goes on"); } +#[test] +fn the_match_line_follows_the_active_drawing_and_find_query() { + let (app, _) = app_with(&["source cat match"]); + let mut p = Panel::new(app, draw); + p.app().run("file.new", json!({"width": 800, "height": 600})).unwrap(); + p.app().run("text.create", json!({"x": 50, "y": 50, "text": "destination dog match"})).unwrap(); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + choose(&p); + set(&p, "find", json!("cat")); + p.click("Find Next"); + assert!(message(&p).contains("source cat match")); + + p.app().run("document.activate", json!({"index": 1})).unwrap(); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match from another drawing"); + + p.app().run("document.activate", json!({"index": 0})).unwrap(); + pump(&p); + assert!(matched(&p).is_some()); + assert!(message(&p).contains("source cat match")); + + set(&p, "find", json!("dog")); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match for the previous query"); + p.click("Find Next"); + pump(&p); + assert_eq!(message(&p), "No matches found", "refreshing the dialog leaves the search result visible"); +} + /// The place a search reached belongs to its document: in another document, Edit › Find Next and /// the dialog start at that document's first match, even where an object there has the same id. /// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off From 49d67e781f777ca26b85a4d8b8b08f3df390a9fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:13:21 -0800 Subject: [PATCH 25/45] Load browser-selected files in library panels --- crates/ui-egui/src/panels/brushes.rs | 2 +- crates/ui-egui/src/panels/graphic_styles.rs | 2 +- crates/ui-egui/src/panels/library_panel.rs | 30 ++++----- .../ui-egui/src/panels/library_panel/tests.rs | 65 +++++++++++++++++++ .../ui-egui/src/panels/swatches/libraries.rs | 7 +- crates/ui-egui/src/panels/symbols.rs | 4 +- 6 files changed, 83 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 3311617585..6f670ae2fd 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -944,7 +944,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { let filters = library_panel::library_pick_filters(BrushLibraries::KIND); - library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path }))) + library_panel::pick_library_file(app, path, filters, load_library) } /// The id prefix of the Window → Brush Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 1d089378d3..cf42d21f00 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1041,7 +1041,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { let filters = library_panel::library_pick_filters(GraphicStyleLibraries::KIND); - library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path }))) + library_panel::pick_library_file(app, path, filters, load_library) } /// The id prefix of the Window → Graphic Style Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index f0eb4a72e2..4ed813fb6a 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -20,7 +20,7 @@ use std::cell::RefCell; use std::collections::HashMap; use craft::behavior::{IconId, Selection, SelectionModel}; -use craft::host::{PickRequest, Picked}; +use craft::host::PickRequest; use craft::theme::variant::Tone; use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; @@ -113,7 +113,7 @@ pub(crate) trait LibraryKind { const OPEN: &'static str; /// The engine command listing the libraries, for error messages. const LIST: &'static str; - /// The engine command loading a library from a file (`{path}` → `{library}`). + /// The engine command loading a library by path or by file name and contents (`{library}`). const LOAD: &'static str; /// The libraries menu's tooltip ("Swatch Libraries Menu"). const MENU: &'static str; @@ -502,13 +502,13 @@ pub(crate) fn locate(app: &mut VectorcraftApp, p: &Value) -> Result Result { +/// Locate Library… answered with the chosen file for missing library panel `given`. +fn located(app: &mut VectorcraftApp, given: &str, params: Value) -> Result { let (k, id) = parse(given).ok_or_else(|| format!("`{given}` isn't a library panel (see window.swatchLibrary)"))?; - let r = app.run(k.load, json!({ "path": path }))?; + let r = app.run(k.load, params)?; let next = r["library"].as_str().unwrap_or_default().to_string(); let to = panel_id(k.kind, &next); if to != given && is_open(&app.ui, &to) { @@ -543,25 +543,21 @@ pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [& } } -/// Other Library… and Locate Library…: `then` loads the library file at `path`, else one picked in -/// an open dialog. The pick is asked of the app (`file_asks`) and answers on a later pass, which -/// runs `then` with the picked file; until then this returns what `file_asks::ask` returns. +/// Other Library… and Locate Library…: `then` gets the load command parameters for the file at +/// `path`, or for the picked file. A browser pick supplies the name and contents. pub(crate) fn pick_library_file( app: &mut VectorcraftApp, path: Option, filters: Vec<(&'static str, &'static [&'static str])>, - then: impl FnOnce(&mut VectorcraftApp, String) -> Result + 'static, + then: impl FnOnce(&mut VectorcraftApp, Value) -> Result + 'static, ) -> Result { if let Some(path) = path { - return then(app, path); + return then(app, json!({ "path": path })); } let request = filters.into_iter().fold(PickRequest::open("library"), |r, (name, exts)| r.filter(name, exts)); - Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match picked { - Picked::Paths(paths) => match paths.into_iter().next() { - Some(path) => then(app, path.to_string_lossy().into_owned()), - None => Ok(Value::Null), - }, - _ => Ok(Value::Null), + Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match file_asks::open_params(&picked) { + Some(params) => then(app, Value::Object(params)), + None => Ok(Value::Null), })) } diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 1844bb5f5f..c950725965 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -247,6 +247,45 @@ fn saving_to_a_file_and_opening_a_palette_file() { assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES)); } +fn browser_library(filename: &str, bytes: &[u8], entry: &str) -> Option { + let mut app = app(); + app.services.download = Some(Box::new(|_, _| Ok(()))); + let picker = scripted(&mut app); + let undo = undo_len(&app); + crate::tests::picks::asks(&mut app, &format!("{}.other", K::OPEN)); + picker.answer_contents(&[(filename, bytes)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + assert_eq!((app.session.documents().len(), undo_len(&app)), (1, undo), "loading a library does not change the drawing"); + let open = last_open(&app.ui)?; + assert_eq!(open.kind, K::KIND); + assert!(is_open(&app.ui, &open.panel())); + let (name, library) = K::get(&app, &open.id)?; + assert!(K::rows(&library, &open.id).iter().any(|row| row.name == entry && row.item.is_some()), "{entry} is in the {name} library"); + Some(name) +} + +#[test] +fn other_library_opens_browser_pick_contents_for_each_panel_kind() { + use crate::panels::{brushes::BrushLibraries, graphic_styles::GraphicStyleLibraries, symbols::SymbolLibraries}; + + let mut source = app(); + source.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + source.run("graphicStyle.new", json!({"name": "Studio Style"})).unwrap(); + source.run("symbol.new", json!({"name": "Studio Symbol"})).unwrap(); + source.run("brush.new", json!({"type": "bristle", "name": "Studio Brush"})).unwrap(); + let encoded = source.run("document.serialize", json!({})).unwrap(); + let document = vectorcraft_format::base64_decode(encoded["dataBase64"].as_str().unwrap()).unwrap(); + let palette = b"GIMP Palette\nName: Browser Palette\n#\n255 0 0\tBrowser Red\n"; + let loaded = [ + browser_library::("Browser Palette.gpl", palette, "Browser Red"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Brush"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Symbol"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Style"), + ]; + assert_eq!(loaded.map(|name| name.unwrap_or_default()), ["Browser Palette", "Browser Studio", "Browser Studio", "Browser Studio"]); +} + #[test] fn the_save_dialog_writes_swatch_exchange_files() { let written = std::rc::Rc::new(std::cell::RefCell::new(vec![])); @@ -488,6 +527,32 @@ fn a_persistent_panel_whose_file_is_gone_is_listed_as_missing_until_located() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn locate_library_loads_browser_contents_into_the_missing_panel() { + let path = std::env::temp_dir().join(format!("vc-browser-locate-{}.gpl", std::process::id())); + let palette = b"GIMP Palette\nName: Replacement\n#\n255 0 0\tNew Red\n"; + std::fs::write(&path, palette).unwrap(); + let mut app = app(); + let missing = panel_of(app.run("window.swatchLibrary.other", json!({"path": path})).unwrap()); + app.run("ui.libraryPanel", json!({"panel": missing, "persistent": true, "view": "smallList"})).unwrap(); + std::fs::remove_file(&path).unwrap(); + + let mut app = restarted(&app); + tidy(&mut app); + app.services.download = Some(Box::new(|_, _| Ok(()))); + let picker = scripted(&mut app); + assert_eq!(app.run("ui.libraryPanel.locate", json!({"panel": missing})), Ok(json!({"pending": "fileDialog"}))); + picker.answer_contents(&[("Replacement.gpl", palette)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + + assert!(!is_open(&app.ui, &missing), "the missing panel has been recovered"); + let panel = last_open(&app.ui).unwrap(); + assert!(is_open(&app.ui, &panel.panel())); + assert_eq!((panel.persistent, panel.view), (true, Some(View::SmallList))); + assert!(SwatchLibraries::get(&app, &panel.id).is_some_and(|(_, lib)| lib.swatch("New Red").is_some())); +} + #[test] fn locating_a_library_open_in_its_own_panel_brings_that_panel_forward() { let dir = std::env::temp_dir().join(format!("vc-locate-open-library-{}", std::process::id())); diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index e255b6757d..4f16980b9a 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -200,12 +200,9 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { - library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), |app, path| { - load_library(app, json!({ "path": path })) - }) + library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), load_library) } /// The id prefix of the Window → Swatch Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 7143c2d88e..321a0a7c6d 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -1037,9 +1037,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { - library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), |app, path| { - load_library(app, json!({ "path": path })) - }) + library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), load_library) } /// The id prefix of the Window → Symbol Libraries → User Defined slots. From 38e7c0c2e890b856cc3655cf61c35275dc253b93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:13:36 -0800 Subject: [PATCH 26/45] Report unavailable browser ICC profile loading --- crates/ui-egui/src/panels/separations.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 1a3e0fefd1..6da7bcfb54 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -270,6 +270,7 @@ fn load_profile(app: &mut VectorcraftApp) { Some(path) => app.run("color.loadProfile", json!({ "path": path })), None => Ok(Value::Null), }, + Picked::Contents(files) if !files.is_empty() => Err("loading profiles from disk isn't available in the browser".into()), _ => Ok(Value::Null), }); } @@ -457,6 +458,24 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn browser_profile_pick_reports_why_it_cannot_load() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let picker = crate::tests::picks::scripted(&mut app); + app.status("Previous status"); + + load_profile(&mut app); + picker.cancel(); + crate::file_asks::poll(&mut app); + assert_eq!(app.ui.status, "Previous status"); + + load_profile(&mut app); + assert_eq!(picker.requests().len(), 2); + picker.answer_contents(&[("proof.icc", b"test profile")]); + crate::file_asks::poll(&mut app); + assert_eq!(app.ui.status, "loading profiles from disk isn't available in the browser"); + } + /// The panel's Proof Setup list offers the targets of View › Proof Setup, in the same order and /// with the same labels, and each one is a target `view.proofSetup` accepts. #[test] From 312a8bd792081e410800697b5152c4f2bf21f876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:14:45 -0800 Subject: [PATCH 27/45] Regenerate Artboard Color Picker command catalog --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index a519986ed0..f2444bc019 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1096,7 +1096,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active", ), ( "ui.sampleScreenColor", From 7ae76f462f5f6b6caa4afde5d27bf90fa95d2121 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:15:31 -0800 Subject: [PATCH 28/45] Require a fresh Apply SVG Filter dialog after Revert --- crates/ui-egui/src/dialogs/svg_filter.rs | 62 ++++++++++++++++++++---- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index 9f7a412b9a..aaf3021f6d 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -51,6 +51,19 @@ const LIST_ROWS: u16 = 7; struct Opening { document: u64, + reverts: u64, +} + +impl Opening { + fn check(&self, app: &VectorcraftApp) -> Result<(), String> { + let Some(doc) = app.session.active().filter(|doc| doc.uid == self.document) else { + return Err(tl!("Return to the original drawing to edit its SVG filters").into()); + }; + if doc.reverts != self.reverts { + return Err(tl!("Reopen Apply SVG Filter after reverting the drawing").into()); + } + Ok(()) + } } fn opening_id() -> egui::Id { @@ -267,7 +280,8 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p /// the default's code or with nothing; when neither has its name, the name shown above the list if /// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let doc = app.session.active().ok_or("no document open")?; + let source = Arc::new(Opening { document: doc.uid, reverts: doc.reverts }); let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" }); if let Some(k) = p.get("index").and_then(Value::as_u64) { let mut q = json!({}); @@ -304,13 +318,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build); crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { let source = opening(app).ok_or("the SVG Filter dialog is gone")?; - if app.session.active().is_none_or(|st| st.uid != source.document) { - return Err(tl!("Return to the original drawing to apply this SVG filter").into()); - } + source.check(app)?; confirm(app, &result.fields) }) .ok_or("no window")?; - ctx.data_mut(|d| d.insert_temp(opening_id(), Arc::new(Opening { document }))); + ctx.data_mut(|d| d.insert_temp(opening_id(), source)); Ok(Value::Null) } @@ -359,11 +371,11 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) { /// button pressed, once. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(source) = opening(app) else { return }; - if app.session.active().is_none_or(|st| st.uid != source.document) { + if let Err(error) = source.check(app) { let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default(); if has_action { set(app, &[(ACTION, json!(""))]); - app.status(tl!("Return to the original drawing to edit its SVG filters")); + app.status(error); } return; } @@ -451,12 +463,12 @@ pub(crate) fn pick() -> PickRequest { /// Asks for an SVG file; once picked, its filters are added to the document and the first one /// added is selected in the dialog when it is open. fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { - let dialog = source.clone().or_else(|| opening(app).filter(|opening| app.session.active().is_some_and(|st| st.uid == opening.document))); + let dialog = source.clone().or_else(|| opening(app).filter(|opening| opening.check(app).is_ok())); file_asks::ask_while( app, pick(), Owner::Document, - move |app| source.is_none_or(|source| opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &source))), + move |app| source.is_none_or(|source| source.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &source))), move |app, picked| { let params = match picked { // The browser answers with the file's contents, not a path. @@ -470,7 +482,7 @@ fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { let added = r["added"].as_array().map_or(0, Vec::len); app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); if let Some(first) = r["added"].get(0) - && dialog.is_some_and(|dialog| opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &dialog))) + && dialog.is_some_and(|dialog| dialog.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &dialog))) { set(app, &[(SELECTED, first.clone())]); } @@ -574,6 +586,36 @@ mod tests { assert!(effects(&app, first).is_empty()); } + #[test] + fn an_svg_filter_draft_cannot_apply_after_reverting_its_drawing() { + let mut app = self::app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("svg-filter-drawing-revert"); + let path = dir.join("drawing.vectorcraft"); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let object = rect(&mut app); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rect(&mut app); + app.run("select.set", json!({"ids": [object]})).unwrap(); + let original = app.session.doc().unwrap(); + let (uid, generation) = (original.uid, original.reverts); + open(&mut app, &json!({})).unwrap(); + let dialog = dialog_id(KIND); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + app.run("select.set", json!({"ids": [object]})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, object).is_empty()); + + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, object).first().map(|effect| effect.params["name"].clone()), Some(json!("Shift"))); + } + #[test] fn the_dialog_draws_its_filters_and_buttons() { let mut app = app(); From 93c8196934888bb58064f0ae46aa55fe0ca34b00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:15:31 -0800 Subject: [PATCH 29/45] Enable Graph Data Import for browser file contents --- crates/ui-egui/src/dialogs/graph_data.rs | 26 ++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ffcc511501..9498b881c7 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -391,9 +391,10 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result bool { - file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() + file_asks::can(app, craft::host::PickKind::Open) + && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. @@ -978,6 +979,27 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn browser_graph_data_import_reads_picked_bytes_without_a_path_reader() { + let (mut app, _) = app_with(",original\nQ1,1", "column"); + app.services.read = None; + app.services.read_head = None; + let files = Arc::new(ScriptedFiles::held().in_browser()); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1, "the browser can open the Import Data picker"); + files.answer(Picked::Contents(vec![("data.txt".into(), b"\timported\nQ2\t8".to_vec())])); + h.run_steps(4); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)), "imported"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 0)), "Q2"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 1)), "8"); + } + #[test] fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { let (mut app, _) = app_with(",first\nQ1,1", "column"); From 826248f56a6216fe1e08ea6b6d241be632d50cd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:15:31 -0800 Subject: [PATCH 30/45] Load and replace Action sets from browser-picked contents --- crates/ui-egui/src/panels/actions/files.rs | 29 ++++++++---- .../ui-egui/src/panels/actions/tests_files.rs | 46 +++++++++++++++++++ 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 9672ee1c64..dd6981c763 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -20,7 +20,7 @@ //! `actionSet.read`), a Set Selection step as a Select Object step. use craft::automation::actions::{Action, ActionColor, ActionStep, ActionsFile}; -use craft::host::{PickKind, PickRequest}; // PLAN: assumed path of the host's picker types in the app's `craft` facade +use craft::host::{PickKind, PickRequest, Picked}; // PLAN: assumed path of the host's picker types in the app's `craft` facade use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -577,15 +577,20 @@ fn read_path(app: &mut VectorcraftApp, path: &str) -> Result { (None, Some(read)) => read(path)?, (None, None) => return Err("no file reader".into()), }; + read_bytes(app, path, &bytes) +} + +/// A desktop or browser file's contents, with its name used only as the unnamed set's fallback. +fn read_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Result { if bytes.len() > MAX_SET_FILE { return Err("the action set file is larger than 8 MiB".into()); } - if is_aia(&bytes) { - return read_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); + if is_aia(bytes) { + return read_aia(app, json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })); } - let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - let text = String::from_utf8(bytes).map_err(|_| "not an action set file")?; - let (name, actions) = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?; + let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let text = std::str::from_utf8(bytes).map_err(|_| "not an action set file")?; + let (name, actions) = read_set(text, if stem.is_empty() { "Actions" } else { &stem })?; Ok(FileRead { name, actions, aia: None }) } @@ -613,8 +618,16 @@ fn read_file( let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); let request = PickRequest::open("actions").filter("Action sets", &exts); Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| { - let path = picked.first_path().ok_or("cancelled")?; - let read = read_path(app, &path.to_string_lossy())?; + let read = match picked { + Picked::Contents(files) => { + let (name, bytes) = files.into_iter().next().ok_or("cancelled")?; + read_bytes(app, &name, &bytes)? + } + other => { + let path = other.first_path().ok_or("cancelled")?; + read_path(app, &path.to_string_lossy())? + } + }; then(app, read) })) } diff --git a/crates/ui-egui/src/panels/actions/tests_files.rs b/crates/ui-egui/src/panels/actions/tests_files.rs index 79bad2c42e..a88cbc36fe 100644 --- a/crates/ui-egui/src/panels/actions/tests_files.rs +++ b/crates/ui-egui/src/panels/actions/tests_files.rs @@ -7,6 +7,52 @@ use super::tests_support::*; use super::*; use crate::dialogs::action_batch::BatchDialog; +#[test] +fn browser_picks_load_and_replace_action_sets_without_a_file_reader() { + let native = json!({ + "format": "vcactions", "version": 1, "name": "Browser", + "actions": [{"name": "Group", "steps": [{"command": "object.group", "params": {}}]}] + }) + .to_string(); + let mut aia = aia_text("", &[("Group", &[("group", true)])]).into_bytes(); + // AIA's text encoding is not required to be UTF-8. + aia.extend(b"/note (\xFF)\n"); + for command in [LOAD_SET, REPLACE_SET] { + for (name, bytes) in [("Browser.vcactions", native.as_bytes()), ("Browser.aia", aia.as_slice())] { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + app.services.read = None; + app.services.read_head = None; + let before = saved_sets(&app); + let undo = undo_steps(&app); + app.run(command, json!({})).unwrap(); + picker.cancel(); + crate::file_asks::poll(&mut app); + assert_eq!(saved_sets(&app), before, "cancel keeps the sets"); + for invalid in [vec![0xff], vec![b' '; files::MAX_SET_FILE + 1]] { + app.run(command, json!({})).unwrap(); + picker.answer_contents(&[(name, &invalid)]); + crate::file_asks::poll(&mut app); + assert_eq!(saved_sets(&app), before, "invalid picked bytes keep the sets"); + assert!(!app.ui.status.is_empty(), "a rejected file reports why"); + } + app.run(command, json!({})).unwrap(); + picker.answer_contents(&[(name, bytes)]); + crate::file_asks::poll(&mut app); + let names = set_names(&app); + assert_eq!(names.last().map(String::as_str), Some("Browser")); + if command == REPLACE_SET { + assert_eq!(names, ["Browser"]); + } else { + assert!(names.len() > 1, "Load keeps existing sets"); + } + assert_eq!(set_actions(&app, names.len() - 1)[0].steps, [ActionStep::new("object.group", json!({}))]); + assert_eq!(undo_steps(&app), undo, "loading actions does not edit the drawing"); + } + } +} + #[test] fn defaults_are_valid_commands() { for a in default_sets().actions { From da3a548ea5deb9e0b22a06adc642605ca7e17763 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:15:31 -0800 Subject: [PATCH 31/45] Use browser picker contents when replacing an image --- crates/engine/src/cmd/links.rs | 69 +++++++++++++++++++----- crates/ui-egui/src/panels/links.rs | 22 ++++++-- crates/ui-egui/src/panels/tests_links.rs | 55 +++++++++++++++++++ docs/mcp.md | 2 + docs/target-app-parity.md | 1 + 5 files changed, 131 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 1115c7e917..5a77b6d780 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -76,6 +76,15 @@ pub fn specs() -> Vec { has_doc, relink ), + cmd!( + "links.replaceEmbedded", + "Replace Image", + [], + None, + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + has_doc, + replace_embedded + ), cmd!( query "links.list", "Links", @@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } +/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement. +fn replace_embedded(s: &mut Session, p: &Value) -> Result { + const C: &str = "links.replaceEmbedded"; + let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?; + let doc = &s.doc()?.doc; + let mut seen = BTreeSet::new(); + for id in &ids { + if !seen.insert(*id) { + return Err(bad(C, format!("image {} is listed twice", id.0))); + } + if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) { + return Err(bad(C, format!("object {} is not an image", id.0))); + } + } + let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?; + let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; + let mut img = fileio::raster_image(&bytes)?; + img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; + Ok(json!({ "replaced": ids_json(&ids) })) +} + /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels /// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the /// transform still gives it its old size. Its Placement Options do not apply. The result is what @@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: /// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a /// distort maps a path's. -fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { +fn refill_distorted( + n: &mut Node, + old_clip: Option<&FileClip>, + link: Option<&LinkInfo>, + img: &RasterImage, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned()); } let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) @@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { - install_with(d, ids, read, force, also, false) +fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, Some(&link), img, force, also, false) } /// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it @@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { } } -/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes +/// through [`unembed_clip`]. fn install_with( d: &mut Document, ids: &[NodeId], - (link, img): FileRead, + link: Option<&LinkInfo>, + img: RasterImage, force: Option, also: Option<(&str, &str)>, unembed: bool, @@ -1341,7 +1380,7 @@ fn install_with( NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), _ => None, }; - let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held); return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { @@ -1353,7 +1392,7 @@ fn install_with( }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } (n, clip) }; @@ -1367,7 +1406,7 @@ fn install_with( }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); clips.push((*id, keep(clip, held.is_some()))); } continue; @@ -1384,12 +1423,12 @@ fn install_with( if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } } // A DCS file's spot plates print on spot swatches of their inks. super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); - store_image(d, &img.key, img.blob, true); + store_image(d, &img.key, img.blob, link.is_some()); clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), @@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result { // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; - let read = (link_info(&path, &bytes), img); + let link = link_info(&path, &bytes); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) + editing_brush_art(d, |d| { + reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)) + }) }); if let Err(e) = edited { remove_written(&written); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 87b574f820..52dcae24df 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -23,7 +23,7 @@ use std::collections::HashMap; use std::sync::Arc; use craft::behavior::{IconId, Selection, keyed}; -use craft::host::{PickKind, PickRequest}; +use craft::host::{PickKind, PickRequest, Picked}; use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; @@ -364,12 +364,26 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest, then: impl FnOnce(&mut Ve /// say. pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec) { let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts)); - ask(app, request, move |app, path| { - let r = app.run("links.relink", json!({ "ids": ids, "path": path, "preserve": "fit" })); - report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[])); + file_asks::ask(app, request, Owner::Document, move |app, picked| { + if let Picked::Contents(files) = picked { + if let Some((name, bytes)) = files.into_iter().next() { + let result = app + .run("links.replaceEmbedded", json!({ "ids": ids, "dataBase64": vectorcraft_format::base64_encode(&bytes) })) + .map_err(|err| format!("{name}: {err}")); + report(app, result, |v| replaced_status(v["replaced"].as_array().map_or(0, Vec::len))); + } + } else if let Some(path) = picked.first_path() { + let r = app.run("links.relink", json!({ "ids": ids, "path": path.to_string_lossy(), "preserve": "fit" })); + report(app, r, |v| replaced_status(v["relinked"].as_array().map_or(0, Vec::len))); + } + Ok(Value::Null) }); } +fn replaced_status(n: usize) -> String { + crate::i18n::msg_n(n as u64, "Replaced {n} image", "Replaced {n} images", &[]) +} + /// Relink images `ids` (none: every missing one) to the files of their names in a picked folder. fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec) { ask(app, PickRequest::folder("links"), move |app, folder| { diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 6f9a6c5046..2d09036751 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -629,6 +629,61 @@ fn properties_shows_the_selected_image_and_its_link_actions() { assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}"); } +#[test] +fn replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step() { + use crate::tests::picks::{poll, scripted}; + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_geom::Rect; + + let dir = Folder::new("replace-browser-bytes"); + let (mut app, linked, _) = app(&dir); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let journal = app.session.journal.len(); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let bytes = png(10, 20); + + super::links::replace(&mut app, vec![linked]); + assert_eq!(picker.requests().len(), 1); + picker.answer_contents(&[("replacement.png", &bytes)]); + poll(&mut app, &ctx); + + let state = app.session.doc().unwrap(); + let NodeKind::Image(image) = &state.doc.node(NodeId(linked)).unwrap().kind else { panic!("replacement must keep the image's id") }; + assert_eq!((image.width, image.height), (10, 20)); + assert!(image.link.is_none(), "browser file contents are embedded"); + assert_eq!(state.doc.images[&image.key].bytes.as_slice(), bytes); + let bounds = image.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 10.0, 20.0)); + assert_eq!((bounds.width(), bounds.height()), (100.0, 200.0), "fit in the old 300 by 200 bounds"); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(app.session.journal.get(journal).map(|(command, _)| command.as_str()), Some("links.replaceEmbedded")); + + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +#[test] +fn replace_image_with_a_desktop_path_remains_linked() { + use crate::tests::picks::{poll, scripted}; + use vectorcraft_doc::{NodeId, NodeKind}; + + let dir = Folder::new("replace-desktop-path"); + let (mut app, _, embedded) = app(&dir); + let path = dir.file("replacement.png", &png(10, 20)); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + + super::links::replace(&mut app, vec![embedded]); + picker.answer(&[&path]); + poll(&mut app, &ctx); + + let state = app.session.doc().unwrap(); + let NodeKind::Image(image) = &state.doc.node(NodeId(embedded)).unwrap().kind else { panic!("replacement must keep the image's id") }; + assert_eq!((image.width, image.height), (10, 20)); + assert_eq!(image.link.as_ref().unwrap().path, path); +} + /// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for /// each image there and links each one to its file; with no folder picked, nothing changes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6f567df149..f3141d314c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10689,6 +10689,8 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e ## Links panel +`links.replaceEmbedded {ids, dataBase64}` uses raster file bytes to replace existing canvas images. It embeds the new pixels and keeps the image ids. The new aspect ratio fits inside the old bounds, and a distorted image keeps its corners. The command records one undo step and returns `{replaced: [ids]}`. The browser's Replace Image uses this operation with the file picker result. + `links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df69c18888..f75b07401c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2538,6 +2538,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. + - Replace Image in the browser embeds the picked raster in the existing image and fits it within the old bounds in one undo step. The desktop picker continues to link to the chosen file. Evidence includes `replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step` and `replace_image_with_a_desktop_path_remains_linked`. - The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name. - When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`). - On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`). From b372e2840db122865b2600ae263b04f2dcc28730 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:16:28 -0800 Subject: [PATCH 32/45] Keep Export As visible before a drawing opens --- crates/ui-egui/src/dialogs/export_as.rs | 11 ++++++----- crates/ui-egui/src/dialogs/export_host.rs | 4 ++-- crates/ui-egui/src/dialogs/tests_export.rs | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 30af709740..7894461e9a 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -111,9 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let source = app.session.active().ok_or("no document")?; - let document = source.uid; - let n = source.doc.artboards.len(); + let source = app.session.active(); + let document = source.map(|source| source.uid); + let n = source.map_or(0, |source| source.doc.artboards.len()); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { Some((id, _)) => id, @@ -138,7 +138,8 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } -fn require_source(app: &VectorcraftApp, document: u64) -> Result<(), String> { +fn require_source(app: &VectorcraftApp, document: Option) -> Result<(), String> { + let document = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?; if app.session.active().is_none_or(|source| source.uid != document) { return Err(tl!("Return to the original drawing to export it").into()); } @@ -147,7 +148,7 @@ fn require_source(app: &VectorcraftApp, document: u64) -> Result<(), String> { /// Check the artboard range and that there is something to export; the save panel and the format's options or /// the file follow once the dialog has closed. -pub(super) fn confirm(app: &mut VectorcraftApp, document: u64, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, document: Option, fields: &DialogFields) -> Result { require_source(app, document)?; if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index 2d45ad40ca..fb68f64c51 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -22,8 +22,8 @@ pub(crate) type After = Option Result, }, /// The options of the raster format `format`. Raster { diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 521cb19043..7ab85da4ae 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -344,6 +344,22 @@ fn a_bad_range_keeps_export_as_open() { assert!(written.borrow().is_empty()); } +#[test] +fn export_as_opened_without_a_drawing_does_not_take_a_later_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + save_panel(&mut app, |_| Some("/out/untitled.png".into())); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["format"], "png"); + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = try_confirm(&mut app).expect_err("the old Export As draft has no source drawing"); + assert!(error.contains("Open Export As from the drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); +} + #[test] fn export_as_waits_for_the_drawing_that_opened_it() { let (mut app, written) = app(2); From 200218358fb0b171a5a700c5561523542df33069 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:20:26 -0800 Subject: [PATCH 33/45] Keep Artboard Options from editing reverted drawings --- .../ui-egui/src/dialogs/artboard_options.rs | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index cb1c6337e5..1e3013b69a 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -154,6 +154,7 @@ struct Setup { #[derive(Clone, Copy)] struct Target { document: u64, + reverts: u64, /// The current artboard's ID, or no ID while creating a new artboard. artboard: Option, } @@ -556,7 +557,7 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; let st = app.session.active().ok_or("no document")?; - let target = Target { document: st.uid, artboard }; + let target = Target { document: st.uid, reverts: st.reverts, artboard }; let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); @@ -652,6 +653,9 @@ fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) - .active() .filter(|st| st.uid == target.document) .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; + if st.reverts != target.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; @@ -1063,4 +1067,39 @@ mod tests { assert!(!is_open(&app)); assert_eq!(*app.session.doc().unwrap().doc, *before); } + + #[test] + fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + open(&mut app).unwrap(); + set(&app, &[("name", json!("Stale Draft"))]).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard)); + let undo = undo_len(&app); + + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1"); + assert_eq!(undo_len(&app), undo); + assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into())); + assert!(is_open(&app)); + let host = app.dialogs().unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert_eq!(host.with(|h| h.get::().unwrap().value.name.clone()), "Stale Draft"); + host.with(|h| h.cancel_by_id(&ctx, id())); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Fresh Draft"))]).unwrap(); + ok(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft"); + } } From 056883d79e47d8fd5ca535d9e5d10c9ed163c9ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:21:35 -0800 Subject: [PATCH 34/45] Exercise Recolor Artwork after switching drawings --- crates/ui-egui/src/dialogs/recolor.rs | 88 +++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 3768c182d2..6c58309987 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -3118,6 +3118,94 @@ mod tests { rc } + fn two_red_drawings() -> (Recolor, u64, u64) { + let mut app = app(120); + let opening = square(&mut app, 10.0, "#ff0000"); + app.run("select.set", json!({"ids": [opening]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = square(&mut app, 60.0, "#ff0000"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap(); + (rc, opening, other) + } + + #[test] + fn recolor_preview_does_not_change_the_other_drawings_art() { + let (mut rc, opening, other) = two_red_drawings(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + rc.frame(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "preview leaves the other drawing's fill alone"); + assert!(!rc.app().session.in_interaction()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + rc.confirm().unwrap(); + } + + #[test] + fn recolor_ok_keeps_the_draft_on_the_opening_drawing() { + let (mut rc, opening, other) = two_red_drawings(); + rc.set("preview", json!(false)).unwrap(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&rc.app()); + let confirmed = rc.confirm(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "OK leaves the other drawing's fill alone"); + assert_eq!(undo_len(&rc.app()), undo); + assert!(confirmed.is_err() && rc.is_open()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + rc.confirm().unwrap(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + } + + #[test] + fn recolor_cancel_leaves_the_other_drawings_pending_edit() { + let (mut rc, opening, other) = two_red_drawings(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + { + let mut app = rc.app(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap(); + } + rc.cancel(); + + assert!(rc.app().session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(fill_hex(&rc, other), "#0000ff"); + rc.app().session.commit_interaction().unwrap(); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + } + + #[test] + fn recolor_delete_leaves_the_other_drawings_same_named_group() { + let mut app = app(120); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#00ff00"]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#ff0000"]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({"group": "Shared"})); + rc.frame(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let other = group_hex(&rc.app(), "Shared"); + + rc.act("delete").unwrap(); + + assert_eq!(group_hex(&rc.app(), "Shared"), other, "Delete leaves the other drawing's group alone"); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert!(group_hex(&rc.app(), "Shared").is_some(), "a refused action does not run after returning"); + rc.act("delete").unwrap(); + assert!(group_hex(&rc.app(), "Shared").is_none()); + } + #[test] fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() { let rc = opened(app(100), json!({"colors": ["#ff8000"]})); From 47e02227d99c3d68889d6d697945cad589576e84 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:22:53 -0800 Subject: [PATCH 35/45] JavaScript Files: link only filesystem picker paths --- .../ui-egui/src/dialogs/javascript_files.rs | 48 +++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index d15f561816..c3a3fb0e6b 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -14,7 +14,7 @@ //! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked. use craft::behavior::{Selection, keyed}; -use craft::host::PickRequest; +use craft::host::{PickId, PickRequest, Picked}; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; @@ -61,6 +61,8 @@ struct Form { file: String, /// The linked file selected in the list, as linked or as the list shows it. selected: String, + /// The file chooser still waiting for its typed answer. + pick: Option, pending: Option, } @@ -217,12 +219,25 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { if selection.items.first() != selected { form.selected = selection.items.into_iter().next().unwrap_or_default(); } - Field::new(caption("File or URL:")).show(ui, |ui, _| { - let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); - let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui); - // The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]). - if let Some(path) = out.picked { - form.file = crate::io::file_url(&path); + Field::new(caption("File or URL:")).show(ui, |ui, cx| { + if let Some(ticket) = form.pick + && let Some(answer) = cx.take_pick_answer(ticket) + { + form.pick = None; + // Browser picks supply the file's bytes and basename. Only a filesystem path can be linked. + if let Picked::Paths(paths) = answer + && let Some(path) = paths.first() + { + form.file = crate::io::file_url(&path.to_string_lossy()); + } + } + let row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).show(ui); + if row.browse + && form.pick.is_none() + && let Some(host) = cx.env.host() + { + let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); + form.pick = Some(host.files().pick(request)); } }); let chosen = selected_row(files, &form.selected); @@ -242,7 +257,7 @@ mod tests { use std::rc::Rc; use std::sync::Arc; - use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; + use craft::host::{AppInfo, Host, ScriptedFiles}; use craft::ui::testing::Fixture; use egui::{Key, Modifiers}; use vectorcraft_engine::Session; @@ -380,4 +395,21 @@ mod tests { let file = form.borrow().file.clone(); assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}"); } + + #[test] + fn a_browser_file_pick_does_not_invent_a_local_script_url() { + let files = Arc::new(ScriptedFiles::held()); + let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() })); + let shown = Rc::clone(&form); + let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut())); + fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build())); + fixture.settle(); + let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button"); + fixture.click(&choose); + fixture.settle(); + let picked = Picked::Contents(vec![("menu.js".into(), b"// local script".to_vec())]); + assert!(files.answer(picked).is_some(), "Choose… filed a browser pick"); + fixture.idle(3); + assert_eq!(form.borrow().file, "https://example.test/menu.js"); + } } From 3d5953a032b1b3cb5a9bc9dd4b77f8617b3a0f91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:23:28 -0800 Subject: [PATCH 36/45] Describe Variables Import as requiring a data source --- crates/engine/src/cmd/variablecmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index c941ccb87e..b863ec5edf 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -1090,7 +1090,7 @@ pub fn specs() -> Vec { "Import…", ["Window", "Variables"], None, - "{path? | name?, dataBase64?} import a data source from a path or from a file name with its bytes, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + "{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", has_doc, variable_import ), From b688d627721a31e168fdea2a77a03bc63c49009e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:23:59 -0800 Subject: [PATCH 37/45] Keep add-on dialogs in the opening drawing --- crates/ui-egui/src/addons/dialogs.rs | 41 ++++++++--- crates/ui-egui/src/addons/dialogs/tests.rs | 81 ++++++++++++++++++++++ 2 files changed, 114 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index d29066a126..6ddf340de4 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -4,7 +4,7 @@ use std::mem; -use craft::ui::dialog::{DialogResult, StackDialog}; +use craft::ui::dialog::{DialogId, DialogResult, StackDialog}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; use egui::Context; use serde_json::{Value, json}; @@ -32,13 +32,27 @@ pub(crate) struct Spec { /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { - open: Option<(craft::ui::dialog::DialogId, &'static Spec)>, + open: Option, preview: LivePreview, } +#[derive(Clone, Copy)] +struct Open { + id: DialogId, + spec: &'static Spec, + document: Option, +} + +impl Open { + fn on_document(self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|state| state.uid) + } +} + /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { - let Some((id, _)) = app.addon_dialogs.open.take() else { return }; + let Some(open) = app.addon_dialogs.open.take() else { return }; + let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { h.cancel_by_id(&ctx, id); @@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) { let _ = h.take_by_id::(id); }); } - mem::take(&mut app.addon_dialogs.preview).cancel(app); + let preview = mem::take(&mut app.addon_dialogs.preview); + if open.on_document(app) { + preview.cancel(app); + } } /// Opens the dialog `spec` describes over `fields`, built each pass by `build`. @@ -62,7 +79,7 @@ pub(crate) fn open( close_open(app); let id = dialog.id(); host.with(|h| h.open(dialog)); - app.addon_dialogs.open = Some((id, spec)); + app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) }); Ok(json!({ "dialog": spec.command })) } @@ -94,10 +111,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } fn pump_commit(app: &mut VectorcraftApp) { - let Some((id, spec)) = app.addon_dialogs.open else { return }; + let Some(open) = app.addon_dialogs.open else { return }; let Some(host) = app.dialogs() else { return }; + let Open { id, spec, .. } = open; + let on_document = open.on_document(app); + if !on_document { + // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. + app.addon_dialogs.preview = LivePreview::default(); + } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); - if let Some((previewing, params)) = &live { + if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); @@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.open = None; let preview = mem::take(&mut app.addon_dialogs.preview); // The dialog is closed already, so a refusal can only go to the status line. - if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { + if !on_document { + app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned()); + } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { app.status(error); } } diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index eb24e09c37..b7f648aa1e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp { /// Two rectangles without a stroke, both selected. fn two_rects() -> VectorcraftApp { let mut app = new_app(); + select_two_rects(&mut app); + app +} + +fn select_two_rects(app: &mut VectorcraftApp) { app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); app.run("select.all", json!({})).unwrap(); +} + +fn two_drawings() -> VectorcraftApp { + let mut app = two_rects(); + app.run("file.new", json!({"width": 700, "height": 500})).unwrap(); + select_two_rects(&mut app); + activate(&mut app, 0); app } +fn activate(app: &mut VectorcraftApp, index: usize) { + app.run("document.activate", json!({"index": index})).unwrap(); +} + fn two_circles() -> VectorcraftApp { let mut app = new_app(); let ids: Vec = [100.0, 160.0] @@ -280,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1); assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back"); } + +#[test] +fn an_add_on_preview_waits_for_its_opening_drawing() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed in the opening drawing"); + + activate(&mut app, 1); + let undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview"); + assert!(!app.session.in_interaction()); + + activate(&mut app, 0); + assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing"); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing"); + cancel(&app, id); + frame(&mut app); + assert_eq!(x0(&app, 1), 100.0); +} + +#[test] +fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() { + let mut app = two_drawings(); + let source_undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(false)); + assert!(confirm(&app, id)); + activate(&mut app, 1); + let target_undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step"); + assert_eq!(app.session.active_index(), Some(1)); + activate(&mut app, 0); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo)); +} + +#[test] +fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0); + + activate(&mut app, 1); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + cancel(&app, id); + let context = ctx(&app); + super::pump(&mut app, &context); + let active = app.session.active().unwrap(); + assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit")); + assert_eq!(active.doc, other); +} From 8d3217fbe50e02325709e8facad181eb4b49b6e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:25:54 -0800 Subject: [PATCH 38/45] Keep Recolor Artwork edits in the opening drawing --- crates/ui-egui/src/dialogs/recolor.rs | 111 +++++++++++++++++++++----- 1 file changed, 93 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 6c58309987..1788afcff5 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -118,7 +118,7 @@ mod prominent; use std::borrow::Cow; use std::cell::RefCell; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::behavior::edit_history::{EditHistory, Step}; use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed}; @@ -152,6 +152,7 @@ use serde_json::{Value, json}; use vectorcraft_color::harmony::{self, Harmony, move_on_wheel}; use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::fileio::builtin_open_filters; use vectorcraft_engine::cmd::swatchlib; @@ -258,8 +259,44 @@ impl Fields { pub(crate) struct Open { /// The dialog on the window's host. pub id: DialogId, + document: u64, /// The preview the pump runs and OK commits. pub preview: LivePreview, + /// The selection snapshot identifies the interaction that ran the preview. + preview_selection: Option>, +} + +impl Open { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + if app.session.active().is_none_or(|state| state.uid != self.document) { + Some("Return to the document where Recolor Artwork opened.") + } else if app.session.in_interaction() && !self.owns_preview(app) { + Some("Finish the active edit before applying Recolor Artwork.") + } else { + None + } + } + + fn take_preview(&mut self) -> LivePreview { + self.preview_selection = None; + std::mem::take(&mut self.preview) + } + + fn cancel(&mut self, app: &mut VectorcraftApp) { + let owns_preview = self.owns_preview(app); + let preview = self.take_preview(); + if owns_preview { + preview.cancel(app); + } + } } /// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected @@ -284,7 +321,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // The group is looked for in the document without the preview of a Recolor Artwork this one // replaces (which can rename the group), as that dialog's rollback below leaves it. let unpreviewed = match &st.interaction { - Some(it) if app.color_dialogs.recolor.is_some() => &it.doc, + Some(it) if app.color_dialogs.recolor.as_ref().is_some_and(|open| open.owns_preview(app)) => &it.doc, _ => &st.doc, }; if let Some(g) = group @@ -301,6 +338,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. cancel_open(app); let st = app.session.active().ok_or("no document open")?; + let document = st.uid; let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -339,7 +377,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; - app.color_dialogs.recolor = Some(Open { id, preview: LivePreview::default() }); + app.color_dialogs.recolor = Some(Open { id, document, preview: LivePreview::default(), preview_selection: None }); Ok(Value::Null) } @@ -349,8 +387,8 @@ fn cancelled(app: &mut VectorcraftApp) { if app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::())) { return; } - if let Some(open) = app.color_dialogs.recolor.take() { - open.preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); } } @@ -363,9 +401,9 @@ const NEW_GROUP: &str = "Color Group"; /// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes. pub(super) fn cancel_open(app: &mut VectorcraftApp) { - let Some(old) = app.color_dialogs.recolor.take() else { return }; + let Some(mut old) = app.color_dialogs.recolor.take() else { return }; let id = old.id; - old.preview.cancel(app); + old.cancel(app); if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { dialogs.with(|host| { host.cancel_by_id(&ctx, id); @@ -476,8 +514,9 @@ const SAVE_GROUP: &str = "__saveGroup"; /// Cancel the preview, so commands read the art's own colors; the pump runs it again afterwards. fn cancel_preview(app: &mut VectorcraftApp) { - if let Some(preview) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) { - preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); + app.color_dialogs.recolor = Some(open); } } @@ -1630,12 +1669,20 @@ pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: Dialog /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { - let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; - // `run` reports a preview that fails on the status line itself. - let _ = live.run(app, on, TITLE, cmd, ¶ms); - if let Some(open) = app.color_dialogs.recolor.as_mut() { - open.preview = live; + let Some(mut open) = app.color_dialogs.recolor.take() else { return }; + if open.problem(app).is_none() { + if !open.owns_preview(app) { + open.take_preview(); + } + // `run` reports a preview that fails on the status line itself. + let ran = open.preview.run(app, on, TITLE, cmd, ¶ms).is_some(); + if !on { + open.preview_selection = None; + } else if ran { + open.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } } + app.color_dialogs.recolor = Some(open); } /// Feeds the open Recolor Artwork what it shows of the app, runs what its passes asked for, asks for @@ -1643,8 +1690,27 @@ fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, /// previews its recolour: once a frame, after the window's dialog host ran. // PLAN: hub-w2 adds the line `recolor::pump(app, ctx)` to `dialogs::host::pump` (co.A6 names this pump). pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(id) = app.color_dialogs.recolor.as_ref().map(|open| open.id) else { return }; + let Some(open) = app.color_dialogs.recolor.as_ref() else { return }; + let id = open.id; let Some(dialogs) = app.dialogs() else { return }; + if let Some(reason) = open.problem(app) { + let requests = dialogs.with(|host| { + let d = host.get_mut_by_id::(id)?; + let group_action = d.fields.fields.remove(GROUP_ACTION).is_some(); + let save_group = d.fields.fields.remove(SAVE_GROUP).is_some(); + let library = std::mem::take(&mut d.filed.library).then(|| Arc::clone(&d.opening)); + Some((library, group_action || save_group)) + }); + if let Some((library, action_refused)) = requests { + if let Some(opening) = library { + pick_library(app, opening); + } + if action_refused { + app.status(reason); + } + } + return; + } // The colour the picker answered for a row reaches the row here, where the app can snap it to Limit to Library. dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) @@ -1681,7 +1747,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Artwork dialog → {changed, canUndo, canRedo}. pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { const NOT_OPEN: &str = "Recolor Artwork is not open"; - let id = app.color_dialogs.recolor.as_ref().map(|open| open.id).ok_or(NOT_OPEN)?; + let open = app.color_dialogs.recolor.as_ref().ok_or(NOT_OPEN)?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } + let id = open.id; let dialogs = app.dialogs().ok_or(NOT_OPEN)?; let mut work = dialogs.with(|host| host.get_mut_by_id::(id).map(RecolorDialog::take_work)).ok_or(NOT_OPEN)?; // Fields set since the last frame take effect first, as the next frame would give them. @@ -1706,7 +1776,8 @@ pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result bool { - app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) + app.color_dialogs.recolor.as_ref().is_some_and(|open| open.problem(app).is_none()) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) } /// Row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -1725,6 +1796,10 @@ pub(super) fn with_new_color(app: &VectorcraftApp, d: &mut RecolorDialog, i: usi /// save colours opened alone as a new colour group). The dialog closes once this answers `Ok`; an /// `Err` keeps it open with the reason. fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { + let open = app.color_dialogs.recolor.as_ref().ok_or("Recolor Artwork is not open")?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } let mut d = fields.clone(); select_group(app, &mut d)?; sync(app, &mut d); @@ -1743,7 +1818,7 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { } r?; } - let preview = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)).unwrap_or_default(); + let preview = app.color_dialogs.recolor.as_mut().map(Open::take_preview).unwrap_or_default(); let committed = if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some())); preview.commit(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})) From 695071f594e2144db19d6480bbeb220f66cb2756 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:20:26 -0800 Subject: [PATCH 39/45] Keep Layer Options from editing reverted drawings --- crates/ui-egui/src/dialogs/layer_options.rs | 64 +++++++++++++++++++-- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 944051cf7d..c25df0cf41 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,9 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let st = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(st.uid, st.reverts, value))); Ok(Value::Null) } @@ -412,6 +412,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { pub(crate) struct LayerOptionsDialog { id: DialogId, document: u64, + reverts: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -423,8 +424,17 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(document: u64, value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, reverts: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { + id: dialog_id(KEY), + document, + reverts, + open: true, + value, + held: HeldAnswer::new(), + refused_at: None, + color_request: None, + } } /// The OK filed by the user, once. @@ -573,9 +583,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some((document, value)) = dialogs.with(|host| { + let Some((document, reverts, value)) = dialogs.with(|host| { let dialog = host.get_mut::()?; - Some((dialog.document, dialog.take_filed()?)) + Some((dialog.document, dialog.reverts, dialog.take_filed()?)) }) else { return; }; @@ -588,6 +598,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // Isolation mode can start while the dialog is open. let answer = match app.session.active().filter(|st| st.uid == document) { None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if st.reverts != reverts => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))), Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } @@ -935,4 +946,45 @@ mod tests { let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone(); assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true)); } + + #[test] + fn layer_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-layer-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, layer) = (original.uid, original.reverts, original.doc.layers[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Stale Draft")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.layers[0].id), (uid, reverts + 1, layer)); + let undo = reverted.history.undo.len(); + + let ctx = app.ui_ctx.clone().unwrap(); + let id = open_id(&app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.doc.node(layer).unwrap().display_name(), "Layer 1"); + assert_eq!(reverted.history.undo.len(), undo); + assert!(app.any_dialog_open(), "the refused draft stays available to inspect or cancel"); + assert_eq!(fields(&app)["name"], "Stale Draft"); + assert_eq!( + dialogs.with(|host| host.held_state(id)), + Some(HeldOk::Refused("The document was reverted. Reopen this dialog to continue.".into())) + ); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Fresh Draft")); + ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); + } } From 591955c0886dfa535040d71762944570eacfde46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:29:17 -0800 Subject: [PATCH 40/45] Exercise saved-name drafts after a real drawing revert --- crates/ui-egui/src/dialogs/saved_names.rs | 82 +++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index 0bbf1e89ea..6121947171 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -368,6 +368,88 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { mod tests { use super::*; + struct SavedFile(std::path::PathBuf); + + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + #[test] + fn saved_names_drafts_do_not_edit_a_reverted_drawing() { + for is_view in [false, true] { + let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let add_shape = |app: &mut VectorcraftApp, x| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + }; + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let open = |app: &mut VectorcraftApp| { + if is_view { + crate::dialogs::edit_views::open(app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(app).unwrap(); + crate::dialogs::edit_selection::KIND + } + }; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + add_shape(&mut app, 10); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + add_shape(&mut app, 40); + let old = app.session.active().unwrap(); + let (document, reverts) = (old.uid, old.reverts); + let kind = open(&mut app); + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap(); + host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID"); + assert_eq!(names(&mut app), json!(["Shared", "Spare"])); + let undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id))); + assert_eq!(open(&mut app), kind); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + host.confirm_by_id(&ctx, id); + }); + pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised", "Spare"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + } + #[test] fn saved_names_edits_stay_with_their_document() { for is_view in [false, true] { From e011f3ad716747a4e44d6804b88568634594f783 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:30:00 -0800 Subject: [PATCH 41/45] Refuse saved-name drafts opened before a document revert --- crates/ui-egui/src/dialogs/saved_names.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index 6121947171..0355c65eab 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -138,6 +138,7 @@ impl ItemSource for Shown<'_> {} pub(crate) struct SavedNamesDialog { id: DialogId, document: u64, + reverts: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -148,10 +149,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(document: u64, names: SavedNames, list: Vec) -> Self { + fn new(document: u64, reverts: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, reverts, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -327,9 +328,10 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); - let document = app.session.active().ok_or("no document open")?.uid; + let active = app.session.active().ok_or("no document open")?; + let (document, reverts) = (active.uid, active.reverts); let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, reverts, names, list))); Ok(()) } @@ -343,15 +345,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.document, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.reverts, dialog.names.command, edits)) }) .collect() }); - for (id, document, command, edits) in filed { - let outcome = if app.session.active().is_some_and(|active| active.uid == document) { - app.run(command, json!({ "edits": edits })) - } else { - Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + for (id, document, reverts, command, edits) in filed { + let outcome = match app.session.active().filter(|active| active.uid == document) { + Some(active) if active.reverts != reverts => Err(tl!("The document was reverted. Reopen the dialog to edit saved names.").to_owned()), + Some(_) => app.run(command, json!({ "edits": edits })), + None => Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()), }; if let Err(reason) = &outcome { app.status(reason.clone()); From 0ba6190b39452211fc0d82935c2c50f026a4e8f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:30:18 -0800 Subject: [PATCH 42/45] Verify selection and view drafts as separate revert cases --- crates/ui-egui/src/dialogs/saved_names.rs | 145 ++++++++++++---------- 1 file changed, 76 insertions(+), 69 deletions(-) diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index 0355c65eab..ed586dcb5c 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -379,77 +379,84 @@ mod tests { } #[test] - fn saved_names_drafts_do_not_edit_a_reverted_drawing() { - for is_view in [false, true] { - let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id()))); - let services = crate::Services { - read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), - write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), - ..Default::default() - }; - let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); - let add_shape = |app: &mut VectorcraftApp, x| { - app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); - }; - let names = |app: &mut VectorcraftApp| { - if is_view { - let views = &app.session.active().unwrap().doc.views; - json!(views.iter().map(|view| &view.name).collect::>()) - } else { - app.run("select.savedList", json!({})).unwrap() - } - }; - let open = |app: &mut VectorcraftApp| { - if is_view { - crate::dialogs::edit_views::open(app).unwrap(); - crate::dialogs::edit_views::KIND - } else { - crate::dialogs::edit_selection::open(app).unwrap(); - crate::dialogs::edit_selection::KIND - } - }; - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - add_shape(&mut app, 10); - for name in ["Shared", "Spare"] { - app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + fn saved_selection_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(false); + } + + #[test] + fn saved_views_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(true); + } + + fn exercise_reverted_draft(is_view: bool) { + let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let add_shape = |app: &mut VectorcraftApp, x| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + }; + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() } - app.run("file.saveAs", json!({"path": path.0})).unwrap(); - assert!(path.0.is_file()); - add_shape(&mut app, 40); - let old = app.session.active().unwrap(); - let (document, reverts) = (old.uid, old.reverts); - let kind = open(&mut app); - let id = id_of(kind); - let ctx = app.ui_ctx.clone().unwrap(); - let dialogs = app.dialogs().unwrap(); - dialogs.with(|host| { - host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap(); - host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); - assert!(!host.confirm_by_id(&ctx, id)); - assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); - }); - - app.run("file.revert", json!({"confirmed": true})).unwrap(); - let active = app.session.active().unwrap(); - assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID"); - assert_eq!(names(&mut app), json!(["Shared", "Spare"])); - let undo = app.session.active().unwrap().history.undo.len(); - pump(&mut app, &ctx); - - assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing"); - assert_eq!(app.session.active().unwrap().history.undo.len(), undo); - assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); - assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id))); - assert_eq!(open(&mut app), kind); - dialogs.with(|host| { - host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); - host.confirm_by_id(&ctx, id); - }); - pump(&mut app, &ctx); - assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted))); - assert_eq!(names(&mut app), json!(["Revised", "Spare"])); - assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + }; + let open = |app: &mut VectorcraftApp| { + if is_view { + crate::dialogs::edit_views::open(app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(app).unwrap(); + crate::dialogs::edit_selection::KIND + } + }; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + add_shape(&mut app, 10); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); } + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + add_shape(&mut app, 40); + let old = app.session.active().unwrap(); + let (document, reverts) = (old.uid, old.reverts); + let kind = open(&mut app); + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap(); + host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID"); + assert_eq!(names(&mut app), json!(["Shared", "Spare"])); + let undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id))); + assert_eq!(open(&mut app), kind); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + host.confirm_by_id(&ctx, id); + }); + pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised", "Spare"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); } #[test] From 03030058fe73df1dbc643596104931930edb2d09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:33:52 -0800 Subject: [PATCH 43/45] Discard stale Document Setup after Revert --- crates/ui-egui/src/dialogs/document_setup.rs | 48 +++++++++++++++++++- crates/ui-egui/src/lib.rs | 2 +- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index c3aa0ef099..0c6e1b5f56 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = ((st.uid, st.reverts), st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -186,8 +186,12 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { - if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + let source = app.document_setup_source.and_then(|(uid, reverts)| app.session.active().filter(|st| st.uid == uid).map(|st| (st, reverts))); + let Some((doc, reverts)) = source else { return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + }; + if doc.reverts != reverts { + return Err(tl!("Reopen Document Setup after reverting the drawing.").to_owned()); } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); @@ -700,6 +704,46 @@ mod tests { check_source_document(true); } + #[test] + fn a_revert_refuses_a_stale_document_setup_for_both_confirmation_paths() { + for edit_artboards in [false, true] { + let (mut app, ctx) = new_app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("document-setup-revert"); + let path = dir.join("setup.vectorcraft"); + app.run("document.setup", json!({"bleed": [2, 2, 2, 2]})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("document.setup", json!({"bleed": [7, 7, 7, 7]})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + let source = app.session.doc().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + let undo = reverted.history.undo.len(); + if edit_artboards { + set(&app, &ctx, "editArtboards", json!(true)); + super::pump(&mut app, &ctx); + } else { + assert!(!press_ok(&mut app, &ctx)); + } + assert!(is_open(&app)); + assert_eq!(app.session.tool_id(), "selection"); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.doc.setup.bleed, [2.0; 4]); + assert_eq!(reverted.history.undo.len(), undo); + + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([5, 5, 5, 5])); + assert!(press_ok(&mut app, &ctx)); + assert_eq!(app.session.doc().unwrap().doc.setup.bleed, [5.0; 4]); + } + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a9b143e397..6265c001c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -274,7 +274,7 @@ pub struct VectorcraftApp { /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The document whose settings the open Document Setup dialog edits. - pub(crate) document_setup_source: Option, + pub(crate) document_setup_source: Option<(u64, u64)>, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one /// step however many values it sets. pub(crate) edit_scopes: HashMap, From 04faef583ad0141fd82c872cdf65bfc57c450965 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:41:08 -0800 Subject: [PATCH 44/45] Import browser-picked Preferences files --- crates/ui-egui/src/prefs_dialog.rs | 20 ++++++++++++-- crates/ui-egui/src/prefs_dialog/tests.rs | 35 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 5a66573eef..c1908fd90f 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -308,9 +308,23 @@ fn export_preferences(app: &mut VectorcraftApp) { fn import_preferences(app: &mut VectorcraftApp) { let request = PickRequest::open("preferences").filter("Preferences", &["json"]); file_asks::ask(app, request, Owner::Free, |app, picked| { - let Picked::Paths(paths) = picked else { return Ok(Value::Null) }; - let Some(path) = paths.first() else { return Ok(Value::Null) }; - match app.run("prefs.import", json!({ "path": path.to_string_lossy() })) { + let params = match picked { + Picked::Paths(paths) => { + let Some(path) = paths.first() else { return Ok(Value::Null) }; + json!({ "path": path.to_string_lossy() }) + } + Picked::Contents(files) => { + let Some((_, bytes)) = files.into_iter().next() else { return Ok(Value::Null) }; + // Match prefs.import's file cap before allocating its JSON text parameter. + if bytes.len() > 1 << 20 { + return Err("The preferences file is larger than 1 MB".into()); + } + let data = String::from_utf8(bytes).map_err(|_| "The preferences file is not valid UTF-8")?; + json!({ "data": data }) + } + _ => return Ok(Value::Null), + }; + match app.run("prefs.import", params) { Ok(_) => app.status("Preferences imported."), Err(e) => app.status(e), } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 81b8e4219e..6bdf24de68 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -797,6 +797,41 @@ fn prefs_import_refreshes_an_open_preferences_dialog() { assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0)); } +#[test] +fn browser_import_applies_picked_preferences_and_refreshes_the_draft() { + let mut a = app(); + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + let picker = crate::tests::picks::scripted(&mut a); + a.services.read = None; + let data = json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"keyboardIncrement": 7}}).to_string(); + import_preferences(&mut a); + picker.answer_contents(&[("preferences.json", data.as_bytes())]); + file_asks::poll(&mut a); + assert!(same(&field(&a, "keyboardIncrement"), &json!(7.0))); + assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0)); + assert_eq!(a.ui.status, "Preferences imported."); + assert!(is_open(&a)); +} + +#[test] +fn browser_import_refuses_bad_contents_without_losing_draft_edits() { + for bytes in [vec![0xff], vec![b' '; (1 << 20) + 1], b"not JSON".to_vec()] { + let mut a = app(); + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + let before = a.session.prefs.to_json(); + let picker = crate::tests::picks::scripted(&mut a); + import_preferences(&mut a); + picker.answer_contents(&[("preferences.json", &bytes)]); + file_asks::poll(&mut a); + assert_eq!(a.session.prefs.to_json(), before); + assert!(same(&field(&a, "keyboardIncrement"), &json!(9))); + assert!(!a.ui.status.is_empty(), "the invalid picked file reports an error"); + assert_ne!(a.ui.status, "Preferences imported."); + } +} + /// An import that turns Enable Touch Workspace on or off switches the workspace on a touch screen, /// as OK in Preferences does. #[test] From 75fa147553f4466d9679267d335c3de9768d656e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:41:08 -0800 Subject: [PATCH 45/45] Open and save Proof Setup files in the browser --- crates/engine/src/cmd/colormgmt/proof_file.rs | 47 +++++--- crates/ui-egui/src/dialogs/proof_setup.rs | 104 ++++++++++++++---- 2 files changed, 119 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs index 7e6c3f2184..e67bc5e3bd 100644 --- a/crates/engine/src/cmd/colormgmt/proof_file.rs +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec { pub(super) fn save(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup.save"; let (path, named) = file_path(s, p, C)?; - let mut setup = proof::view().setup; - setup_params(p, &mut setup, C)?; - check_device(&setup.target).map_err(|e| bad(C, e))?; - // A file `view.proofSetup.load` would refuse is not written (a device with a very long name). - let bytes = encode(&setup); - if bytes.len() > MAX_FILE { - return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes"))); - } + let (setup, bytes) = encode_options(p, &path)?; if named && let Some(dir) = std::path::Path::new(&path).parent() && !dir.is_dir() @@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { Ok(Value::Object(r)) } +/// Serialize the Customize dialog's draft without committing it or writing a path. +pub fn draft_bytes(p: &Value) -> Result> { + encode_options(p, "Proof Setup").map(|(_, bytes)| bytes) +} + +fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec)> { + const C: &str = "view.proofSetup.save"; + let mut setup = proof::view().setup; + setup_params(p, &mut setup, C)?; + check_device(&setup.target).map_err(|e| bad(C, e))?; + let bytes = encode(&setup); + if bytes.len() > MAX_FILE { + return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes"))); + } + Ok((setup, bytes)) +} + /// The file `p` names for `cmd` and the usable proof setup in it. fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> { let (path, _) = file_path(s, p, cmd)?; // One byte past the limit shows a file over it, which is not read further. let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?; - if bytes.len() > MAX_FILE { - return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes"))); - } - let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + let setup = checked_setup(&bytes, &path, cmd)?; Ok((path, setup)) } +/// Read a picked proof setup's validated settings without applying them to the view. +pub fn draft_fields(bytes: &[u8], name: &str) -> Result { + let setup = checked_setup(bytes, name, "view.proofSetup.read")?; + Ok(Value::Object(setup_json(&setup))) +} + +fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result { + if bytes.len() > MAX_FILE { + return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes"))); + } + let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + Ok(setup) +} + pub(super) fn read(s: &mut Session, p: &Value) -> Result { let (path, setup) = read_setup(s, p, "view.proofSetup.read")?; let mut r = setup_json(&setup); diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index a5987f699b..cb0e6981d2 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -4,8 +4,8 @@ //! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and //! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save… //! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one -//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the -//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below +//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy +//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below //! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker //! starts in its own default folder until the folder exists. //! @@ -116,15 +116,10 @@ fn rgb_device(device: &str) -> bool { /// The dialog over the host's values, made again every pass. fn build(fields: &mut DialogFields) -> ParamDialog<'_> { - // The web has no folder to keep setups in. - let footer = if cfg!(target_arch = "wasm32") { - Vec::new() - } else { - vec![ - (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), - (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), - ] - }; + let footer = vec![ + (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), + (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), + ]; ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer) } @@ -297,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s /// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again. fn save(app: &mut VectorcraftApp, fields: &DialogFields) { + let mut request = + PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); + let mut p = params(fields); + if let Some(o) = p.as_object_mut() { + o.remove("proof"); + } + if app.host.files().browser_saves() { + match proof_file::draft_bytes(&p) { + Ok(bytes) => { + crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| { + match picked { + Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), + Picked::Downloaded(name) => app.status(format!("Saved {name}")), + Picked::Failed(error) => return Err(error), + _ => {} + } + Ok(Value::Null) + }); + } + Err(e) => app.status(e.to_string()), + } + return; + } // The picker opens in the folder, made for it when it may be written. [`list_saved`] removes // it again when the picker closes without a file in it. let dir = app.session.proof_setup_dir().map(Path::to_path_buf); @@ -307,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { if made.is_some() { saved().made = made; } - let mut request = - PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); if let Some(dir) = dir { request = request.directory(dir); } - let mut p = params(fields); - if let Some(o) = p.as_object_mut() { - o.remove("proof"); - } ask(app, request, Owner::Free, move |app, picked| { let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) }; let path = path.to_string_lossy().into_owned(); @@ -343,8 +355,16 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) }; ask_while(app, request, Owner::Free, is_live, move |app, picked| { - let Some(path) = picked.first_path() else { return Ok(Value::Null) }; - let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; + let r = match picked { + Picked::Contents(files) => { + let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) }; + proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())? + } + other => { + let Some(path) = other.first_path() else { return Ok(Value::Null) }; + app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))? + } + }; let fields = [ ("device", "target"), ("intent", "intent"), @@ -817,6 +837,52 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_browser_pick_loads_a_proof_setup_into_the_draft() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "preview", json!(false)); + let before = proof::view(); + let mut source = before.setup.clone(); + source.intent = Intent::Saturation; + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))])); + crate::file_asks::poll(&mut app); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])])); + crate::file_asks::poll(&mut app); + assert!(app.ui.status.contains("larger than")); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + } + + #[test] + fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] { + set(&mut app, &ctx, k, v); + } + let before = proof::view(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save"); + let path = dir.join("draft.vcproof"); + press(&mut app, &ctx, SAVE); + files.answer(Picked::Saved { path: path.clone(), file_type: None }); + crate::file_asks::poll(&mut app); + let bytes = files.file(&path).expect("the browser file service receives the draft bytes"); + assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation); + assert_eq!(proof::view(), before); + assert_eq!(values(&app)["intent"], "saturation"); + assert!(!path.exists(), "the browser save does not write through the native path"); + } + #[test] fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { let _view = DefaultProofView::new();