From 1eff539ff6082cd0775b426441730f5265adae2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:18:55 -0800 Subject: [PATCH 01/42] Redraw the first Pen drag frame and keep partial raster edits consistent --- crates/render/src/fx/renderer.rs | 3 + crates/render/src/fx/tests.rs | 25 ++++++ crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/caches.rs | 9 ++- crates/ui-egui/src/canvas/raster.rs | 50 +++++++----- crates/ui-egui/src/canvas/tests.rs | 116 ++++++++++++++++++++++++---- 6 files changed, 165 insertions(+), 40 deletions(-) diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 8021e701de..cafc8ec35b 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -134,6 +134,9 @@ impl Renderer { // During a drag, a larger shadow on a multithreaded context is filtered within the // drag's budget (`with_filters`), and no raster is kept. if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET { + // The fallback can differ from a still raster (a glow blurs soft alpha here). + // A patch over a still frame cannot splice these pictures together. + self.stats.view_sized += 1; return None; } let (w, h) = (w as u16, h as u16); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 1832f18580..1090c937ad 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1581,6 +1581,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +#[test] +fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { + let doc = doc_with( + Rect::new(20.0, 20.0, 40.0, 40.0), + Color::BLACK, + vec![ + ("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})), + ("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})), + ], + ); + let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0)); + let mut still = Renderer::new(); + still.threads = 2; + let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels; + assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters"); + + let mut drag = Renderer::new(); + drag.threads = 2; + let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() }; + let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels; + assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling"); + assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter"); + assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame"); +} + /// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20 /// square around the origin draws its drop shadow from the raster of an earlier frame. The /// shadow is made from the instance's art, which the renderer measures the group's content by. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index ffe4d54ecd..d2698033dc 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -120,7 +120,7 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, - worker_parts: false, + whole_frames: false, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 08b15cddc5..1be3cbe933 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,10 +25,11 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, - /// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn - /// again on this thread would not have matched the frame around it: until the worker's next - /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). - pub worker_parts: bool, + /// The frame shown drew art in a way that depends on its size, or a part of it drawn again on + /// this thread would not have matched the frame around it: until the next whole frame is shown, + /// edits of the frame shown render whole, on the worker when the frame is heavy + /// ([`canvas::show`]). + pub whole_frames: bool, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 780dd5f7a8..a12d184cd0 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -55,12 +55,15 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) /// shows in the frame it is made in, when the part's share of the frame's last whole render time /// is at most 8 ms, and except when that frame drew raster effects from rasters made before their -/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame -/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn -/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): -/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What -/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to -/// draw the part again. +/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects, +/// and this thread's doesn't. No frame that drew art in a way that depends on its size, or that a +/// part drawn again here since it was shown would have differed from, is drawn again in part +/// ([`crate::CanvasCache::whole_frames`]). A frame that drew nothing from moved rasters or at a +/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction +/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change. +/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what +/// it measures (a 3D effect's art) to draw the part again. pub(super) fn changed_pixels( app: &mut VectorcraftApp, key: &CacheKey, @@ -70,14 +73,20 @@ pub(super) fn changed_pixels( w: u32, h: u32, ) -> Option> { - let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?; + let shown_key = app.canvas.key.as_ref()?; + // The worker keeps its still rasters while the UI thread draws the first edit. Rendering only + // part of a UI-thread frame could evict its own still rasters before a drag needs them. + let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting; + let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| { + o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts + })?; // A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds. if opts.mask_view.is_some() { return None; } - let shown_key = app.canvas.key.as_ref()?; - let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() }; - let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some()); + let (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) }; + let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() }; + let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.reused.is_some()); // A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]). let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision); if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way { @@ -92,11 +101,12 @@ pub(super) fn changed_pixels( vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), - Some([x0, y0, x1, y1]) => { + Some([x0, y0, x1, y1]) if !app.canvas.whole_frames => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } + Some(_) => None, }, vectorcraft_render::Changed::Everything => None, } @@ -597,7 +607,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.reused = done.reused.then(|| frame::clock(ctx)); app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; - app.canvas.worker_parts = done.view_sized; + app.canvas.whole_frames = done.view_sized; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -686,11 +696,12 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// key: only the document changed since the frame shown, in that part of it /// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. /// -/// Over a frame the worker rendered, a part that drew raster effects from rasters made before -/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), -/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), -/// would not match the frame around it: it is not drawn, false is returned, and the edits after it -/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +/// A part that drew art in a way that depends on the frame's size +/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution +/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a +/// worker frame, could differ from the frame around it. It is not drawn, false is returned, +/// and the edits after it render whole until the next whole frame is +/// shown ([`crate::CanvasCache::whole_frames`]). fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool { let Frame { key, doc, effects, view, opts, pixel, .. } = frame; let t0 = monotonic_ms(); @@ -703,8 +714,8 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); - if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { - app.canvas.worker_parts = true; + if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 { + app.canvas.whole_frames = true; return false; } let width = part.width; @@ -824,6 +835,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = monotonic_ms() - t0; app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; + app.canvas.whole_frames = app.canvas.renderer.stats.view_sized > 0; app.canvas.from_worker = false; app.canvas.reused = None; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..75aefe02cc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -752,6 +752,72 @@ fn an_edit_renders_only_its_part_of_the_canvas() { assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it"); } +/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas +/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too, +/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew, +/// and an inner glow that fits the view but not the part the edit changed. +#[test] +fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() { + keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size); +} + +fn an_edit_over_art_drawn_for_the_frames_size() { + for cropped in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread, however long it takes + app.canvas.renderer.threads = 2; + let (rect, effect) = if cropped { + (json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}})) + } else { + (json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}})) + }; + let art = app.run("shape.rectangle", rect).unwrap()["id"].clone(); + let mut effect = effect; + effect["ids"] = json!([art]); + app.run("effect.apply", effect).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone(); + let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + // A new view: the next frame renders whole. + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) }; + } + // Where the canvas texture changed in a frame, and its pixels there. + let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| { + let tex = app.canvas.texture.as_ref().map(|t| t.id()); + let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (d.pos, img.pixels.clone()) + }); + delta.clear(); + set + }; + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); + assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size"); + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas"); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + let (pos, edited) = canvas(&app, delta).expect("the edit shows"); + assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats"); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.renderer.threads = 2; + app.canvas.key = None; + let (_, delta) = frame_output(&mut app, &ctx); + let fresh = canvas(&app, delta).map(|(_, px)| px); + assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref())); + } +} + /// A canvas more device pixels across than the largest texture side the display supports renders /// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel /// Preview's region of document pixels stays within it too. @@ -1576,9 +1642,15 @@ fn a_drag_at_a_lower_resolution() { assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref())); // A dialog's preview: an interaction, and no drag. app.session.begin_interaction("Texturizer").unwrap(); - assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution"); + app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap(); + let preview = run(&mut app, vec![]).expect("the preview renders"); + assert!(preview != after, "the preview changes the art"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging)); assert_eq!(app.canvas.renderer.stats.previewed, 0); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.key = None; + let fresh = run(&mut app, vec![]); + assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref())); } /// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference. @@ -1673,10 +1745,10 @@ fn a_drag_over_a_wide_blur() { } } -/// An interaction's frames stay on the worker once it drew the frame shown, however fast that -/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this -/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the -/// worker, a fast frame renders on this thread as before. +/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame +/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it +/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a +/// frame from the worker, a fast frame renders on this thread as before. #[test] fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1689,6 +1761,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); (app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0); app.session.begin_interaction("Preview").unwrap(); + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } shapes(&mut app, &ctx); let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting); assert_eq!(pending, from_worker, "sent to the worker: {from_worker}"); @@ -1701,9 +1776,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } -/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the -/// frame of the move: once the press's frame arrives from the worker, every move shows the -/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into +/// that frame, here, in the frame of the press or the move: each shows the document's revision and +/// queues nothing on the worker. When the frame shown drew effect rasters /// from before their objects moved, when a part drawn here would have differed from it, or when /// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker, /// and the moves after the worker's frame are drawn here again. A frame of an older revision on @@ -1724,6 +1799,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { let (worker, mut side) = WorkerSide::start(); app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; + // A new zoom: the frame shown is the worker's. + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } + frame(&mut app, &ctx, vec![]); + assert!(side.render()); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.from_worker, "the worker drew the frame shown"); app.select_tool("pen"); let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision); let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision); @@ -1731,8 +1814,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); frame(&mut app, &ctx, vec![button(at, true)]); - assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); - assert!(side.render()); + assert_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame"); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's"); + assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker"); let mut drag = |app: &mut VectorcraftApp| { at += vec2(9.0, 5.0); frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); @@ -1745,7 +1829,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { for case in ["moved", "differs", "slow"] { match case { "moved" => app.canvas.moved = true, - "differs" => app.canvas.worker_parts = true, + "differs" => app.canvas.whole_frames = true, _ => app.canvas.last_ms = 10_000.0, } drag(&mut app); @@ -1753,26 +1837,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { assert!(side.render(), "{case}: the move renders on the worker"); drag(&mut app); assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); - assert!(!app.canvas.worker_parts, "{case}"); + assert!(!app.canvas.whole_frames, "{case}"); } // A worker's frame that drew art in a way that depends on its size: the move after it renders // on the worker too. - app.canvas.worker_parts = true; + app.canvas.whole_frames = true; drag(&mut app); let job = side.jobs.try_iter().last().expect("the move is on the worker"); let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job); side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap(); drag(&mut app); - assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size"); + assert!(app.canvas.whole_frames, "the frame shown drew art that depends on its size"); assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker"); drag(&mut app); assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here"); // A frame on its way of an older revision: the next move is drawn here, and that frame is not // shown when it arrives. - app.canvas.worker_parts = true; + app.canvas.whole_frames = true; drag(&mut app); assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way"); - app.canvas.worker_parts = false; + app.canvas.whole_frames = false; for late in [false, true] { if late { assert!(side.render()); From 68f2230d1e9648c7a14ba76934798e9211fea3af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:12:29 -0800 Subject: [PATCH 02/42] Keep canvas brush drops in their source document --- crates/ui-egui/src/canvas/drops.rs | 7 +++++-- crates/ui-egui/src/canvas/drops/tests.rs | 26 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..50fc760237 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> { let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); - let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); + let brush = Target::new(rect, view, covered, |d: &ListDrag| { + (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); let style = cx.drop_target::, _>(&style); @@ -336,7 +338,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), None => Ok(()), Some(hit) => { @@ -344,6 +346,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, + Payload::Brush(_) => Ok(()), Payload::Style(key) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..a4aad999aa 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -134,6 +134,32 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +#[test] +fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { + let (mut app, ctx) = app_with_canvas(); + let make_brush = |app: &mut VectorcraftApp, width| { + app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap(); + app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap(); + }; + make_brush(&mut app, 30); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + make_brush(&mut app, 60); + app.run("brush.setCurrent", json!({"name": null})).unwrap(); + let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); + frame(&mut app, &ctx, vec![]); + + let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); + let before = brush_of(&app); + assert!(before.is_none()); + let history = undo_len(&app); + let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); + assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); + drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either"); +} + /// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of /// a closed document places nothing. #[test] From 2f56868ae471c4d4ac414714614696fa50f34311 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:36:34 -0800 Subject: [PATCH 03/42] Color Themes: keep Create actions usable in short panels --- crates/ui-egui/src/panels/color_themes.rs | 71 +++++++++++++++++++---- 1 file changed, 59 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 067f820a5a..227cfb3933 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -16,8 +16,8 @@ use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; use craft::ui::buttons::IconButton; use craft::ui::choice::{SwatchSpacing, SwatchTable}; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; -use craft::ui::layout_components::Row; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::notices::Notice; @@ -480,6 +480,34 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { fn create(app: &mut VectorcraftApp, ui: &mut Ui) { let mut d = draft(app); + // The label is translated around the theme's name, not looked up whole. + let save_label = match &d.editing { + Some(n) => crate::i18n::fmt(tl!("Save changes to {name}"), &[("name", n)]).to_string(), + None => tl!("Save theme to My Themes").to_string(), + }; + let actions = [ + FooterAction::new(icon("file-plus"), tl!("New theme from the current color")), + FooterAction::new(icon("dc-folder"), tl!("Add to Swatches")).enabled(enabled(app, ADD_TO_SWATCHES)), + FooterAction::new(icon("save"), save_label), + ]; + let mut picked = None; + Stack::new() + .label(tl!("Create")) + .fill() + .scroll(Scroll::vertical()) + .footer(|ui, _| { + let out = FooterBar::actions(actions.clone()).show_footer(ui); + if !ui.is_sizing_pass() { + picked = out.picked; + } + }) + .show(ui, |ui, _| create_controls(app, ui, &mut d)); + if let Some(id) = picked.and_then(|at| [NEW_THEME, ADD_TO_SWATCHES, SAVE].get(at).copied()) { + run(app, id, &Value::Null); + } +} + +fn create_controls(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Draft) { let before = d.clone(); let (mut mode, mut held) = (app.ui.color_themes_panel.mode, app.ui.color_themes_panel.held.clone()); let labels: Vec<&str> = std::iter::once("Custom").chain(Harmony::ALL.into_iter().map(harmony::label)).collect(); @@ -518,7 +546,7 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(&i) = chosen.items.last() { d.sel = i; } - sliders(ui, &mut d, &mut mode, &mut held); + sliders(ui, d, &mut mode, &mut held); Row::new().show(ui, |ui, _| { let hex = d.colors.get(d.sel).map(hex_rgba).unwrap_or(Rgba::rgb(0, 0, 0)); let mut edited = hex; @@ -533,7 +561,7 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { if IconButton::new(icon("paint-bucket")).label(tl!("Set the current fill or stroke to the selected color")).enabled(can_set).show(ui).clicks == 1 { - set_active_color(app, &d); + set_active_color(app, d); } let current = active_paint(app).color(); if IconButton::new(icon("pipette")).label(tl!("Set the selected color to the current color")).enabled(current.is_some()).show(ui).clicks == 1 @@ -546,16 +574,9 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { let st = &mut app.ui.color_themes_panel; st.mode = mode; st.held = held; - if d != before { + if *d != before { set_draft(app, d.clone()); } - // The label is translated around the theme's name, not looked up whole. - let save_label = match &d.editing { - Some(n) => crate::i18n::fmt(tl!("Save changes to {name}"), &[("name", n)]).to_string(), - None => tl!("Save theme to My Themes").to_string(), - }; - let labels = vec![Label::from(tl!("New theme from the current color")), Label::from(tl!("Add to Swatches")), Label::from(save_label)]; - footer(app, ui, &[NEW_THEME, ADD_TO_SWATCHES, SAVE], &["file-plus", "dc-folder", "save"], labels); } fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -633,6 +654,32 @@ mod tests { &app.session.prefs.color_themes } + #[test] + fn a_short_color_themes_panel_keeps_create_actions_in_view() { + use craft::ui::testing::pointer; + + let app = Rc::new(RefCell::new(app())); + let mut fx = fixture(&app); + let room = vec2(340.0, 320.0); + fx.room(room).settle(); + let names = ["New theme from the current color", "Add to Swatches", "Save theme to My Themes"]; + for name in names { + let action = fx.by_label(name).unwrap_or_else(|| panic!("{name} is missing")); + assert!(action.rect.bottom() <= room.y, "{name} at {:?} is below the panel", action.rect); + assert!(fx.visible(&action).is_some(), "{name} is clipped"); + } + let save_at = fx.by_label("Save theme to My Themes").unwrap().rect; + let name_at = fx.by_label("Name:").expect("the draft name").rect; + fx.frame(vec![pointer::moved(egui::pos2(20.0, room.y / 2.0)), pointer::wheel(-600.0)]).settle(); + let name = fx.by_label("Name:").expect("the draft name").rect; + assert!(name.top() < name_at.top(), "the body scrolls"); + assert!(name.top() >= 0.0 && name.bottom() <= save_at.top(), "the name {name:?} scrolls above the footer {save_at:?}"); + let save = fx.by_label("Save theme to My Themes").unwrap(); + assert_eq!(save.rect, save_at, "the footer stays put while the controls scroll"); + fx.click(&save).settle(); + assert_eq!(themes(&app.borrow()).len(), 1); + } + /// The panel over `app` in a fixture, settled; the app stays reachable through the `Rc`. fn fixture(app: &Rc>) -> Fixture { let shared = Rc::clone(app); From f5bc5566db3e49197d390bb6f12b0353b01a68ab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:29:00 -0800 Subject: [PATCH 04/42] Preserve process swatch color across canvas documents --- crates/ui-egui/src/canvas/drops.rs | 12 +++- crates/ui-egui/src/canvas/drops/tests.rs | 77 ++++++++++++++++++++- crates/ui-egui/src/panel_drag.rs | 2 + crates/ui-egui/src/panels/swatches.rs | 3 +- crates/ui-egui/src/panels/swatches/dnd.rs | 17 +++-- crates/ui-egui/src/panels/swatches/tests.rs | 19 ++++- 6 files changed, 118 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..ed9b696ffb 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -349,7 +349,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), let top = top_object(app, &hit)?; run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) } - Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + Payload::Panel(PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" && let Some((id, points)) = selected_mesh_drop(app, at, zoom) @@ -358,7 +358,15 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), return run(app, "object.mesh.setPointColor", params); } let Some(hit) = hit() else { return Ok(()) }; - let mut params = params.clone(); + let source = rows.as_ref().and_then(|rows| rows.process_color_source); + let mut params = if let Some(document) = source + && app.session.active().is_some_and(|st| st.uid != document) + && let Some(color) = paint.color() + { + json!({"color": crate::panels::color_json(&color), "keepModel": true}) + } else { + params.clone() + }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..0ebde61779 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -10,7 +10,7 @@ use vectorcraft_engine::Session; use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; -use crate::panel_drag::PanelDrag; +use crate::panel_drag::{PanelDrag, SwatchRows}; use crate::panels::brushes::{BrushKey, BrushLibraries}; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; @@ -45,6 +45,81 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { + let (mut app, ctx) = app_with_canvas(); + let name = "Shared Swatch"; + let at = Point::new(250.0, 70.0); + let add_target = |app: &mut VectorcraftApp| { + NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap(); + let paint = source.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { grabbed: name.into(), names: vec![name.into()], groups: false, process_color_source: Some(source.uid) }; + let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; + + let local_target = add_target(&mut app); + app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); + let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name"); + assert_ne!(edited, paint); + + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + let target = add_target(&mut app); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, target), paint); + assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination); +} + +#[test] +fn a_swatch_drag_keeps_its_color_after_next_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays held during Next Document"); + panel.release(); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 83ebf46070..a7bbc3a87b 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -45,6 +45,8 @@ pub struct SwatchRows { pub names: Vec, /// The names are colour groups. pub groups: bool, + /// The document of a grabbed, unlinked process color, whose paint can travel on its own. + pub process_color_source: Option, } impl PanelDrag { diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9995752ec1..ea03a1086f 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -407,9 +407,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { doc: Arc::clone(&st.doc), }; let dragged_doc = Arc::clone(&thumbs.doc); + let document = st.uid; let shown_app: &VectorcraftApp = app; let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag)))) + .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), diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index dd3aff50f9..91e035de54 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -44,17 +44,20 @@ 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)), + let (paint, params, process_color_source) = match key { + SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name), None), SwatchKey::Swatch(_) => match d.swatch(name) { - Some(w) => (w.paint.clone(), swatch_params(d, name)), - None => (Paint::None, Value::Null), + Some(w) => { + let process = !w.global && !w.spot && matches!(w.paint, Paint::Solid { swatch: None, .. }); + (w.paint.clone(), swatch_params(d, name), process.then_some(document)) + } + None => (Paint::None, Value::Null, None), }, - _ => (Paint::None, Value::Null), + _ => (Paint::None, Value::Null, None), }; - let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) }; + let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)), process_color_source }; 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 b638b289f5..447f152aa9 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -96,7 +96,24 @@ 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()) + dnd::drag_of(&doc(app), app.session.active().unwrap().uid, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) +} + +#[test] +fn only_unlinked_process_swatches_carry_their_source_for_canvas_color() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Global red", "color": "#ff0000", "global": true})).unwrap(); + app.run("swatch.new", json!({"name": "Spot blue", "color": "#0000ff", "spot": true})).unwrap(); + let tint = app.run("swatch.new", json!({"swatch": "Spot blue", "tint": 40})).unwrap(); + let document = app.session.active().unwrap().uid; + let source = |name| { + let PanelDrag::Paint { rows: Some(rows), .. } = rows_drag(&app, name, &[name]) else { panic!("a swatch row drag") }; + rows.process_color_source + }; + assert_eq!(source("Red"), Some(document)); + for name in ["Global red", "Spot blue", tint["name"].as_str().unwrap(), "[None]", "[Registration]"] { + assert_eq!(source(name), None, "{name}"); + } } /// Art `ids` dragged off the canvas. From f5c5adbfa6e4455ba475e5b502f2430d4b312c9e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:50:47 -0800 Subject: [PATCH 05/42] Keep Live Paint Gap Options with its original document --- crates/ui-egui/src/dialogs/live_paint_gaps.rs | 138 +++++++++++++++--- crates/ui-egui/src/dialogs/option_form.rs | 14 +- 2 files changed, 132 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index bcbb884bc2..f03b2167e5 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -26,6 +26,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "livePaintGapOptions"; const CMD: &str = "livePaint.gapOptions"; +const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for."; /// The undo step the preview and OK make. const PREVIEW_LABEL: &str = "Gap Options"; @@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec { pub(crate) struct Open { /// The dialog the preview belongs to. pub id: DialogId, + /// The document that owns the preview interaction. + document: u64, /// The preview the options run as. pub preview: LivePreview, } +impl Open { + fn cancel(self, app: &mut VectorcraftApp) { + if app.session.active().is_some_and(|active| active.uid == self.document) { + self.preview.cancel(app); + } + } +} + /// Open Gap Options on the selected Live Paint groups, filled in from the first one's options. pub fn open(app: &mut VectorcraftApp) -> Result { - let groups: Vec = app - .session - .doc() - .map(|d| { - let doc = &d.doc; - d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect() - }) - .unwrap_or_default(); + let active = app.session.active().ok_or("select a Live Paint group")?; + let document = active.uid; + let groups: Vec = active + .selection + .objects + .iter() + .filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)) + .map(|id| id.0) + .collect(); let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) }; let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?; let o = &info["gapOptions"]; @@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let fields = [("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))]; let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value))); - option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?; + option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document })).ok_or("no window")?; Ok(Value::Null) } +fn original_document(app: &VectorcraftApp, extra: &Value) -> Option { + let document = extra["document"].as_u64()?; + app.session.active().filter(|active| active.uid == document).map(|_| document) +} + /// `livePaint.gapOptions` parameters from the values and the groups in `extra`. fn params(values: &Map, extra: &Value) -> Value { let size = match values.get("size").and_then(Value::as_str) { @@ -111,24 +128,43 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) { /// OK: keep the previewed options as one undo step; with no preview running they run as one. fn run(app: &mut VectorcraftApp, values: &Map, extra: &Value) -> Result { - let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview); + let document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?; + let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview); preview.commit(app, CMD, params(values, extra)) } /// The dialog closed without OK: roll the preview back. fn cancelled(app: &mut VectorcraftApp) { if let Some(open) = app.object_dialogs.gaps.take() { - open.preview.cancel(app); + open.cancel(app); } } /// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the /// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`]. /// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running. -pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let shown = dialogs.with(|host| { - let form = host.get::().filter(|form| form.is(KIND))?; + let form = host.get_mut::().filter(|form| form.is(KIND))?; + let source = form.extra["document"].as_u64()?; + if !app.session.documents().iter().any(|doc| doc.uid == source) { + host.cancel::(ctx); + return None; + } + let document = original_document(app, &form.extra); + let paused = document.is_none(); + if form.preview_paused != paused { + form.preview_paused = paused; + if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) { + form.held.clear_refusal(); + } + ctx.request_repaint(); + } + let Some(document) = document else { + form.previewed = Value::Null; + return None; + }; if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) { return None; } @@ -137,17 +173,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) { params["color"] = Value::Null; } - Some((form.id(), params, form.preview)) + Some((form.id(), document, params, form.preview)) }); - let Some((id, params, on)) = shown else { return }; + let Some((id, document, params, on)) = shown else { return }; // A preview of another dialog is rolled back before this one starts its own. let mut open = match app.object_dialogs.gaps.take() { - Some(open) if open.id == id => open, + Some(open) if open.id == id && open.document == document => open, stale => { if let Some(stale) = stale { - stale.preview.cancel(app); + stale.cancel(app); } - Open { id, preview: LivePreview::default() } + Open { id, document, preview: LivePreview::default() } } }; let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, ¶ms); @@ -177,6 +213,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec { let Some(dialogs) = app.dialogs() else { return vec![] }; let shown = dialogs.with(|host| { let form = host.get::().filter(|form| form.is(KIND) && form.preview)?; + original_document(app, &form.extra)?; Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned())) }); let Some((gaps, color)) = shown else { return vec![] }; @@ -236,6 +273,71 @@ mod tests { app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap() } + fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 { + let group = gapped_group(app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert_eq!(gapped_group(app), group, "the new document reuses the group ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(app, "detect", json!(true)).unwrap(); + group + } + + #[test] + fn gap_confirmation_stays_with_its_document() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!press_ok(&mut app), "the unrelated group cannot take the edit"); + assert_eq!(options(&app, group), GapOptions::default()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(held(&app).is_none(), "the stale refusal clears on the original tab"); + assert!(press_ok(&mut app), "the original group's edit can be retried"); + assert!(options(&app, group).detect); + } + + #[test] + fn closing_the_original_document_dismisses_gap_options() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(app.session.close_document(0)); + pump_all(&mut app); + assert!(!is_open(&app)); + assert_eq!(options(&app, group), GapOptions::default()); + } + + #[test] + fn gap_preview_disappears_in_another_document_and_resumes_on_return() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let unrelated_overlays = overlays(&app); + pump_all(&mut app); + let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().unwrap().preview_paused); + assert!(paused(&app)); + assert_eq!(fields(&app)["preview"], json!(true)); + assert_eq!(options(&app, group), GapOptions::default()); + assert!(!app.session.in_interaction()); + assert!(unrelated_overlays.is_empty()); + assert!(overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(!paused(&app)); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + cancel(&mut app); + assert_eq!(options(&app, group), GapOptions::default()); + } + #[test] fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/option_form.rs b/crates/ui-egui/src/dialogs/option_form.rs index 8648332c7e..49ef4a34b4 100644 --- a/crates/ui-egui/src/dialogs/option_form.rs +++ b/crates/ui-egui/src/dialogs/option_form.rs @@ -7,7 +7,7 @@ use std::ops::RangeInclusive; use craft::theme::variant::Tone; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row; @@ -175,6 +175,8 @@ pub(crate) struct OptionForm { lengths: LengthUnits, /// The Preview check box. pub(super) preview: bool, + /// The current document does not own this dialog's preview. + pub(super) preview_paused: bool, /// Whether the dialog's container is open. open: bool, /// The OK the dialog filed for [`pump`] to answer. @@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values: extra, lengths, preview: false, + preview_paused: false, open: true, held: HeldAnswer::new(), requests: HostRequests::new(), @@ -249,8 +252,9 @@ impl StackDialog for OptionForm { // The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing. let finish = self.held.is_accepted() && !measuring; let answers = if measuring { Vec::new() } else { self.requests.take_answers() }; - let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self; + let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self; let (spec, lengths) = (*spec, *lengths); + let show_pause = *preview && *preview_paused; let title = (spec.title)(); let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone())); let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values)) @@ -274,6 +278,12 @@ impl StackDialog for OptionForm { if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) { Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); } + if show_pause { + Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Polite) + .show(ui); + } if finish { form.request_close_as(CloseReason::Activated); } From 962dce59f77f72ce1463d94708a4c5b98f527df3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:00:10 -0800 Subject: [PATCH 06/42] Keep tracing preset picker effects with the requesting manager --- crates/ui-egui/src/dialogs/tracing_presets.rs | 106 +++++++++++------- .../src/dialogs/tracing_presets/tests.rs | 42 +++++++ 2 files changed, 108 insertions(+), 40 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index d8ff9b4d49..2db0261f2b 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -89,6 +89,8 @@ pub(crate) struct Manager { data: RowsData, /// What a button asked for, taken by [`pump`]. action: Option, + /// Identifies this opening when an Import picker finishes later. + import_owner: Arc<()>, } impl StackDialog for Manager { @@ -180,8 +182,13 @@ impl StackDialog for Manager { /// Open the presets manager on `selected` (default: the first preset, Default). pub(crate) fn open(app: &mut VectorcraftApp, selected: Option<&str>) { - let manager = - Manager { list: image_trace::presets(app), selected: selected.unwrap_or("Default").to_string(), data: RowsData::of(app), action: None }; + let manager = Manager { + list: image_trace::presets(app), + selected: selected.unwrap_or("Default").to_string(), + data: RowsData::of(app), + action: None, + import_owner: Arc::new(()), + }; match app.dialogs() { Some(dialogs) => { dialogs.with(|host| host.open(manager)); @@ -251,10 +258,11 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin select(app, next.as_deref().unwrap_or("Default")); } Action::Import => { + let Some(owner) = with_manager(app, |m| Arc::clone(&m.import_owner)) else { return Ok(()) }; let name = file_asks::filter_name(crate::i18n::current(), "Tracing presets"); let request = PickRequest::open("tracingPresets").filter(name, TRACE_PRESET_EXTS); // The answer, or its failure, reaches the status bar from the continuation; nothing is pending here. - let _ = file_asks::ask(app, request, Owner::Free, picked); + let _ = file_asks::ask(app, request, Owner::Free, move |app, answer| picked(app, answer, ImportSource::Picker(owner))); } Action::Export => { crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}), |_, _| Ok(Value::Null))?; @@ -263,20 +271,37 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin Ok(()) } -/// The file Import… picked: a path on the desktop, the file's bytes on the web. -fn picked(app: &mut VectorcraftApp, picked: Picked) -> Result { - match picked { - Picked::Paths(paths) => { - if let Some(path) = paths.first() { - open_path(app, &path.to_string_lossy())?; - } +enum ImportSource { + FileOpen, + Picker(Arc<()>), +} + +impl ImportSource { + fn matches(&self, manager: &Manager) -> bool { + match self { + Self::FileOpen => true, + Self::Picker(owner) => Arc::ptr_eq(owner, &manager.import_owner), } - Picked::Contents(files) => { - if let Some((_, bytes)) = files.first() { - open_file(app, bytes)?; + } + + fn select(&self, app: &VectorcraftApp, name: &str) { + let _ = with_manager(app, |manager| { + if self.matches(manager) { + manager.selected = name.to_string(); } - } - _ => {} + }); + } +} + +/// The file Import… picked, a path on the desktop or the file's bytes on the web. +fn picked(app: &mut VectorcraftApp, picked: Picked, source: ImportSource) -> Result { + let file = match picked { + Picked::Paths(paths) => paths.first().map(|path| file_contents(app, json!({ "path": path.to_string_lossy() }))).transpose()?, + Picked::Contents(files) => files.first().map(|(_, bytes)| checked_contents(bytes)).transpose()?, + _ => None, + }; + if let Some(file) = file { + open_import(app, file, source)?; } Ok(Value::Null) } @@ -294,6 +319,7 @@ fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec, + source: ImportSource, } /// The Replace question. Its own type, so the host keeps its answer apart from every other prompt's. @@ -301,22 +327,23 @@ pub(crate) struct ReplacePresets(pub(crate) StandardPrompt); crate::dialogs::confirm::wrapped_dialog!(ReplacePresets, StandardPrompt, REPLACE_KIND); -/// Asks whether the import of `file` replaces the saved presets `skipped` kept, over the manager -/// when it is open. -fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value) { +/// Asks whether the import of `file` replaces the saved presets `skipped` kept. It opens over the +/// manager if the import targets that opening. +fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value, source: ImportSource) { let names: Vec