PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix live brush preview drawing a polygon (#189) (#240) (#240)
Brandon Thomas109498a746ca
diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rsindex 0e9ab4034..9e78118ac 100644--- a/crates/engine/src/brush_cmds/tests.rs+++ b/crates/engine/src/brush_cmds/tests.rs@@ -312,6 +312,51 @@ fn live_stroke_matches_the_committed_stroke() {assert!(LiveStroke::begin(&Session::new(), &json!({"points": [[1, 1]]})).is_err());}+#[test]+fn live_stroke_equals_the_commit_at_every_zoom_with_smoothing() {+ // #189: the preview while dragging must be the committed stroke (within 1/255), with a soft+ // brush on an opaque Background with content, at any zoom (the smoothing string scales with+ // it), with smoothing on, pressure, 8 and 16 bits, and points fed one pointer move at a time.+ let pts: Vec<[f64; 3]> = (0..40)+ .map(|i| {+ let t = f64::from(i) / 39.0;+ [40.0 + 120.0 * t, 60.0 + 30.0 * (t * 7.0).sin(), 0.3 + 0.7 * t]+ })+ .collect();+ for depth in [8, 16] {+ for zoom in [0.25, 1.0, 4.0, 16.0] {+ for (amount, pulled) in [(0.1, false), (0.5, false), (0.3, true)] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 200, "height": 120, "depth": depth, "background": "white"})).unwrap();+ s.execute("edit.fill", json!({"color": "#1a2550"})).unwrap();+ s.execute("paint.stroke", json!({"points": [[20, 20], [180, 100]], "size": 8, "hardness": 1.0, "color": "#ffffff"})).unwrap();+ s.tools.foreground = [0.0, 0.0, 0.0, 1.0];+ let brush = json!({"size": 40, "hardness": 0.0, "pressureSize": true, "smoothing": {"amount": amount, "pulledString": pulled}});+ let p = json!({"points": [pts[0]], "brush": brush, "zoom": zoom, "target": "pixels"});+ let mut live = LiveStroke::begin(&s, &p).unwrap();+ for q in &pts[1..] {+ live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap();+ }+ let mut commit = p.clone();+ commit["points"] = json!(pts);+ commit["seed"] = json!(live.seed);+ s.execute("paint.stroke", commit).unwrap();+ let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().clone();+ let done = surface(&s);+ let worst = (0..120).flat_map(|y| (0..200).map(move |x| (x, y))).map(|(x, y)| {+ let (a, b) = (shown.rgba(x, y), done.rgba(x, y));+ (0..4).map(|i| (a[i] - b[i]).abs()).fold(0.0f32, f32::max)+ });+ let worst = worst.fold(0.0f32, f32::max);+ let label = format!("depth {depth}, zoom {zoom}, smoothing {amount} (pulled string {pulled})");+ assert!(worst <= 1.0 / 255.0, "{label}: preview differs from the commit by {worst}");+ // Not two blank canvases: the soft stroke is there, edge included.+ assert!(done.rgba(40, 60)[0] < 0.1 && (0.05..0.9).contains(&done.rgba(40, 60 - 14)[2]), "{label}: soft stroke");+ }+ }+ }+}+#[test]fn new_brush_controls_round_trip_through_set_brush() {let mut s = session(40, 40);diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 0712cb504..691a252c3 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1489,9 +1489,12 @@ fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf:}}-fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {+fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos()));- let Some(d) = &app.drag else { return };+ let Some(d) = &app.drag else {+ app.trail = None;+ return;+ };let mut last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);if matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee) {let o = &app.ui.tool_options;@@ -1501,15 +1504,15 @@ fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXfor// The canvas shows the live stroke itself (`LiveStroke`).Tool::Brush | Tool::Eraser => {}t if t.is_brushlike() || t == Tool::QuickSelection => {- // Retouching strokes preview as a translucent trail of the brush footprint.- let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();- let w = (app.session.tools.brush.size * xf.zoom).max(1.0);+ // Retouching strokes preview as a translucent trail of the brush footprint: a mask,+ // not a brush-wide egui polyline (which zoomed in tessellates into wedges, #189).let col = Color32::from_white_alpha(if t == Tool::QuickSelection { 40 } else { 60 });- if pts.len() == 1 {- painter.circle_filled(pts[0], w / 2.0, col);- } else {- painter.add(egui::Shape::line(pts, Stroke::new(w, col)));- }+ let Some(st) = app.session.active() else { return };+ let size = [st.doc.size.width, st.doc.size.height];+ let doc_rect = xf.doc_rect(st.doc.bounds());+ let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size));+ trail.feed(&d.points, app.session.tools.brush.size);+ trail.draw(painter, doc_rect, xf.flip, col);}t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::draw_shape_preview(app, painter, xf, t, d.start, last, d.modifiers),Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection => {@@ -1677,6 +1680,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)points.insert(0, [p[0], p[1], pressure as f64]);}app.drag = Some(Drag { tool, start: from.unwrap_or([x, y]), points, modifiers: mods, erase, constrain: None });+ app.trail = None;app.stylus.begin_stroke();if from.is_some() {app.stylus.record_point();@@ -2070,6 +2074,83 @@ mod tests {assert!((0..120).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))), "no stale tails in the preview");}+ /// Shapes the drag preview paints for `app` this frame.+ fn drag_preview_shapes(app: &mut PhotocraftApp, ctx: &egui::Context, zoom: f32) -> Vec<egui::epaint::ClippedShape> {+ let out = ctx.run_ui(egui::RawInput::default(), |ui| {+ let ctx = ui.ctx();+ let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));+ let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect);+ let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false };+ draw_drag_preview(app, &painter, &xf);+ });+ let egui::FullOutput { mut textures_delta, shapes, .. } = out;+ textures_delta.clear();+ shapes+ }++ #[test]+ fn brush_drags_paint_no_stand_in_shape_over_the_canvas() {+ // #189: v0.1 drew the stroke being dragged as a foreground-coloured egui polyline as wide+ // as the brush; zoomed in, egui tessellated it into hard black wedges fanning out from the+ // start. The canvas shows the real stroke (`LiveStroke`) and nothing is drawn over it.+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 120, "height": 60})).unwrap();+ app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": 0.0}})).unwrap();+ for tool in [Tool::Brush, Tool::Eraser] {+ app.ui.tool = tool;+ let idle = drag_preview_shapes(&mut app, &ctx, 12.0).len();+ tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ for i in 1..40 {+ let t = f64::from(i);+ tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 3.0).sin() * 4.0, pressure: 1.0 }, egui::Modifiers::NONE);+ }+ assert!(app.live_stroke.is_some(), "{tool:?}: the canvas shows the live stroke");+ assert_eq!(drag_preview_shapes(&mut app, &ctx, 12.0).len(), idle, "{tool:?}: no overlay while dragging");+ tool_event(&mut app, ToolEvent::Up { x: 59.0, y: 30.0 }, egui::Modifiers::NONE);+ }+ }++ #[test]+ fn retouch_drags_show_the_footprint_without_wedges() {+ // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the+ // footprint, with nothing outside the brush radius of the path, however small the steps.+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 120, "height": 60})).unwrap();+ app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap();+ app.ui.tool = Tool::Dodge;+ tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ let mut pts = vec![[20.0, 30.0]];+ for i in 1..80 {+ let t = f64::from(i) * 0.5;+ let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0];+ tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE);+ pts.push(p);+ if i % 20 == 0 {+ // One mesh for the trail, however long the drag.+ let shapes = drag_preview_shapes(&mut app, &ctx, 12.0);+ assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline");+ }+ }+ drag_preview_shapes(&mut app, &ctx, 12.0);+ let trail = app.trail.as_ref().unwrap();+ assert_eq!(trail.scale(), 1.0);+ for y in 0..60 {+ for x in 0..120 {+ let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min);+ if d < 14.0 {+ assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint");+ } else if d > 16.0 {+ assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint");+ }+ }+ }+ tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE);+ drag_preview_shapes(&mut app, &ctx, 12.0);+ assert!(app.trail.is_none(), "the trail ends with the drag");+ }+#[test]fn layer_style_dialog_previews_live_and_cancel_restores() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 7169c0d13..6c2e1f0e1 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -82,6 +82,7 @@ pub mod smart_ui;pub mod snap_ui;pub mod state;pub mod stroke_constraint;+pub mod stroke_trail;pub mod stylus;mod tab_strip;pub mod theme;@@ -210,6 +211,8 @@ pub struct PhotocraftApp {drag: Option<canvas::Drag>,/// Brush/Eraser stroke being drawn, rendered by the engine (see `canvas::LiveStroke`).live_stroke: Option<canvas::LiveStroke>,+ /// Footprint trail of a retouching drag (see `stroke_trail`).+ trail: Option<stroke_trail::Trail>,/// The next tool `Down` is a right-button drag that erases (see `paint_mouse`).secondary_erase: bool,/// End of the last painting stroke: ⇧-click draws a straight line from it (#178).@@ -321,6 +324,7 @@ impl PhotocraftApp {checker: None,drag: None,live_stroke: None,+ trail: None,secondary_erase: false,last_stroke_end: None,control_rx: None,diff --git a/crates/ui-egui/src/stroke_trail.rs b/crates/ui-egui/src/stroke_trail.rsnew file mode 100644index 000000000..4d1fe8699--- /dev/null+++ b/crates/ui-egui/src/stroke_trail.rs@@ -0,0 +1,168 @@+//! The translucent footprint trail the retouching tools (Dodge, Blur, Clone Stamp, …) and Quick+//! Selection show while dragging: the union of the brush's round footprint along the drag.+//!+//! It is a coverage mask in document space, stamped segment by segment as the pointer moves and+//! drawn as one texture over the document. It used to be an egui polyline as wide as the brush:+//! egui tessellates a polyline whose width is much larger than its steps (any zoomed-in drag)+//! into hard pie wedges fanning out across the canvas (#189), and translucent overlaps doubled up.++use egui::{Color32, ColorImage, Rect, TextureHandle, TextureOptions, pos2};++/// Longest side of the mask, in mask pixels (big documents are stamped at a reduced scale).+const MAX_SIDE: u32 = 1024;++/// A drag's footprint mask.+pub struct Trail {+ /// Document size the mask covers.+ doc: [u32; 2],+ /// Document pixels per mask pixel.+ k: f32,+ w: usize,+ h: usize,+ /// Coverage 0..=255 per mask pixel.+ cov: Vec<u8>,+ /// Drag points stamped so far.+ fed: usize,+ /// Mask pixels changed since the last upload (x0, y0, x1, y1), if any.+ dirty: Option<[usize; 4]>,+ tex: Option<TextureHandle>,+}++impl Trail {+ pub fn new(doc: [u32; 2]) -> Self {+ let k = doc[0].max(doc[1]).div_ceil(MAX_SIDE).max(1);+ let (w, h) = (doc[0].div_ceil(k).max(1) as usize, doc[1].div_ceil(k).max(1) as usize);+ Self { doc, k: k as f32, w, h, cov: vec![0; w * h], fed: 0, dirty: None, tex: None }+ }++ /// Coverage at a mask pixel (tests).+ pub fn coverage(&self, x: usize, y: usize) -> u8 {+ if x < self.w && y < self.h { self.cov.get(y * self.w + x).copied().unwrap_or(0) } else { 0 }+ }++ /// Document pixels per mask pixel.+ pub fn scale(&self) -> f32 {+ self.k+ }++ /// Stamp the drag points not seen yet: round footprints of `diameter` document pixels joined+ /// into a capsule per segment (coverage is the max, so overlaps don't add up).+ pub fn feed(&mut self, points: &[[f64; 3]], diameter: f32) {+ if self.fed >= points.len() {+ return;+ }+ let k = f64::from(self.k);+ let r = (f64::from(diameter.max(1.0)) / 2.0) / k;+ let mask = |p: &[f64; 3]| [p[0] / k, p[1] / k];+ for i in self.fed..points.len() {+ let Some(b) = points.get(i).map(mask) else { break };+ let a = i.checked_sub(1).and_then(|j| points.get(j)).map_or(b, mask);+ self.capsule(a, b, r);+ }+ self.fed = points.len();+ }++ fn capsule(&mut self, a: [f64; 2], b: [f64; 2], r: f64) {+ if !(a.iter().chain(&b).all(|v| v.is_finite()) && r.is_finite()) {+ return;+ }+ let x0 = (a[0].min(b[0]) - r - 1.0).floor().max(0.0);+ let y0 = (a[1].min(b[1]) - r - 1.0).floor().max(0.0);+ let x1 = (a[0].max(b[0]) + r + 1.0).ceil().min(self.w as f64);+ let y1 = (a[1].max(b[1]) + r + 1.0).ceil().min(self.h as f64);+ if x1 <= x0 || y1 <= y0 {+ return;+ }+ let (x0, y0, x1, y1) = (x0 as usize, y0 as usize, x1 as usize, y1 as usize);+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let len2 = dx * dx + dy * dy;+ for y in y0..y1 {+ for x in x0..x1 {+ let (px, py) = (x as f64 + 0.5 - a[0], y as f64 + 0.5 - a[1]);+ let t = if len2 > 0.0 { ((px * dx + py * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };+ let d = (px - t * dx).hypot(py - t * dy);+ // One mask pixel of anti-aliasing at the edge.+ let c = ((r + 0.5 - d).clamp(0.0, 1.0) * 255.0).round() as u8;+ if let Some(v) = self.cov.get_mut(y * self.w + x)+ && c > *v+ {+ *v = c;+ }+ }+ }+ let d = self.dirty.get_or_insert([x0, y0, x1, y1]);+ *d = [d[0].min(x0), d[1].min(y0), d[2].max(x1), d[3].max(y1)];+ }++ fn image(&self, r: [usize; 4], color: Color32) -> ColorImage {+ let [x0, y0, x1, y1] = r;+ let mut px = Vec::with_capacity((x1 - x0) * (y1 - y0));+ for y in y0..y1 {+ for x in x0..x1 {+ let c = self.coverage(x, y);+ px.push(Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), ((u16::from(c) * u16::from(color.a())) / 255) as u8));+ }+ }+ ColorImage::new([x1 - x0, y1 - y0], px)+ }++ /// Upload what changed and draw the trail over the document (`doc_rect` = the document's+ /// screen rectangle, `flip` = mirrored view), tinted `color` where fully covered.+ pub fn draw(&mut self, painter: &egui::Painter, doc_rect: Rect, flip: bool, color: Color32) {+ let opts = TextureOptions::LINEAR;+ let dirty = self.dirty.take();+ if self.tex.is_none() {+ let img = self.image([0, 0, self.w, self.h], color);+ self.tex = Some(painter.ctx().load_texture("stroke-trail", img, opts));+ } else if let Some(r) = dirty {+ let img = self.image(r, color);+ if let Some(t) = self.tex.as_mut() {+ t.set_partial([r[0], r[1]], img, opts);+ }+ }+ let Some(t) = &self.tex else { return };+ // The mask's last column/row may reach past the document (sizes rounded up).+ let (u, v) = (self.doc[0] as f32 / (self.w as f32 * self.k), self.doc[1] as f32 / (self.h as f32 * self.k));+ let uv = if flip { Rect::from_min_max(pos2(u, 0.0), pos2(0.0, v)) } else { Rect::from_min_max(pos2(0.0, 0.0), pos2(u, v)) };+ painter.image(t.id(), doc_rect, uv, Color32::WHITE);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_trail_is_the_union_of_round_footprints_along_the_drag() {+ let mut t = Trail::new([200, 100]);+ // Many tiny steps with a wide brush (what zoomed-in drags send).+ let pts: Vec<[f64; 3]> = (0..200).map(|i| [40.0 + f64::from(i) * 0.5, 50.0 + (f64::from(i) * 0.3).sin(), 1.0]).collect();+ t.feed(&pts[..100], 40.0);+ t.feed(&pts, 40.0);+ assert_eq!(t.coverage(90, 50), 255, "on the path");+ assert_eq!(t.coverage(90, 50 + 15), 255, "inside the footprint");+ assert_eq!(t.coverage(90, 50 + 25), 0, "outside the footprint: no wedges reaching out");+ assert_eq!(t.coverage(5, 50), 0, "nothing behind the start");+ assert_eq!(t.coverage(170, 50), 0, "nothing past the end");+ // Every covered pixel lies within the brush radius of the path.+ for y in 0..100 {+ for x in 0..200 {+ if t.coverage(x, y) > 0 {+ let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min);+ assert!(d <= 21.5, "({x}, {y}) is {d} px from the path");+ }+ }+ }+ }++ #[test]+ fn hostile_points_and_huge_documents_are_safe() {+ let mut t = Trail::new([300_000, 2]);+ assert!(t.scale() > 1.0 && t.w <= MAX_SIDE as usize);+ t.feed(&[[f64::NAN, 1.0, 1.0], [f64::INFINITY, -1e300, 1.0], [-5.0, -5.0, 1.0], [1e12, 1.0, 1.0]], 1e9);+ t.feed(&[], 10.0);+ let mut e = Trail::new([0, 0]);+ e.feed(&[[0.0, 0.0, 1.0]], 0.0);+ assert!(e.coverage(0, 0) > 0 && e.coverage(5, 5) == 0);+ }+}diff --git a/crates/ui-egui/tests/live_stroke_canvas.rs b/crates/ui-egui/tests/live_stroke_canvas.rsnew file mode 100644index 000000000..06d51fa1d--- /dev/null+++ b/crates/ui-egui/tests/live_stroke_canvas.rs@@ -0,0 +1,149 @@+//! #189: while a Brush stroke is drawn, the canvas must show the stroke as it will be committed.+//! v0.1 drew a stand-in while dragging, a foreground-coloured egui polyline as wide as the brush,+//! which egui tessellates into hard pie wedges fanning out from the start once the brush is much+//! wider than the pointer's steps (zoomed in). The real stroke only appeared on release.+//!+//! These drive the real app offscreen and compare the screen at the last pointer move with the+//! screen after release, on the GPU canvas and on the CPU canvas (flipped views draw through it),+//! at several zooms, with smoothing, pressure, and 8- and 16-bit documents. Skips when no GPU+//! adapter exists (like `color_managed_canvas.rs`).++use photocraft_ui_egui::PhotocraftApp;+use photocraft_ui_egui::control::{ControlRequest, handle};+use serde_json::{Value, json};++type Harness = egui_kittest::Harness<'static, PhotocraftApp>;+type Pixels = Vec<[u8; 4]>;++fn harness() -> Option<Harness> {+ let built = std::panic::catch_unwind(|| {+ egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(|cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ if let Some(rs) = cc.wgpu_render_state.as_ref() {+ app.set_wgpu(rs.clone());+ }+ app+ })+ });+ match built {+ Ok(h) => Some(h),+ Err(_) => {+ eprintln!("skipping: no GPU adapter");+ None+ }+ }+}++/// Runs a control call and the frame that shows it; returns that (call + frame) time in ms.+fn control(h: &mut Harness, method: &str, params: Value) -> f64 {+ let ctx = h.ctx.clone();+ let (req, _rx) = ControlRequest::new(method, params);+ let t0 = std::time::Instant::now();+ handle(h.state_mut(), &ctx, &req);+ h.step();+ let ms = t0.elapsed().as_secs_f64() * 1000.0;+ h.run_steps(2);+ ms+}++#[derive(Clone, Copy, Debug)]+struct Case {+ zoom: f32,+ smoothing: f32,+ hardness: f32,+ depth: u8,+ pressure: bool,+ /// Flipped view: drawn through the CPU canvas texture instead of the GPU canvas.+ flip: bool,+}++/// A dark blue document with a white line, then a soft black stroke across it. Returns the+/// canvas pixels before the stroke, at its last pointer move, and after release, and whether+/// the GPU canvas drew them.+fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {+ let mut times = Vec::new();+ {+ let app = h.state_mut();+ // Close what an earlier case left open.+ while app.session.active().is_some() {+ app.run("file.close", json!({"discard": true})).expect("close");+ }+ app.run("file.new", json!({"width": 300, "height": 200, "depth": c.depth, "background": "white"})).expect("new");+ app.run("edit.fill", json!({"color": "#1a2550"})).expect("fill");+ app.run("paint.stroke", json!({"points": [[60, 60, 1], [240, 140, 1]], "size": 12, "hardness": 1.0, "color": "#ffffff"})).expect("line");+ app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).expect("colours");+ let brush = json!({"size": 30, "hardness": c.hardness, "pressureSize": c.pressure, "smoothing": {"amount": c.smoothing}});+ app.run("tools.setBrush", json!({ "brush": brush })).expect("brush");+ app.sync_views();+ app.ui.view.flip_horizontal = c.flip;+ }+ control(h, "ui.set", json!({"tool": "brush", "zoom": c.zoom, "center": [150, 100]}));+ // The smoothing tool option syncs on the first frame with the Brush: set it after.+ h.state_mut().session.tools.brush.smoothing.amount = c.smoothing;+ let canvas = |h: &mut Harness| {+ h.run_steps(3);+ let r = h.state().last_canvas_rect.shrink(4.0);+ let img = h.render().expect("render");+ let mut px = Vec::new();+ for y in r.top() as u32..(r.bottom() as u32).min(img.height()) {+ for x in r.left() as u32..(r.right() as u32).min(img.width()) {+ px.push(img.get_pixel(x, y).0);+ }+ }+ px+ };+ let before = canvas(h);+ let pressure = |t: f64| if c.pressure { 0.3 + 0.7 * t } else { 1.0 };+ control(h, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100, "pressure": pressure(0.0)}]}));+ let n = 14;+ let mut last = (100.0, 100.0);+ for i in 1..=n {+ let t = f64::from(i) / f64::from(n);+ last = (100.0 + 100.0 * t, 100.0 + 40.0 * (t * 6.0).sin());+ times.push(control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(t)}]})));+ }+ times.sort_by(f64::total_cmp);+ // Pointer move → stroke rendered → frame built (canvas refresh and upload included).+ eprintln!("{c:?}: move-to-frame median {:.2} ms, max {:.2} ms", times[times.len() / 2], times[times.len() - 1]);+ let drawing = canvas(h);+ let gpu = h.state().perf.gpu && !c.flip;+ control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]}));+ let done = canvas(h);+ (before, drawing, done, gpu)+}++fn max_diff(a: &[[u8; 4]], b: &[[u8; 4]]) -> u8 {+ assert_eq!(a.len(), b.len());+ a.iter().zip(b).flat_map(|(p, q)| (0..3).map(move |i| p[i].abs_diff(q[i]))).max().unwrap_or(0)+}++#[test]+fn the_canvas_shows_the_committed_stroke_while_it_is_drawn() {+ let Some(mut h) = harness() else { return };+ h.run_steps(4);+ let mut cases = Vec::new();+ for zoom in [0.5, 1.0, 4.0, 12.0] {+ for smoothing in [0.0, 0.1, 0.5] {+ cases.push(Case { zoom, smoothing, hardness: 0.0, depth: 8, pressure: false, flip: false });+ }+ }+ cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 1.0, depth: 8, pressure: false, flip: false });+ cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 16, pressure: false, flip: false });+ cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 8, pressure: true, flip: false });+ cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 8, pressure: false, flip: true });+ cases.push(Case { zoom: 12.0, smoothing: 0.5, hardness: 0.0, depth: 16, pressure: true, flip: true });+ let mut gpu_seen = false;+ for c in cases {+ let (before, drawing, done, gpu) = frames(&mut h, c);+ gpu_seen |= gpu;+ // The stroke is on screen while drawing (not a blank canvas compared with a blank one)…+ assert!(max_diff(&before, &drawing) > 100, "{c:?}: the stroke shows while drawing");+ // …and is exactly what release leaves there: nothing extra (no stand-in shape), nothing missing.+ let d = max_diff(&drawing, &done);+ assert!(d <= 1, "{c:?}: the canvas changed by {d}/255 on release");+ }+ if !gpu_seen {+ eprintln!("note: the GPU compositor fell back to the CPU for every case");+ }+}