From 72984fddaacd6ec248ccb1acaea34ae96d58b20e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:53:08 -0800 Subject: [PATCH 01/23] Enforce data limits on host receivers and indexers --- crates/js/src/host.rs | 63 +++++++++++++++++++++++++---------- crates/js/src/host_classes.rs | 13 +++++--- crates/js/src/host_tests.rs | 48 ++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 21 deletions(-) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..276895e782 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -265,9 +266,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -299,6 +298,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -407,16 +414,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +462,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,8 +504,8 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, @@ -520,7 +519,14 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { @@ -552,6 +558,29 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d2994fb80b..9d14718dee 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -172,6 +172,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -220,11 +226,10 @@ impl Interp { /// gets `true` as a third argument. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - let mut args = vec![this, k]; - if probe { - args.push(Data::Bool(true)); + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); } + let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 25265086e5..1d199fb16c 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -11,6 +11,54 @@ fn realm(fuel: u64) -> Realm { r } +#[test] +fn non_finite_indexer_keys_reach_the_host_unchanged() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|args| Ok(Data::Bool(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite())))); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); +} + +#[test] +fn host_receivers_obey_limits_lowered_after_the_object_was_created() { + for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { + for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] { + let mut r = realm(1_000_000); + let calls = Rc::new(Cell::new(0)); + let called = calls.clone(); + let function: HostFunction = Rc::new(move |_| { + called.set(called.get() + 1); + Ok(Data::Undefined) + }); + let class = HostClass { + name: "Indexed".into(), + parent: None, + members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))], + index: Some(function), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap(); + r.set_data_limits(limits); + let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}"); + assert_eq!(calls.get(), 0, "{expression}"); + } + } +} + +#[test] +fn index_keys_share_the_receivers_data_budget() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); + assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); + let source = "var result = 'called'; try { it[new Array(200).join('x')]; } catch (e) { result = e.name; } result"; + assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); +} + /// A realm with `host.take(value)`, which records what it was given and returns it. fn with_take(r: &mut Realm) -> Rc>> { let seen: Rc>> = Rc::default(); From 10c8cba547a212aac504df4bf75bf1270f75fef4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:45:56 -0800 Subject: [PATCH 02/23] Keep Swatches list drags in the document that started them --- crates/ui-egui/src/panel_drag.rs | 2 + crates/ui-egui/src/panels/swatches.rs | 9 ++-- crates/ui-egui/src/panels/swatches/dnd.rs | 7 +-- crates/ui-egui/src/panels/swatches/tests.rs | 56 ++++++++++++++++++++- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 83ebf46070..27cab1fe2c 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -41,6 +41,8 @@ pub enum PanelDrag { /// panel order. #[derive(Clone, Debug, PartialEq)] pub struct SwatchRows { + /// The document whose rows the drag started on. + pub document: u64, pub grabbed: String, pub names: Vec, /// The names are colour groups. diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 58f24ed3f5..bb8eaa994f 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -409,8 +409,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let dragged_doc = Arc::clone(&thumbs.doc); let document = st.uid; let shown_app: &VectorcraftApp = app; - let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) + let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), @@ -422,8 +422,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) - .footer(None) - .show(ui); + .footer(None); + // A list drag is keyed by its browser ID. Each document has its own browser. + let out = ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner; app.ui.swatches_panel = model; let shown = shown_keys(&data); if let Some((at, _, alt)) = out.used diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2151357979..f4d100f2d6 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,9 +4,10 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; -/// Swatches take paint payloads and artwork from the current document's canvas. +/// Swatches take paints, and take swatch rows or canvas art from the current document. pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { match drag { + PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, PanelDrag::Paint { .. } => true, PanelDrag::Art { document: source, .. } => *source == document, _ => false, @@ -53,7 +54,7 @@ impl Drop { /// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own /// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> PanelDrag { +pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { let name = name_of(key); let (paint, params) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name)), @@ -63,7 +64,7 @@ pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec) -> Pane }, _ => (Paint::None, Value::Null), }; - let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; + let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index c770f5094a..0e5387e547 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -96,7 +96,61 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { /// The drag the row `name` starts, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - dnd::drag_of(&doc(app), &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) + let document = app.session.active().unwrap().uid; + dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) +} + +#[test] +fn a_swatch_row_drag_reorders_only_its_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, Role}; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = app(); + let source = app.session.active().unwrap().uid; + let before_source = names_of(&app, None); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let destination = app.session.active().unwrap().uid; + let before_destination = names_of(&app, None); + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + + let mut panel = Panel::new(app, show); + let drag_red = |panel: &mut Panel| { + let red = "Red, #ed1c24"; + let from = panel.rect(red).center(); + let to = panel.rect("Green, #39b54a").center(); + panel.drag_hold_role(red, Role::LIST_ITEM, to - from); + let grabbed = drag::active::>(panel.ctx()).map(|d| d.grabbed.clone()); + assert_eq!(grabbed, Some(SwatchKey::Swatch("Red".into()))); + }; + drag_red(&mut panel); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + panel.release(); + assert_eq!(names_of(&panel.app(), None), before_destination); + + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, source); + assert_eq!(names_of(&panel.app(), None), before_source); + drag_red(&mut panel); + panel.release(); + assert_ne!(names_of(&panel.app(), None), before_source); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(names_of(&panel.app(), None), before_source); +} + +#[test] +fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { + let mut app = app(); + let drag = rows_drag(&app, "Red", &["Red"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let before = doc(&app); + assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid)); + dropped_below(&mut app, drag.clone(), none()); + dropped(&mut app, drag, "Green", alt()); + assert_eq!(doc(&app).swatches, before.swatches); } /// Art `ids` dragged off the canvas. From 293a7d2cb1616f79bb66dc16dfc825937b996b54 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:57:51 -0800 Subject: [PATCH 03/23] Disambiguate the color checksum dependency in Cargo.lock --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] From 237f97b87b12cdfb89216281fa1a1cf01dedca6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:06:49 -0800 Subject: [PATCH 04/23] Keep CSS Properties actions reachable in short panels --- crates/ui-egui/src/panels/css_properties.rs | 97 ++++++++++++++++----- 1 file changed, 74 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index b3e8833076..91683cc016 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use craft::behavior::IconId; use craft::keymap::CommandRef; use craft::theme::variant::Tone; -use craft::ui::contract::{Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Stack; use craft::ui::menu::PanelRow; @@ -132,19 +132,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let opts = app.ui.css_properties_panel.options.clone(); let all = !selected && app.ui.css_properties_panel.all; let Some(shown) = shown(app, &opts, all) else { return }; - Stack::new().fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { - let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); - if shown.rules > 0 { - SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); - } else if selected { - let hint = tl!("The selected objects have no CSS of their own (see below)."); - Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } else { - let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); - Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); - } - }); - let notes = (shown.more > 0) + let notes: Vec<_> = (shown.more > 0) .then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one.")) .into_iter() .chain((shown.skipped > 0).then(|| { @@ -154,23 +142,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { "{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.", ) })) - .chain(shown.warnings.iter().map(|w| sentence(w))); - for n in notes { - Text::new(n).role(TypeRole::Caption).shade(Shade::Muted).show(ui); - } + .chain(shown.warnings.iter().map(|w| sentence(w))) + .collect(); let has_css = shown.rules > 0; let scope = if all { "all" } else { "selection" }; // Generate at the start edge; Export at the end edge with Copy before it. - let footer = FooterBar::actions([ + let actions = [ FooterAction::new(IconId::new("sparkles"), tl!("Generate CSS: the whole document's CSS while nothing is selected")) .pressed(all) .enabled(!selected), FooterAction::new(IconId::new("save"), if all { tl!("Export All…") } else { tl!("Export Selected CSS…") }).enabled(has_css), FooterAction::new(IconId::new("copy"), if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") }).enabled(has_css), - ]) - .at_start(1) - .show_footer(ui); - match footer.picked { + ]; + let mut picked = None; + let notes_room = (ui.available_height() / 3.0).min(72.0); + Stack::new() + .fill() + .footer(|ui, _| { + if !notes.is_empty() { + Stack::new().label(tl!("Notes")).fill_width().scroll(Scroll::vertical()).room_height(notes_room).show(ui, |ui, _| { + for note in ¬es { + Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + } + }); + } + let footer = FooterBar::actions(actions.clone()).at_start(1).show_footer(ui); + if !ui.is_sizing_pass() { + picked = footer.picked; + } + }) + .show(ui, |ui, _| { + Stack::new().label(tl!("CSS Properties")).fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| { + let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe"))); + if shown.rules > 0 { + SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui); + } else if selected { + let hint = tl!("The selected objects have no CSS of their own (see below)."); + Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } else { + let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document."); + Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui); + } + }); + }); + match picked { Some(0) => { crate::menus::invoke(app, GENERATE, json!({})); } @@ -311,3 +326,39 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option return None, }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + #[test] + fn generated_css_notices_keep_the_actions_in_a_short_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({ "width": 100, "height": 100 })).unwrap(); + for card in 0..12 { + let id = app.run("shape.rectangle", json!({ "x": 0, "y": 0, "width": 20, "height": 20 })).unwrap()["id"].clone(); + app.run("layer.setProps", json!({ "id": id, "name": format!("Card-{card}") })).unwrap(); + } + app.run("shape.ellipse", json!({ "x": 30, "y": 0, "width": 20, "height": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + let options = CssOptions { unnamed: false, ..CssOptions::default() }; + let styles = shown(&mut app, &options, true).unwrap(); + assert_eq!((styles.rules, styles.skipped), (12, 1)); + app.ui.css_properties_panel = CssPropertiesPanel { options, all: true }; + + let mut panel = Panel::new(app, show); + let room = egui::vec2(220.0, 220.0); + panel.room(room).frame(); + panel.frame(); + for name in ["Copy All Styles", "Export All…"] { + let action = panel.rect(name); + assert!(action.bottom() <= room.y && action.right() <= room.x, "{name} overflows the panel at {action:?}"); + assert!(panel.enabled(name), "{name} is enabled when there is CSS"); + } + let notice = panel.rect("1 unnamed object left out: name it, or turn on Unnamed Objects in the panel menu."); + assert!(notice.top() >= 0.0 && notice.bottom() <= panel.rect("Copy All Styles").top(), "the notice fits above the actions: {notice:?}"); + assert!(notice.left() >= 0.0 && notice.right() <= room.x, "the notice wraps within the panel: {notice:?}"); + } +} From dfa6bae8eb69fb00ae56e35b72f0c77664c4cb1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:27:23 -0800 Subject: [PATCH 05/23] Strengthen host indexer argument and shared-budget assertions --- crates/js/src/host_tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 125ff9c43b..8c4b036898 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -14,7 +14,10 @@ fn realm(fuel: u64) -> Realm { #[test] fn non_finite_indexer_keys_reach_the_host_unchanged() { let mut r = realm(1_000_000); - let index: HostFunction = Rc::new(|args| Ok(Data::Bool(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite())))); + let index: HostFunction = Rc::new(|args| { + assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}"); + Ok(Data::Bool(true)) + }); let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; @@ -55,7 +58,7 @@ fn index_keys_share_the_receivers_data_budget() { r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); - let source = "var result = 'called'; try { it[new Array(200).join('x')]; } catch (e) { result = e.name; } result"; + let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result"; assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); } From 3b029f3fecd76c3a43026970dbbff158c0c2a4b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:38:39 -0800 Subject: [PATCH 06/23] Keep Anchor Inspector actions reachable in short panels --- crates/ui-egui/src/addons/pathtools.rs | 8 ++++-- crates/ui-egui/src/addons/pathtools/tests.rs | 26 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 1914b37a36..8ad60b5fb4 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -17,10 +17,10 @@ pub mod tangent_circle; use craft::behavior::ColumnWidth; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::text::NumberField; @@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); return; } + Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui)); +} + +fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let readout = readout(app); let anchor = readout.anchor.as_ref(); let selected = app.session.active().is_some_and(|st| !st.selection.is_empty()); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index df2571a136..9a63194c34 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles); } +#[test] +fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { + let mut app = app(); + let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap(); + let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let mut panel = Panel::new(app, super::show); + let room = egui::vec2(220.0, 215.0); + panel.room(room).frame(); + panel.frame(); + let action = "Remove Points, Keep Shape"; + assert!(panel.rect(action).bottom() > room.y, "the action starts clipped"); + panel.focus(action); + let rect = panel.rect(action); + assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}"); + panel.focus("Make Smooth"); + panel.click("Make Smooth"); + let anchor = readout(&panel.app()).anchor.unwrap(); + assert!(anchor.lengths.iter().all(|length| *length > 0.0)); +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) From 90c9b981bbd5640a516a150edfed753ad852b496 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:17:44 -0800 Subject: [PATCH 07/23] Qualify the color crate SHA-256 lock dependency --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] From 7124a1ae45b6057da8d8321264d42dd7075a07a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:40:25 -0800 Subject: [PATCH 08/23] Keep Image Trace actions reachable in compact panels --- crates/ui-egui/src/panels/image_trace.rs | 198 +++++++++++++----- .../ui-egui/src/panels/image_trace/tests.rs | 84 ++++++++ crates/ui-egui/src/tests/panel_harness.rs | 7 + 3 files changed, 240 insertions(+), 49 deletions(-) diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 0dce28aaa8..afd294a0e5 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -14,21 +14,26 @@ use std::sync::Arc; // PLAN: assumed import paths of the framework items below: `craft::ui::primitives::IconId`, // `craft::ui::runtime::commands::{CommandState, CommandStates}`, `craft::ui::menu::PanelRow`, // `craft::ui::patterns::presets::*`, `crate::edits` (widgets-w13) and `crate::chrome::rank` (chrome-w16). -use craft::behavior::IconId; +use craft::behavior::{IconId, Metrics, Proposal, ScrollPos, Sense}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, IconButton, SplitButton, SplitMenu, ToggleButton}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{ + Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Entry, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, +}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, SliderField, SliderFieldLayout}; -use craft::ui::layout_components::Row; +use craft::ui::layout::BodyLayout; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::Env; use craft::ui::sections::Section; +use craft::ui::style::{ComponentStyle, StyleCx}; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; @@ -786,7 +791,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { st.preset = "Default".into(); st.params = list.presets.first().map(|p| p.1.clone()).unwrap_or_default(); } - let (is_trace, is_image, any_trace) = (t.is_trace, t.is_image, t.any_trace); // The saved preset changes since the last frame apply to the panel's settings before the selected object's // settings, which `sync_with_object` resolves against every change, are adopted. follow_preset_changes(app, &mut st, &list.presets); @@ -794,6 +798,135 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes) }; + let preview = app.ui.image_trace_preview; + let mut actions = (false, false, false); + let stack = Stack::new().label(tl!("Image Trace")).fill().scroll(Scroll::vertical()); + let env = Env::of(ui); + let settings_row = env.tokens.size.control.md + env.tokens.space.gap.row; + let footer = Stack::new().id_salt("trace-footer-measure").measure_in(ui, Proposal::Width(ui.available_width()), |ui, _| { + show_footer(ui, preview, &t); + }); + let compact_offset = ui.scope_id().with("trace-compact-offset"); + let settings = if ui.available_height() >= footer.y + settings_row { + if !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.remove::(compact_offset)); + } + stack.footer(|ui, _| actions = show_footer(ui, preview, &t)).show(ui, |ui, _| show_settings(app, ui, &mut st, &list, &t)) + } else { + // When the footer moves into the scroll area, start with its actions in view. + let before = ui.ctx().data(|data| data.get_temp(compact_offset)).unwrap_or_default(); + let mut offset = before; + let shown = CompactSettings::new(Bind::bound(&mut offset)).show(ui, |ui, _| { + actions = show_actions(ui, preview, &t); + Divider::horizontal().show(ui); + show_settings(app, ui, &mut st, &list, &t) + }); + if offset != before && !ui.is_sizing_pass() { + ui.ctx().data_mut(|data| data.insert_temp(compact_offset, offset)); + } + shown + }; + let (mut retrace, held) = settings.inner.unwrap_or_default(); + let (preview_toggled, trace_clicked, expand_clicked) = actions; + if !ui.is_sizing_pass() { + hold_source(app, t.any_trace && held); + } + if preview_toggled { + run_reporting(app, "imageTrace.preview", json!({})); + } + if trace_clicked { + trace(app, &mut st); + } + if expand_clicked { + run_reporting(app, "imageTrace.expand", json!({})); + } + // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is + // traced with the settings that waited in the panel. With no Image Trace object selected, it is + // traced when it is selected again. An object whose settings waited while another object was + // selected is traced when it is selected again with Preview on. + let preview = app.ui.image_trace_preview; + retrace |= preview && (st.preview_off || restored) && t.is_trace && st.params != st.synced["params"]; + if t.is_trace || !preview { + st.preview_off = !preview; + } + cancel_disabled_ignore_sampler(app, &st.params); + if retrace && t.is_trace && preview { + trace(app, &mut st); + } + app.ui.image_trace_panel.shown = st; +} + +/// The very short layout needs a bound offset so returning to it shows the actions first. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(container, unregistered)] +struct CompactSettings<'a> { + #[common] + common: Common, + #[container] + props: ContainerProps, + offset: Bind<'a, ScrollPos>, +} + +impl<'a> CompactSettings<'a> { + fn new(offset: Bind<'a, ScrollPos>) -> Self { + let props = ContainerProps::new().sizing(Sizing::Fill).layout(BodyLayout::stack()).scroll(Scroll::vertical()); + Self { common: Common::new(), props, offset }.label(tl!("Image Trace")) + } +} + +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct CompactSettingsStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for CompactSettings<'_> { + const ROLE: Role = Role::GROUP; + type Style = CompactSettingsStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: CompactSettingsStyleKey) -> CompactSettingsStyle { + CompactSettingsStyle { metrics: Metrics::new() } + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn scroll(&mut self) -> Option> { + Some(self.offset.reborrow()) + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +impl Container for CompactSettings<'_> {} + +fn show_footer(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + Divider::horizontal().show(ui); + show_actions(ui, preview, target) +} + +fn show_actions(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) { + let mut value = preview; + let mut trace_clicked = false; + let mut expand_clicked = false; + Row::new().wrap(true).show(ui, |ui, _| { + Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); + let can_trace = target.is_trace || target.is_image; + let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); + if !can_trace { + trace_button = trace_button.tooltip(tl!("Select an image to trace")); + } + trace_clicked = trace_button.show(ui).clicked(); + expand_clicked = Button::new(tl!("Expand")).enabled(target.any_trace).show(ui).clicked(); + }); + (value != preview, trace_clicked, expand_clicked) +} + +fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: &PresetList, t: &Target) -> (bool, bool) { let mut retrace = false; // A preset button chooses its preset as the Preset row does; the button of the panel's @@ -804,7 +937,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut on = was; ToggleButton::new(label, Bind::bound(&mut on)).tooltip(preset_label(name)).show(ui); if on && !was { - retrace |= choose_preset(&mut st, &list.presets, name); + retrace |= choose_preset(st, &list.presets, name); } } }); @@ -824,7 +957,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); for event in preset_row.events { match event { - NamedPresetEvent::Apply(name) => retrace |= choose_preset(&mut st, &list.presets, &name), + NamedPresetEvent::Apply(name) => retrace |= choose_preset(st, &list.presets, &name), NamedPresetEvent::Create { name, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": name, "params": st.params })), NamedPresetEvent::Rename { key, text, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": key, "newName": text })), NamedPresetEvent::Delete(name) => run_reporting(app, "imageTrace.presets.delete", json!({ "name": name })), @@ -845,21 +978,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Row::new().show(ui, |ui, _| { picked = view_pick(ui, st.view); let tip = tl!("Press and hold to view the source image"); - held = - IconButton::new(IconId::new("eye")).label(tip).tooltip(tip).selected(app.ui.trace_hold_source.is_some()).enabled(any_trace).show(ui).held; + held = IconButton::new(IconId::new("eye")) + .label(tip) + .tooltip(tip) + .selected(app.ui.trace_hold_source.is_some()) + .enabled(t.any_trace) + .show(ui) + .held; }); if let Some(v) = picked { st.view = v; - if any_trace { + if t.any_trace { set_view(app, v); } } - hold_source(app, any_trace && held); split_row(app, ui); let data = RowsData::of(app); let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); - let sampler = Sampler { enabled: is_trace || is_image, armed: app.ui.trace_ignore_sampler.is_some() }; + let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; let advanced = Section::new(tl!("Advanced")) .open(Bind::bound(&mut app.ui.image_trace_advanced)) .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) @@ -880,7 +1017,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { cancel_ignore_sampler(app, true); } - Divider::horizontal().show(ui); if let Some((p, a, c)) = st.info { Text::new(crate::i18n::fmt( tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"), @@ -889,43 +1025,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .shade(Shade::Muted) .show(ui); } - let (mut preview_toggled, mut trace_clicked, mut expand_clicked) = (false, false, false); - Row::new().show(ui, |ui, _| { - let preview = app.ui.image_trace_preview; - let mut value = preview; - Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui); - preview_toggled = value != preview; - let can_trace = is_trace || is_image; - let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace); - if !can_trace { - trace_button = trace_button.tooltip(tl!("Select an image to trace")); - } - trace_clicked = trace_button.show(ui).clicked(); - expand_clicked = Button::new(tl!("Expand")).enabled(any_trace).show(ui).clicked(); - }); - if preview_toggled { - run_reporting(app, "imageTrace.preview", json!({})); - } - if trace_clicked { - trace(app, &mut st); - } - if expand_clicked { - run_reporting(app, "imageTrace.expand", json!({})); - } - // Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is - // traced with the settings that waited in the panel. With no Image Trace object selected, it is - // traced when it is selected again. An object whose settings waited while another object was - // selected is traced when it is selected again with Preview on. - let preview = app.ui.image_trace_preview; - retrace |= preview && (st.preview_off || restored) && is_trace && st.params != st.synced["params"]; - if is_trace || !preview { - st.preview_off = !preview; - } - cancel_disabled_ignore_sampler(app, &st.params); - if retrace && is_trace && preview { - trace(app, &mut st); - } - app.ui.image_trace_panel.shown = st; + (retrace, held) } /// The panel menu's rows: Release and Expand act on the selected Image Trace objects. diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index b72c13639d..3935cbe8c2 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -99,6 +99,90 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp { app } +fn scroll_settings(panel: &mut Panel, dy: f32) { + panel.scroll_at(egui::pos2(30.0, 30.0), dy); + panel.advance(1.0); + panel.frame(); +} + +#[test] +fn preview_trace_and_expand_stay_reachable_in_a_compact_panel() { + let mut app = traced_app(); + app.run("imageTrace.release", json!({})).unwrap(); + app.ui.image_trace_advanced = true; + let source = first_selected(&app).unwrap(); + assert!(matches!(source.kind, NodeKind::Image(_))); + let mut panel = panel_over(app); + assert!(panel.rect_role("Image Trace", craft::ui::contract::Role::GROUP).is_positive()); + for size in [egui::vec2(148.0, 480.0), egui::vec2(240.0, 170.0), egui::vec2(148.0, 170.0)] { + panel.room(size); + panel.frame(); + panel.frame(); + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for label in ["Preview", "Trace", "Expand"] { + assert!(panel.in_view(label), "{label} is clipped at {size:?}"); + let rect = panel.rect(label); + assert!(room.contains_rect(rect), "the whole {label} control {rect:?} fits at {size:?}"); + } + assert!(panel.enabled("Trace")); + assert!(!panel.enabled("Expand")); + } + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview); + + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the settings scroll"); + assert_eq!(panel.rect("Trace"), action, "scrolling settings leaves the action in place"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "scrolling reaches the end of Advanced"); + + panel.click("Trace"); + assert!(selected_trace(&panel.app()).is_some()); + assert!(panel.enabled("Expand")); + panel.click("Expand"); + assert!(selected_trace(&panel.app()).is_none()); + assert!(!is_trace(&first_selected(&panel.app()).unwrap())); + panel.app().run("edit.undo", json!({})).unwrap(); + assert!(selected_trace(&panel.app()).is_some()); + + // A single action row needs less height than the wrapped footer in the narrow panel. + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.frame(); + scroll_settings(&mut panel, 1000.0); + let action = panel.rect("Trace"); + let first_preset = panel.rect("Auto Color").top(); + scroll_settings(&mut panel, -1000.0); + assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the short settings viewport scrolls"); + assert!(panel.in_view("Trace")); + assert_eq!(panel.rect("Trace"), action, "a short panel still pins the footer when the actions fit on one line"); + + // Shorten the panel while the settings-only body remains scrolled to Advanced. + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "Preview starts in view in a very short panel"); + let ignore = shown(&panel).params["ignoreWhite"].clone(); + scroll_settings(&mut panel, -1000.0); + panel.click("Ignore Color"); + assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "a very short panel still scrolls to the last setting"); + + panel.room(egui::vec2(240.0, 100.0)); + panel.frame(); + panel.room(egui::vec2(148.0, 68.0)); + panel.frame(); + panel.frame(); + let preview = panel.app().ui.image_trace_preview; + panel.click("Preview"); + assert_ne!(panel.app().ui.image_trace_preview, preview, "shrinking a second time starts at the actions"); +} + #[test] fn sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source() { let mut app = traced_app(); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 725305d6b3..f9910b0bf8 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -223,6 +223,13 @@ impl Panel { self.after(); } + /// Turns the wheel by `dy` points over `at`. + pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) { + self.frame_with(vec![Event::PointerMoved(at)]); + self.frame_with(vec![craft::ui::testing::pointer::wheel(dy)]); + self.after(); + } + /// Drags from the control named `from` to the one named `to`. pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) { let to = self.find(to).center(); From 98dc8b910363c64284addd6c9c581c5b3ac31f88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:11:59 -0800 Subject: [PATCH 09/23] Give each Magic Wand tolerance field an accessible name --- crates/ui-egui/src/panels/magic_wand.rs | 19 +++++++++++++++++-- crates/ui-egui/src/panels/tests_panel_rows.rs | 10 +++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/magic_wand.rs b/crates/ui-egui/src/panels/magic_wand.rs index 7a44811ed0..68a151d5fa 100644 --- a/crates/ui-egui/src/panels/magic_wand.rs +++ b/crates/ui-egui/src/panels/magic_wand.rs @@ -44,8 +44,10 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &'static str, fl app.run("magicWand.set", json!({ flag: now })).ok(); } if let Some((key, field)) = tol { - Field::new(tl!("Tolerance:")).id_salt(key).enabled(on).show(ui, |ui, _| { - if let Some(n) = field().enabled(on).show(ui).value().copied().flatten() { + let caption = tl!("Tolerance:"); + Field::new(caption).id_salt(key).enabled(on).show(ui, |ui, _| { + let name = format!("{caption} {label}"); + if let Some(n) = field().label(name).keeps_name(true).enabled(on).show(ui).value().copied().flatten() { app.run("magicWand.set", json!({ key: n })).ok(); } }); @@ -114,6 +116,19 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; + #[test] + fn each_tolerance_field_has_its_own_accessible_name() { + use craft::ui::contract::Role; + use craft::ui::testing::Fixture; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut fixture = Fixture::new(move |ui| show(&mut app, ui)); + fixture.settle(); + let names: Vec<_> = fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node)).collect(); + assert_eq!(names, ["Tolerance: Fill Color", "Tolerance: Stroke Color", "Tolerance: Stroke Weight", "Tolerance: Opacity"]); + assert_eq!(fixture.texts().iter().filter(|run| run.text == "Tolerance:").count(), 4); + } + #[test] fn color_tolerance_fields_go_to_100_in_a_cmyk_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index e249c1ea95..01ed51a6a6 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -74,7 +74,15 @@ fn the_document_info_rows_wrap_in_a_narrow_panel_in_german() { #[test] fn the_magic_wand_rows_wrap_in_a_narrow_panel_in_french() { - let past = past_a_narrow_panel("magicWand", "fr", &["Tolerance:"]); + use crate::i18n::{Lang, LangExt as _, tr}; + + let captions = ["Tolerance:"]; + let panel = floated(app_with_rect(), "magicWand", "fr", Place::Floating(PANEL_MIN_WIDTH), &captions); + let prefix = format!("{} ", tr(Lang::from_code("fr").unwrap(), "Tolerance:")); + let fields: Vec<_> = panel.nodes.iter().filter(|(name, _)| name.starts_with(&prefix)).cloned().collect(); + assert_eq!(fields.len(), 4, "{fields:?}"); + let mut past = panel.past_named(&captions); + past.extend(panel.past(fields)); assert!(past.is_empty(), "past the panel: {past:?}"); } From 4925b64fe5192ce4666a5d690e897f2d48360958 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:26:55 -0800 Subject: [PATCH 10/23] Flush native save directories on Unix --- crates/format/src/atomic.rs | 135 ++++++++++++++++++++++++++++++++---- crates/format/src/lib.rs | 2 + docs/mcp.md | 9 ++- docs/target-app-parity.md | 2 + 4 files changed, 131 insertions(+), 17 deletions(-) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..44a9f01369 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -472,6 +517,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..0c09df22d1 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; diff --git a/docs/mcp.md b/docs/mcp.md index a12daa1b46..09b7a62543 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores -`precision`. A save writes -a temporary file and renames it over the old one, so a failed save never damages the file; only the images the -document uses are written, and document keys written by a newer version are kept. +`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete +content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it. +A failure during that copy reports the locations of the new content and any saved original. +Only the images the document uses are written, and document keys written by a newer version are kept. +On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails, +the save reports an error stating that the file was written. An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d56d4fd4cd..3283f694f1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,5 +1,7 @@ # Parity with Adobe Illustrator +Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written. + > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). From e6d5e51f0efbe3a11bba7c434e66cd3b26fb1217 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:41:28 -0800 Subject: [PATCH 11/23] Require fresh export confirmation after changing documents --- .../ui-egui/src/dialogs/export_for_screens.rs | 13 +++++--- crates/ui-egui/src/dialogs/tests_screens.rs | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5e765e306c..0211830949 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -996,17 +996,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let key = app.session.active().map(|st| (st.uid, st.revision)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((stale, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; - if stale { + if shown != key { let (doc, thumbs) = document_view(app, ctx); dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { @@ -1031,7 +1031,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from); + // OK validated its selection against the document the dialog showed before refreshing. + let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) { + params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) + } else { + Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) + }; dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { d.held.answer(answer); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 8a73810d89..af68809f46 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -67,6 +67,36 @@ fn stays_open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, log) = app(1, true); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + open(&mut app); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + export_for_screens::pump(&mut app, &ctx); + + assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Destination.png"]); +} + fn temp_folder(tag: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id())) } From 735bdc09184520d947c4ca2722b37102abd7657b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:53:14 -0800 Subject: [PATCH 12/23] Preserve custom arrowhead attachment in Stroke previews --- crates/ui-egui/src/panels/stroke.rs | 32 ++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index e47111a613..d7406230d7 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -136,7 +136,7 @@ pub(crate) fn builtin_arrow_name(label: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label) } -/// The preview cache key of `a`: its name, and for a custom head its art. +/// The preview cache key of `a`: its name, and for a custom head its art and where the stroke ends. fn arrow_key(a: Option<&Arrowhead>) -> String { match a { Some(Arrowhead::Custom(c)) => { @@ -148,6 +148,7 @@ fn arrow_key(a: Option<&Arrowhead>) -> String { (p.x.to_bits(), p.y.to_bits()).hash(&mut h); } } + c.stop().to_bits().hash(&mut h); format!("custom:{}:{:x}", c.name, h.finish()) } _ => format!("{a:?}"), @@ -487,8 +488,13 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - let weight = fit(w - 6.0, long).min(fit(h / 2.0 - 1.0, half)).min(2.5); inset = -b.x0.min(0.0) * weight; if weight < LEAST { - let path = c.path.transformed(vectorcraft_geom::Affine::scale(weight / LEAST)); - a = Some(Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path)))); + let shrink = weight / LEAST; + let path = c.path.transformed(vectorcraft_geom::Affine::scale(shrink)); + let mut head = vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path); + if let Some(stop) = c.stop { + head = head.with_stop(stop * shrink); + } + a = Some(Arrowhead::Custom(std::sync::Arc::new(head))); } scale = scale.min(weight.max(LEAST) / WIDTH * 100.0); } @@ -735,6 +741,26 @@ mod tests { assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); } + #[test] + fn custom_arrowhead_thumbnails_preserve_where_the_stroke_ends() { + use vectorcraft_doc::CustomArrowhead; + use vectorcraft_geom::{PathData, Point, SubPath}; + + let outline = PathData::single(SubPath::polyline(&[Point::new(0.0, -60.0), Point::new(4.0, 60.0), Point::new(4.0, -60.0)], true)); + let custom = CustomArrowhead::new("Wide Flag".into(), outline); + let halfway = Arrowhead::Custom(std::sync::Arc::new(custom.clone())); + let explicit_stop = Arrowhead::Custom(std::sync::Arc::new(custom.with_stop(0.75))); + assert_ne!(arrow_key(Some(&halfway)), arrow_key(Some(&explicit_stop)), "each stroke attachment needs its own thumbnail"); + + let preview = arrow_doc(Some(explicit_stop), true, 56.0, 22.0).unwrap(); + let node = preview.node(preview.selectable_art()[0]).unwrap(); + let Some(Arrowhead::Custom(head)) = &node.appearance.stroke().unwrap().start_arrow else { + panic!("the preview should draw the custom arrowhead"); + }; + // The preview has 10 points above the line. At the minimum weight, 60 units would need 15. + assert_eq!(head.stop, Some(0.5)); + } + #[test] fn while_typing_the_panel_strokes_the_selected_characters() { use vectorcraft_doc::{LineJoin, NodeKind}; From 3e596a792756db5a6dbea27923cf495c00cf41da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:53:44 -0800 Subject: [PATCH 13/23] Keep Links row menus with their source document --- crates/ui-egui/src/panels/links.rs | 18 ++++++++---- crates/ui-egui/src/panels/tests_links.rs | 35 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 72c90a8efc..87b574f820 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -96,7 +96,8 @@ pub(crate) struct LinksModel { pub(super) show: Option<(u64, u64)>, nested: NestedPicks, selection: Selection, - menu: Option, + /// The document uid and row ID whose context menu is open. + menu: Option<(u64, u64)>, } /// `links.list` and the first selected image's `links.info`, with what they were fetched for. @@ -710,13 +711,16 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option) { /// The Links panel: the images as a list with a footer of link actions and the Link Info section. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { drop_stale_picks(app); + let uid = app.session.active().map(|st| st.uid); + if app.ui.links.menu.is_some_and(|(document, _)| Some(document) != uid) { + app.ui.links.menu = None; + } let Some(mut cache) = cached(app, ui.ctx()) else { Panel::new(tl!("Links")).show(ui, |ui, _| { Text::new(tl!("No document")).shade(Shade::Muted).show(ui); }); return; }; - let uid = app.session.active().map(|st| st.uid); let reveal = app.ui.links.show.take().filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); // A Show filter that leaves the requested row out goes back to Show All. @@ -730,7 +734,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let selected = selected_links(app); let mut selection = std::mem::take(&mut app.ui.links.selection); selection.items = selected.clone(); - let open_menu = app.ui.links.menu; + let open_menu = app.ui.links.menu.map(|(_, row)| row); let units = app.session.general_unit(); let view: &VectorcraftApp = app; @@ -808,8 +812,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let items = app.ui.links.selection.items.clone(); apply_selection(app, rows_of(&cache), items); } - if menu_for.is_some() { - app.ui.links.menu = menu_for; + if let Some(row) = menu_for { + app.ui.links.menu = uid.map(|document| (document, row)); } if let Some(id) = activated { go_to(app, id); @@ -828,7 +832,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let Some((a, id)) = row_act { app.ui.links.menu = None; - act(app, a, Some(id)); + if app.session.active().map(|st| st.uid) == uid { + act(app, a, Some(id)); + } } } diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 7c07781d02..6f9a6c5046 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -663,6 +663,41 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } +#[test] +fn switching_documents_dismisses_a_links_row_menu() { + let dir = Folder::new("context-switched-document"); + let (mut app, first, _) = app(&dir); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let path = dir.file("other.png", &png(40, 20)); + let second = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents have different images at the same local ID"); + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, super::links::show); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + panel.secondary_click("linked.png"); + assert!(panel.menu_item_enabled("Embed Image")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Embed Image"), "the other document must not inherit the row menu"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["linked"], true); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Embed Image"), "switching back must not revive the menu"); + assert_eq!(panel.app().run("links.info", json!({"id": first})).unwrap()["linked"], true); + + activate(&mut panel, 1, destination); + panel.secondary_click("other.png"); + panel.click_menu_item("Embed Image"); + assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["status"], "embedded"); +} + #[test] fn right_click_context_menu_in_links_panel() { let dir = Folder::new("context-menu"); From fc47ab939d928aaf24402a379260fa69a07b7331 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:54:23 -0800 Subject: [PATCH 14/23] Keep Define Grid changes on their source document --- .../ui-egui/src/dialogs/perspective_grid.rs | 24 +++++++++++--- .../ui-egui/src/dialogs/tests_perspective.rs | 33 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index bed5ab085b..d75a811a74 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, + app.session.active().map(|st| st.uid), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, + /// The document whose grid Define Grid edits. + source_document: Option, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -190,10 +193,18 @@ pub(super) struct GridDialog { } impl GridDialog { - fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String) -> Self { + fn new( + def: GridDefinition, + mode: GridMode, + source_document: Option, + (ppi, bare_points): (f64, bool), + presets: Vec, + new_name: String, + ) -> Self { let mut dialog = GridDialog { id: dialog_id(KIND), mode, + source_document, draft: GridDraft { def }, presets: Vec::new(), rows: Vec::new(), @@ -516,9 +527,12 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { + if app.session.active().map(|st| st.uid) != source_document { + return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } @@ -546,10 +560,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let filed = dialogs.with(|host| { let dialog = host.get_mut::()?; dialog.set_presets(presets, new_name); - dialog.held.take().map(|def| (dialog.mode.clone(), def)) + dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def)) }); - let Some((mode, def)) = filed else { return }; - let next = file(app, &mode, &def); + let Some((mode, source_document, def)) = filed else { return }; + let next = file(app, &mode, source_document, &def); if let Err(why) = &next { app.status(why.clone()); } diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 90af85ee0c..089296ae7a 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -104,6 +104,39 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() { assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle())); } +#[test] +fn define_grid_applies_only_to_the_document_where_it_opened() { + let mut app = app(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let destination = app.session.active().unwrap(); + let destination_uid = destination.uid; + let destination_undo = destination.history.undo.len(); + let destination_grid = grid(&app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let source_uid = app.session.active().unwrap().uid; + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#112233")).unwrap(); + let ctx = window(&app); + let id = dialog_id(super::perspective_grid::KIND); + host(&app, |h| { + assert!(!h.confirm_by_id(&ctx, id)); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + super::perspective_grid::pump(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().uid, destination_uid); + assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source_uid); + ok(&mut app); + assert_eq!(kind(&app), None); + assert_eq!(grid(&app).right_color.hex(), "#112233"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); From 8901f9ac4e3683bbe8e79ba3ef3e4dff881446a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:58:23 -0800 Subject: [PATCH 15/23] Keep Artboard Options attached to their original target --- .../ui-egui/src/dialogs/artboard_options.rs | 117 +++++++++++++++--- 1 file changed, 100 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..cb1c6337e5 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -137,8 +137,7 @@ impl ArtboardOptionsValue { } } -/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's -/// document, presets and preferences cannot change while it is open. +/// What the dialog shows but does not edit, read from the app when it opens. struct Setup { /// The lengths the fields keep and show. lengths: LengthUnits, @@ -152,9 +151,17 @@ struct Setup { fit_bounds: [Option; 2], } +#[derive(Clone, Copy)] +struct Target { + document: u64, + /// The current artboard's ID, or no ID while creating a new artboard. + artboard: Option, +} + /// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests. pub struct ArtboardOptionsDialog { id: DialogId, + target: Target, value: ArtboardOptionsValue, setup: Setup, held: HeldAnswer, @@ -162,8 +169,8 @@ pub struct ArtboardOptionsDialog { } impl ArtboardOptionsDialog { - fn new(value: ArtboardOptionsValue, setup: Setup) -> Self { - ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } + fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self { + ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } } } @@ -546,13 +553,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { /// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog /// shows read from the app. -fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result { +fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; + let st = app.session.active().ok_or("no document")?; + let target = Target { document: st.uid, artboard }; + let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); let fills = fill_colors(app); value.seed_customs(&fills); - let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc)); let setup = Setup { lengths: crate::canvas::rulers::general_lengths(app), origin: app.ruler_origin(), @@ -560,7 +569,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result< fills, fit_bounds: [artwork, app.selection_bounds()], }; - host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup))); + host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup))); Ok(json!({ "dialog": KIND })) } @@ -569,6 +578,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let index = active_index(app); let st = app.session.active().ok_or("no document")?; let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let artboard = a.id; let r = a.rect; let value = ArtboardOptionsValue { index, @@ -585,7 +595,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { pixel_aspect: a.video_ruler_pixel_aspect_ratio, ..Default::default() }; - present(app, value) + present(app, value, Some(artboard)) } /// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new @@ -605,7 +615,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { pixel_aspect: 1.0, ..Default::default() }; - present(app, value) + present(app, value, None) } /// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it @@ -613,12 +623,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { /// point picked in the dialog. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; - let Some((held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.held.take(), d.value.reference))) else { return }; + let Some((target, held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.target, d.held.take(), d.value.reference))) + else { + return; + }; if app.ui.transform_panel.reference_point != reference { app.ui.transform_panel.reference_point = reference; } if let Some(value) = held { - let answer = confirm(app, &value).map(drop).map_err(Label::from); + let answer = confirm(app, target, &value).map(drop).map_err(Label::from); host.with(|h| { if let Some(d) = h.get_mut::() { d.held.answer(answer); @@ -633,21 +646,28 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// used (its column and row), all in one undo step. Fitting applies only to this artboard and never /// moves its artwork. The Global checkboxes' preferences are set only after the artboard command /// succeeds, so an error leaves them as they were. -fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result { +fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result { + let st = app + .session + .active() + .filter(|st| st.uid == target.document) + .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; set_globals(app, globals)?; return Ok(r); } - let p = v.params(); - let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect); - let changed = |k: &str, old: Option| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6)); - let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let (index, board) = + st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?; + let mut p = v.params(); + p["index"] = json!(index); + let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6); + let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height())); let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2); let mut entries = vec![]; if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) { - for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { let (w, h) = if let Some(choice) = v.size_choice { let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue }; @@ -753,6 +773,69 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn confirmation_follows_the_original_artboard_after_reorder() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + let original = app.session.active().unwrap().doc.artboards[0].id; + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original); + let undo = undo_len(&app); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed")); + assert_eq!(undo_len(&app), undo + 1); + } + + #[test] + fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() { + for create in [false, true] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + if create { + open_new(&mut app).unwrap(); + } else { + open(&mut app).unwrap(); + } + set(&app, &[("name", json!("Source"))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1")); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!(artboards.len(), if create { 2 } else { 1 }); + assert_eq!(artboards.last().unwrap().name, "Source"); + } + } + + #[test] + fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2"); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + } + /// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document. #[test] fn position_moves_art_only_with_the_tool_option_on() { From f4184d5c5117d891daaaadb6067d86eb7e1ff48b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:04:03 -0800 Subject: [PATCH 16/23] Keep Text Styles row menus with their source document --- crates/ui-egui/src/panels/text_styles.rs | 8 +++- .../ui-egui/src/panels/text_styles/tests.rs | 48 +++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index dbd7447b34..bfcffa6e65 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -66,6 +66,8 @@ impl StylesPanels { pub(crate) struct StylesPanel { /// The uid of the document the highlight was made in. document: Option, + /// Changes when the panel switches documents, so reopening a document cannot restore its old popup. + scope_generation: u64, /// The highlighted styles, in the order they were picked. highlight: Vec, /// The selection's lead style. @@ -83,7 +85,7 @@ fn highlighted(app: &mut VectorcraftApp, kind: Kind, listed: &[&str]) -> Vec = listed.iter().enumerate().map(|(i, name)| TextStyleRow::new(i as u64, super::label_or_name(name, i == 0))).collect(); @@ -271,7 +274,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if let Some(id) = reveal.as_deref().and_then(id_of) { list = list.reveal(id); } - let out = list.show(ui); + // The framework's row menu and footer drag use list indices that are local to this document. + let out = ui.push_id(("text-styles-document", kind.panel_kind(), scope), |ui| list.show(ui)).inner; let name_of = |id: &u64| listed.get(*id as usize).map(|n| n.to_string()); let panel = app.ui.text_styles.of(kind); panel.highlight = sel.items.iter().filter_map(name_of).collect(); diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index 3e80710437..5144f8ce9a 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -4,6 +4,54 @@ use crate::tests::picks::{answer_dialog, cancel_dialog, open_dialogs, poll, scri use crate::tests::synthetic::key_frame; use vectorcraft_doc::{NodeId, NodeKind}; +#[test] +fn switching_documents_dismisses_text_styles_row_menus() { + use crate::tests::panel_harness::Panel; + use vectorcraft_engine::Session; + + for kind in [Kind::Char, Kind::Para] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let command = format!("{}.new", kind.prefix()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "First Style"})).unwrap(); + let first = style_id(&mut app, kind, "First Style"); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run(&command, json!({"name": "Second Style"})).unwrap(); + let second = style_id(&mut app, kind, "Second Style"); + let destination = app.session.active().unwrap().uid; + assert_eq!(first, second, "the two documents carry styles at the same list index"); + app.run("window.previousDocument", json!({})).unwrap(); + + let draw: fn(&mut VectorcraftApp, &mut Ui) = match kind { + Kind::Char => |app, ui| show(app, ui, Kind::Char), + Kind::Para => |app, ui| show(app, ui, Kind::Para), + }; + let mut panel = Panel::new(app, draw); + let activate = |panel: &mut Panel, index, document| { + panel.app().session.execute("document.activate", &json!({"index": index})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().uid, document); + }; + let has_copy = |panel: &Panel, name: &str| styles(&mut panel.app(), kind).iter().any(|style| style.0 == name); + panel.secondary_click("First Style"); + assert!(panel.menu_item_enabled("Duplicate Style")); + activate(&mut panel, 1, destination); + assert!(!panel.shows("Duplicate Style"), "the new document does not inherit the row menu"); + assert!(!has_copy(&panel, "Second Style copy")); + + activate(&mut panel, 0, source); + assert!(!panel.shows("Duplicate Style"), "the old row menu does not reappear"); + assert!(!has_copy(&panel, "First Style copy")); + + activate(&mut panel, 1, destination); + panel.secondary_click("Second Style"); + panel.click_menu_item("Duplicate Style"); + assert!(has_copy(&panel, "Second Style copy")); + } +} + // PLAN: assumed type-w19 items reachable through `super::*`: `run_action(app, kind, action)`, // `StylesPanel { highlight: Vec, .. }` and `StylesPanels { char, para, made }` at // `app.ui.text_styles`, `highlighted(app, kind, listed: &[&str]) -> Vec`, `TextStyleAction`, and a From e5c631732427c8cb1d70734e05ae213085eb4dc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:14:24 -0800 Subject: [PATCH 17/23] Keep Rename Artboards on its original selection --- .../ui-egui/src/dialogs/rename_artboards.rs | 69 ++++++++++++++++--- 1 file changed, 61 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index d6b74551f5..6eb9001c3b 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -19,14 +19,15 @@ pub(crate) const CMD: &str = "artboard.rename"; /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - (indices, name.to_owned()) - }); + let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; + let document = st.uid; + let selected: Vec<_> = + crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); + let name = match selected.as_slice() { + [one] => one.name.clone(), + _ => String::new(), + }; + let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { @@ -39,6 +40,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if name.trim().is_empty() { return Ok(()); } + let st = + app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + let indices = artboards + .iter() + .map(|id| st.doc.artboards.iter().position(|board| board.id == *id)) + .collect::>>() + .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { app.status(e); } @@ -105,6 +113,51 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } + #[test] + fn rename_follows_the_original_artboards_after_reordering() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap(); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + } + + #[test] + fn rename_waits_for_the_document_it_opened_in() { + let mut app = app(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open(), "the original document can still answer"); + + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]); + assert!(!app.any_dialog_open()); + } + + #[test] + fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.delete", json!({"index": 2})).unwrap(); + app.run("artboard.duplicate", json!({"index": 1})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open()); + } + /// OK with an empty name or the name the artboard already has records no undo step. #[test] fn nothing_changes_for_an_empty_or_unchanged_name() { From 492e0c72d76437bd62b15deaf616166af07a10c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:06:04 -0800 Subject: [PATCH 18/23] Keep File Info confirmation with its document --- crates/ui-egui/src/dialogs/file_info.rs | 72 ++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index e43435b5ae..fffa334f21 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -55,8 +55,14 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ()); - crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; + let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| { + if !app.session.active().is_some_and(|active| active.uid == *document) { + return Err(tl!("File Info can only change the document it was opened for.").to_owned()); + } + app.run("file.info", Value::Object(fields.clone())).map(|_| ()) + }; + crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?; Ok(Value::Null) } @@ -215,6 +221,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, + document: u64, open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -230,9 +237,10 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(value: Info) -> Self { + fn new(document: u64, value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), + document, open: true, hold: false, value, @@ -371,15 +379,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = Info; + type Answer = (u64, Info); fn held_ok(mut self) -> Self { self.hold = true; self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|fields| (self.document, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -674,6 +682,58 @@ mod tests { assert!(with_dialog(&app, |_| ()).is_some()); } + #[test] + fn a_file_info_confirmation_stays_with_its_document() { + let mut app = windowed(); + for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": title, "author": author})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Source")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application"); + + activate(&mut app, 1); + let before = app.session.active().unwrap(); + let document = before.doc.clone(); + let b_undo = before.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched"); + assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched"); + assert_eq!(after.history.undo.len(), b_undo); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft"); + let source = app.session.active().unwrap(); + assert_eq!(source.doc.info_title(), "Revised Source"); + assert_eq!(source.doc.metadata.author, "Ada"); + assert_eq!(source.doc.metadata.keywords, ["print"]); + assert_eq!(source.history.undo.len(), a_undo + 1); + } + + #[test] + fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() { + let mut app = windowed(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Destination")).unwrap(); + assert!(press_ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().history.undo.is_empty()); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); From 84480460687248db4c5845b43c3c89aa4f3694f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:16:41 -0800 Subject: [PATCH 19/23] Keep Flattener Preview settings within narrow panels --- .../ui-egui/src/panels/flattener_preview.rs | 107 +++++++++++++++--- 1 file changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index e2c724fe2f..c55c06b1c3 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -13,9 +13,9 @@ use std::sync::Arc; use craft::behavior::CanvasTransform; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Divider, Shade, Text}; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom}; use craft::ui::pickers::Select; @@ -200,30 +200,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } // The highlighted art takes the theme's error colour. let highlight = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.solid); + let compact = ui.available_width() < Env::of(ui).tokens.size.plot.width; let mut set = app.ui.flattener_preview.clone(); let mut refresh_now = false; - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { refresh_now = Button::new(tl!("Refresh")).tooltip(tl!("Preview the document as it is now")).show(ui).clicked(); let entries = Highlight::ALL.map(|h| Entry::new(h, h.label())); - Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries).show(ui); + let picker = Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + Row::new().fill_width().wrap(true).show(ui, |ui, _| { Text::new(tl!("Overprints:")).shade(Shade::Muted).show(ui); let entries = Overprints::ALL.map(|o| Entry::new(o, o.label())); - Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries).show(ui); + let picker = Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries); + let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker }; + picker.show(ui); }); - Row::new().show(ui, |ui, _| { + let preset_id = ui.scope_id().with("flattener-preset-row"); + let mut preset = |ui: &mut Ui| { Text::new(tl!("Preset:")).shade(Shade::Muted).show(ui); let names = flatten::preset_names(app); - let mut fields = DialogFields::from_pairs([("preset", set.preset.clone())]); - flatten::preset_picker(ui, &mut fields, "preset", &names, custom(app)); - if let Some(name) = fields.text("preset") - && name != set.preset + let is_custom = custom(app); + let current = if is_custom { String::new() } else { set.preset.clone() }; + let mut fields = DialogFields::from_pairs([("preset", current.clone())]); + flatten::preset_picker(ui, &mut fields, "preset", &names, is_custom); + if !ui.is_sizing_pass() + && let Some(name) = fields.text("preset").filter(|name| *name != current) && let Some(p) = app.session.flattener_preset(name) { (set.preset, set.options) = (p.name, p.options); } - }); + }; + if compact { + Stack::new().id(preset_id).fill_width().show(ui, |ui, _| preset(ui)); + } else { + Row::new().id(preset_id).fill_width().wrap(true).show(ui, |ui, _| preset(ui)); + } if set.show_options { Divider::horizontal().show(ui); let params = flatten::option_params(&[], ""); @@ -285,11 +298,16 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, // At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit. let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height()); let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32); - let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) + let pane = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) .aspect(ASPECT) .click_centres(false) - .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")) - .show(ui); + .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")); + let out = if w < Env::of(ui).tokens.size.plot.width { + let (_, room) = ui.allocate_space(vec2(w, w / ASPECT)); + pane.show_at(ui, room) + } else { + pane.show(ui) + }; *view = match out.clicked { Some(at) => { let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 }; @@ -484,6 +502,65 @@ mod tests { assert_eq!(back.flattener_preview, app.ui.flattener_preview); } + #[test] + fn the_flattener_selectors_and_preview_fit_a_narrow_dock() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + let width = 100.0; + panel.room(vec2(width, 520.0)).frame(); + panel.frame(); + for name in ["Highlight", "Overprints", "Preset:"] { + let rect = panel.rect_role(name, Role::COMBO_BOX); + assert!(rect.left() >= 0.0 && rect.right() <= width, "{name} overflows the dock at {rect:?}"); + } + let pane = panel.rect("Flattener Preview"); + assert!(pane.left() >= 0.0 && pane.right() <= width, "preview overflows the dock at {pane:?}"); + } + + #[test] + fn the_flattener_selectors_keep_their_caption_rows_when_the_panel_is_wide() { + use craft::ui::contract::Role; + + let mut panel = crate::tests::panel_harness::Panel::new(app(), show); + panel.room(vec2(440.0, 600.0)).frame(); + panel.frame(); + for (caption, role, picker) in + [("Refresh", Role::BUTTON, "Highlight"), ("Overprints:", Role::LABEL, "Overprints"), ("Preset:", Role::LABEL, "Preset:")] + { + let row = panel.rect_role(caption, role); + let field = panel.rect_role(picker, Role::COMBO_BOX); + assert!(field.left() >= row.right() && field.center().y >= row.top() && field.center().y <= row.bottom(), "{picker} is below {caption}"); + } + } + + #[test] + fn the_compact_flattener_applies_a_preset_and_refreshes_the_snapshot() { + use craft::ui::contract::Role; + + let mut app = app(); + command(&mut app, &json!({"preset": "high", "options": {"balance": 12}})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.room(vec2(100.0, 520.0)).frame(); + panel.frame(); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.app().ui.flattener_preview.options.balance, 12.0); + panel.click_role("Preset:", Role::COMBO_BOX); + panel.click("High Resolution"); + let expected = FlattenOptions::preset("high").unwrap(); + assert_eq!(panel.app().ui.flattener_preview.options, expected); + panel.app().run("select.all", json!({})).unwrap(); + panel.app().run("transparency.set", json!({"opacity": 100})).unwrap(); + assert!(stale(&panel.app()), "the live document changed"); + panel.click("Refresh"); + assert!(!stale(&panel.app()), "Refresh takes a new snapshot"); + let well = panel.rect("Flattener Preview"); + panel.click_at(well.center()); + assert!(!panel.app().flattener_preview.view.fit, "the compact preview still zooms"); + } + /// The panel in a fixture, and the preview pane's bounds. fn shown_pane() -> (std::rc::Rc>, craft::ui::testing::Fixture, egui::Rect) { let app = std::rc::Rc::new(std::cell::RefCell::new(app())); From bd619b9222b6b52b463e529497f651bab3124229 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:22:48 -0800 Subject: [PATCH 20/23] Bind Document Setup actions to their source document --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs/document_setup.rs | 63 ++++++++++++++++++-- crates/ui-egui/src/lib.rs | 2 + 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 14329e8f0f..6ed9a2d818 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -234,6 +234,7 @@ impl VectorcraftApp { told: Default::default(), missing_font_edit_token: None, held: Default::default(), + document_setup_source: None, edit_scopes: Default::default(), command_dialog: Default::default(), effect_dialogs: Default::default(), diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index de5cac3c02..c3aa0ef099 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values) }); super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?; + app.document_setup_source = Some(source); Ok(Value::Null) } @@ -185,6 +186,9 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { + if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); let color = color_commands(app, &map)?; @@ -220,9 +224,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); - let edit = dialogs.with(|host| { - host.get_by_id::(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone()) - }); + let Some(edit) = dialogs.with(|host| { + host.get_by_id::(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone())) + }) else { + app.document_setup_source = None; + return; + }; if let Some(fields) = edit { match confirm(app, &fields) { Ok(_) => { @@ -645,6 +652,54 @@ mod tests { app.session.active().unwrap().history.undo.len() } + fn check_source_document(edit_artboards: bool) { + let (mut app, ctx) = new_app(); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + set(&app, &ctx, "colorMode", json!("cmyk")); + + let apply = |app: &mut VectorcraftApp| { + if edit_artboards { + set(app, &ctx, "editArtboards", json!(true)); + super::pump(app, &ctx); + !is_open(app) + } else { + press_ok(app, &ctx) + } + }; + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_steps(&app); + let accepted = apply(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, destination); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings"); + assert_eq!(undo_steps(&app), undo); + assert_eq!(app.session.tool_id(), "selection"); + assert!(!accepted && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(apply(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, source); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1)); + assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" }); + assert!(!is_open(&app)); + } + + #[test] + fn source_document_is_required_to_confirm_document_setup() { + check_source_document(false); + } + + #[test] + fn source_document_is_required_to_edit_artboards_from_document_setup() { + check_source_document(true); + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6078ca0c07..412377ce61 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -270,6 +270,8 @@ pub struct VectorcraftApp { pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, + /// The document whose settings the open Document Setup dialog edits. + pub(crate) document_setup_source: Option, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one /// step however many values it sets. pub(crate) edit_scopes: HashMap, From 4f8a7d22d9b5d93b838e9c5c5f2b12e27d62f5c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:29:16 -0800 Subject: [PATCH 21/23] Keep Layer Options changes in their source document --- crates/ui-egui/src/dialogs/layer_options.rs | 62 +++++++++++++++++++-- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 3ed57d9471..944051cf7d 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); Ok(Value::Null) } @@ -410,6 +411,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { /// the dialog open with the reason under its rows. pub(crate) struct LayerOptionsDialog { id: DialogId, + document: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -421,8 +423,8 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } } /// The OK filed by the user, once. @@ -571,7 +573,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let Some((document, value)) = dialogs.with(|host| { + let dialog = host.get_mut::()?; + Some((dialog.document, dialog.take_filed()?)) + }) else { + return; + }; let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), @@ -579,8 +586,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => None, }; // Isolation mode can start while the dialog is open. - let answer = match sublayer { - Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + let answer = match app.session.active().filter(|st| st.uid == document) { + None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } _ => { @@ -681,6 +689,48 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + #[test] + fn layer_options_and_new_layers_follow_their_document() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let mut app = app(); + let source_id = app.session.active().unwrap().doc.layers[0].id; + app.run("file.new", json!({"width": 160, "height": 160})).unwrap(); + let destination_id = app.session.active().unwrap().doc.layers[0].id; + assert_eq!(destination_id, source_id, "the two documents reuse a layer ID"); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + app.run(command, arguments).unwrap(); + set(&mut app, "name", json!("Source Draft")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = open_id(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + + let layers = |app: &VectorcraftApp| { + let mut names = vec![]; + app.session.active().unwrap().doc.walk(|node| { + if node.is_layer() { + names.push(node.display_name()); + } + }); + names + }; + activate(&mut app, 1); + let before = layers(&app); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert!(layers(&app).iter().any(|name| name == "Source Draft")); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } + /// Two layers with different options, the first plain and the second green, locked, in /// outline view and dimmed to 30%. fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) { From 1573e976e0677905663fc8f29bc715754d8edcd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:40:13 -0800 Subject: [PATCH 22/23] Keep saved Selection and View edits with their document --- crates/ui-egui/src/dialogs/saved_names.rs | 79 +++++++++++++++++++++-- 1 file changed, 72 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index d14a41fb74..0bbf1e89ea 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -137,6 +137,7 @@ impl ItemSource for Shown<'_> {} /// The saved-names dialog of one kind. pub(crate) struct SavedNamesDialog { id: DialogId, + document: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -147,10 +148,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(names: SavedNames, list: Vec) -> Self { + fn new(document: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -326,8 +327,9 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); Ok(()) } @@ -335,18 +337,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec)> = dialogs.with(|host| { + let filed: Vec<_> = dialogs.with(|host| { host.open_dialogs() .into_iter() .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.names.command, edits)) }) .collect() }); - for (id, command, edits) in filed { - let outcome = app.run(command, json!({ "edits": edits })); + for (id, document, command, edits) in filed { + let outcome = if app.session.active().is_some_and(|active| active.uid == document) { + app.run(command, json!({ "edits": edits })) + } else { + Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + }; if let Err(reason) = &outcome { app.status(reason.clone()); } @@ -357,3 +363,62 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_names_edits_stay_with_their_document() { + for is_view in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + for size in [100, 200] { + app.run("file.new", json!({"width": size, "height": size})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + } + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let kind = if is_view { + crate::dialogs::edit_views::open(&mut app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(&mut app).unwrap(); + crate::dialogs::edit_selection::KIND + }; + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + h.confirm_by_id(&ctx, id); + }); + + activate(&mut app, 1); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + host.with(|h| h.confirm_by_id(&ctx, id)); + pump(&mut app, &ctx); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } +} From b458d505953a951799a4f509d518e4532e26a1e9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 05:52:11 +0700 Subject: [PATCH 23/23] Properties: the stroke-profile check asks tool_paints, which replaced bucket_paints --- crates/ui-egui/src/panels/properties/appearance_section.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..b3266b032d 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -100,9 +100,9 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// Whether a stroke that `stroke.set` edits has a width profile /// ([`vectorcraft_engine::Session::edited_strokes_profiled`]), cached per document revision and /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or -/// the Live Paint Bucket is active, when the list edits the stroke the panel shows. +/// a tool paints the stroke ([`vectorcraft_engine::Session::tool_paints`]), when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false };