From f2ebff3de52f44957c6f01f2f5b8fd80acb8a493 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 22:00:37 +0100 Subject: [PATCH 1/9] fix(ui): centre size-changing filter previews on the CPU canvas A filter preview that changes the canvas's dimensions (Image > Image Rotation) kept the unpreviewed document on the CPU canvas (a mirrored or pixel-aspect view, no usable GPU, a GPU fallback), since drawing its texture over the document's bounds stretched it. The CPU canvas now draws it over its own area centred on the document's, as the GPU canvas centres it (preview_bounds, CpuTextures::bounds), with the drop shadow, checkerboard and rotated-view mapping on that area too. Such previews redraw whole and have no detail texture (both work in the document's pixels). Turning Preview off or cancelling restores the document. Fixes #8989. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 126 +++++++++++++++++++++++++---------- 1 file changed, 92 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dcbcade454b..d9db2650627 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -226,6 +226,10 @@ pub struct DetailTexture { pub(crate) struct CpuTextures { pub texture: egui::TextureId, pub scale: f32, + /// The document area the texture covers: the document's bounds, or for a filter preview that + /// changes the canvas's dimensions (Image › Rotation) its result centred on the document, as + /// the GPU canvas draws it. + pub bounds: DRect, /// The detail texture and the document area it covers (x0, y0, x1, y1 in document pixels). pub detail: Option<(egui::TextureId, [f32; 4])>, } @@ -1611,11 +1615,25 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, ensure_texture_in_view(app, ctx, idx, display, None).map(|t| (t.texture, t.scale)) } -/// Whether a filter preview of `preview` size shows a `doc` sized document reduced by `k` (its -/// proxy factor), so the CPU canvas can draw it over the document's bounds unstretched. -fn preview_fits(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> bool { +/// The document area a filter preview of `preview` size covers, for a `doc` sized document +/// previewed at proxy factor `k`: the document's bounds when it is the document's size (reduced by +/// `k`), else its own size (times `k`) centred on the document's centre, as the GPU canvas centres +/// a size-changing preview (Image › Rotation). +fn preview_bounds(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> DRect { let k = k.max(1); - doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height + let full = DRect::from_size(doc); + if doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height { + return full; + } + let side = |p: u32, d: u32| { + let covered = i64::from(p) * i64::from(k); + let x0 = (i64::from(d) - covered).div_euclid(2); + let clamp = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32; + (clamp(x0), clamp(x0 + covered)) + }; + let (x0, x1) = side(preview.width, doc.width); + let (y0, y1) = side(preview.height, doc.height); + DRect::new(x0, y0, x1, y1) } /// [`ensure_texture`], and for a canvas showing `view` of a document too large for one @@ -1637,15 +1655,18 @@ pub(crate) fn ensure_texture_in_view( // canvas (no usable GPU, a flipped or pixel-aspect-corrected view, a GPU fallback) showed the // document unfiltered. Its result is drawn here instead, as the channel views draw it. // A preview reduced for a zoomed-out view (a proxy, factor `k`) covers the whole document at - // its own size. One whose dimensions change otherwise (Image › Rotation) would be stretched - // over the document's bounds here, so the CPU canvas keeps the document for it, as before. + // its own size. One whose dimensions change otherwise (Image › Rotation) covers its own area, + // centred on the document's, as the GPU canvas draws it (`preview_bounds`). + let committed = app.session.documents().get(idx).map(|st| st.doc.bounds()).unwrap_or(doc.bounds()); + let mut bounds = committed; let mut reduced = false; if let Some((preview, key)) = filter_channel_preview(app, idx, ctx) { let k = app.filter_preview.as_ref().map_or(1, |p| p.key.k.max(1)); - if app.session.documents().get(idx).is_some_and(|st| preview_fits(st.doc.size, preview.size, k)) { - (doc, preview_key, reduced) = (preview, key, k > 1); - } + bounds = preview_bounds(committed.size(), preview.size, k); + (doc, preview_key, reduced) = (preview, key, k > 1); } + // Detail textures and partial redraws work in the document's own pixels. + let reduced = reduced || bounds != committed; let view = view.filter(|_| !reduced); // A flipped view draws a GPU machine's canvas through here: an adjustment dialog's preview of // a large document (taken by the GPU path) would cost a full-size CPU composite per change. @@ -1714,10 +1735,10 @@ pub(crate) fn ensure_texture_in_view( let texture = cache.texture.as_ref()?.id(); let scale = cache.scale; // Without a view (the Navigator's call) the views' detail textures stay as they are. - let Some(view) = view else { return Some(CpuTextures { texture, scale, detail: None }) }; + let Some(view) = view else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; let old = cache.detail.iter().position(|(k, _)| *k == view.key).map(|i| cache.detail.remove(i).1); let Some(plan) = detail_plan([doc.size.width, doc.size.height], texture_side(ctx), view.zoom, view.visible) else { - return Some(CpuTextures { texture, scale, detail: None }); + return Some(CpuTextures { texture, scale, bounds, detail: None }); }; let t0 = crate::gpu_canvas::now_ms(); let name = format!("canvas-detail-{}-{}", id.0, cache_key(id, output).1); @@ -1725,7 +1746,7 @@ pub(crate) fn ensure_texture_in_view( if detail.as_ref().is_some_and(|d| d.rendered) { app.perf.span("canvas detail", crate::gpu_canvas::now_ms() - t0); } - let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, detail: None }) }; + let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; detail.rendered = false; // Where its texels lie in the document: reduced texel t covers [t·W/w, (t+1)·W/w). let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); @@ -1737,7 +1758,7 @@ pub(crate) fn ensure_texture_in_view( if cache.detail.len() > MAX_DETAIL_VIEWS { cache.detail.remove(0); } - Some(CpuTextures { texture, scale, detail: Some(shown) }) + Some(CpuTextures { texture, scale, bounds, detail: Some(shown) }) } /// Most CPU canvas views of one document on one display that keep a detail texture. @@ -3596,23 +3617,26 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: paint_gpu_view(&painter, rect, params, &pattern); } else { app.navigator_gpu.remove(&doc.id); - if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { - painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0)); - } - let rotated = view.rotation.abs() > 0.05; - let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, &ctx), square)); // A document too large for one full-resolution texture also gets the part in view at // the screen's resolution, drawn over the reduced whole (#7568). let in_view = InView { visible: visible_doc_rect(&xf), zoom: view.zoom, key: egui::Id::new(("pc-canvas-detail", ctx.viewport_id(), idx, primary)).value() }; let textures = ensure_texture_in_view(app, &ctx, idx, output, Some(in_view)); let tex = textures.as_ref().map(|t| t.texture); - paint_cpu_document(&painter, &xf, doc.bounds(), rotated, checkerboard, tex); + // The area the image covers: a size-changing preview's own (Image › Rotation). + let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds); + if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { + let shadow_rect = if area == doc.bounds() { img_rect } else { xf.doc_rect(area) }; + painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(shadow_rect, 0)); + } + let rotated = view.rotation.abs() > 0.05; + let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, &ctx), square)); + paint_cpu_document(&painter, &xf, area, rotated, checkerboard, tex); if let Some((detail, area)) = textures.and_then(|t| t.detail) { paint_cpu_detail(&painter, &xf, doc.bounds(), rotated, checkerboard, detail, area); } for &c in &pattern { - paint_cpu_document(&painter, &pattern_xf(&xf, c, size), doc.bounds(), rotated, checkerboard, tex); + paint_cpu_document(&painter, &pattern_xf(&xf, c, size), area, rotated, checkerboard, tex); } } // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). @@ -4851,8 +4875,13 @@ fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on /// Textured document quad whose corners follow [`ViewXform`] (rotation + flip). fn paint_mapped_image(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, size: [f32; 2], tint: Color32) { - let [w, h] = size; - let pts = [xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)]; + paint_mapped_image_at(painter, xf, tex, uv, [0.0, 0.0], size, tint); +} + +/// [`paint_mapped_image`] over the `size` document area starting at `origin`. +fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)]; let mut mesh = Mesh::with_texture(tex); for i in 0..4 { @@ -4897,12 +4926,13 @@ fn paint_cpu_document( tex: Option, ) { let size = [bounds.width() as f32, bounds.height() as f32]; + let origin = [bounds.x0 as f32, bounds.y0 as f32]; let img_rect = xf.doc_rect(bounds); match checker { Some((checker_id, square)) => { if rotated { let tiles = vec2(size[0], size[1]) / (2.0 * square); - paint_mapped_image(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE); + paint_mapped_image_at(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), origin, size, Color32::WHITE); } else { let tiles = img_rect.size() / (2.0 * square); painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); @@ -4910,7 +4940,7 @@ fn paint_cpu_document( } None => { if rotated { - paint_mapped_quad(painter, xf, size, Color32::WHITE); + paint_mapped_quad(painter, xf, origin, size, Color32::WHITE); } else { painter.rect_filled(img_rect, 0.0, Color32::WHITE); } @@ -4918,7 +4948,7 @@ fn paint_cpu_document( } if let Some(tex) = tex { if rotated { - paint_mapped_image(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE); + paint_mapped_image_at(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), origin, size, Color32::WHITE); } else { let uv = if xf.flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; painter.image(tex, img_rect, uv, Color32::WHITE); @@ -4968,9 +4998,9 @@ fn paint_cpu_detail( quad(tex, [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]); } -fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, size: [f32; 2], color: Color32) { - let [w, h] = size; - let pts = vec![xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)]; +fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], size: [f32; 2], color: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = vec![xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); } @@ -6855,13 +6885,41 @@ mod tests { assert_eq!(shown, expected.pixels, "{size:?}: the canvas shows the preview"); assert_ne!(shown.first(), plain.first(), "{size:?}: not the unfiltered document"); } - // A preview that changes the canvas's dimensions (a 90° rotation) isn't stretched over the - // document's bounds: only one the document's size (reduced by its factor) is drawn. + // A preview that changes the canvas's dimensions covers its own area, centred on the + // document's (as the GPU canvas centres it), rather than being stretched over it. let size = |w, h| photocraft_geom::Size::new(w, h); - assert!(preview_fits(size(64, 32), size(64, 32), 1)); - assert!(preview_fits(size(2401, 2200), size(1201, 1100), 2), "a proxy"); - assert!(!preview_fits(size(64, 32), size(32, 64), 1), "rotated"); - assert!(!preview_fits(size(64, 32), size(80, 40), 1), "canvas grown"); + assert_eq!(preview_bounds(size(64, 32), size(64, 32), 1), DRect::new(0, 0, 64, 32)); + assert_eq!(preview_bounds(size(2401, 2200), size(1201, 1100), 2), DRect::new(0, 0, 2401, 2200), "a proxy"); + assert_eq!(preview_bounds(size(64, 32), size(32, 64), 1), DRect::new(16, -16, 48, 48), "rotated"); + assert_eq!(preview_bounds(size(64, 32), size(80, 40), 1), DRect::new(-8, -4, 72, 36), "canvas grown"); + assert_eq!(preview_bounds(size(4000, 2000), size(1000, 2000), 2), DRect::new(1000, -1000, 3000, 3000), "a rotated proxy"); + + // Image › Image Rotation › Arbitrary 90° on a 64×32 document: its 32×64 preview is drawn over + // the centred 32×64 area. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + let (size, _) = pixels(&ctx, t.texture); + assert_eq!(size, [32, 64], "the rotated preview's texture"); + assert_eq!(t.bounds, DRect::new(16, -16, 48, 48), "centred on the document"); + let centre = |r: DRect| (r.x0 + r.x1, r.y0 + r.y1); + assert_eq!(centre(t.bounds), centre(app.session.active().unwrap().doc.bounds()), "the same centre, so the view's pan holds"); + // Preview off, then Cancel: the document again, unchanged. + let revision = app.session.active().unwrap().revision; + app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap().fields.insert("__preview".into(), json!(false)); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "Preview off"); + crate::dialogs::cancel(&mut app, id).unwrap(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "after Cancel"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched"); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32)); } #[test] From 4df36ba4c4623a858fac8b5a0140c153e7c10f57 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 22:28:12 +0100 Subject: [PATCH 2/9] fix(ui): outline a size-changing preview's area with the Line border MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of #8994: with Canvas Border set to Line, the border stayed on the document's rectangle while a size-changing preview (a 90° rotation) drew over its own area. The canvas closure now returns the edge it drew (the preview's area on the CPU canvas), and the border outlines it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d9db2650627..e3c382b14eb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3539,6 +3539,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow; // Drop shadow, checkerboard, document image. let img_rect = xf.doc_rect(doc.bounds()); + // The canvas edge the Line border outlines: a size-changing preview's own (CPU canvas). + let mut edge_rect = img_rect; // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas // (whose edge blends into them) and without its shadow. let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output); @@ -3625,8 +3627,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let tex = textures.as_ref().map(|t| t.texture); // The area the image covers: a size-changing preview's own (Image › Rotation). let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds); + if area != doc.bounds() { + edge_rect = xf.doc_rect(area); + } if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { - let shadow_rect = if area == doc.bounds() { img_rect } else { xf.doc_rect(area) }; + let shadow_rect = edge_rect; painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(shadow_rect, 0)); } let rotated = view.rotation.abs() > 0.05; @@ -3801,7 +3806,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } } - (img_rect, beyond, layer_edges) + (beyond, layer_edges, edge_rect) }; let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &display_view, xf)) }; let img_rect = xf.doc_rect(doc.bounds()); @@ -4463,7 +4468,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } else { xf }; - let (img_rect, beyond, layer_edges) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf)); + let (beyond, layer_edges, edge_rect) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf)); // A Hand drag (the tool, Space or the middle button) keeps every overlay on screen, as in // Photoshop: the Pen path being drawn, paths, guides, grid, transform box (#6592). Only the // tool cursors below give way to the fist. @@ -4510,7 +4515,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview), // nor while the Crop tool hides everything outside its box (Show Cropped Area off). if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) { - painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside); + painter.rect_stroke(edge_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside); } crate::type_tool::draw_overlay(app, &painter, &xf); crate::transform_tool::draw_overlay(app, &painter, &xf); From f74229c64a077a2fd6abe4f1fa329ec09b9cbaeb Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 22:40:55 +0100 Subject: [PATCH 3/9] fix(ui): tile Pattern Preview copies by a size-changing preview's area MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of #8994: with View > Pattern Preview on, the CPU canvas placed the copies of a size-changing preview (a 90° rotation) at the document's size, leaving gaps and overlaps. They now tile the area the preview covers, from its origin. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e3c382b14eb..811a75e7037 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3640,8 +3640,16 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if let Some((detail, area)) = textures.and_then(|t| t.detail) { paint_cpu_detail(&painter, &xf, doc.bounds(), rotated, checkerboard, detail, area); } - for &c in &pattern { - paint_cpu_document(&painter, &pattern_xf(&xf, c, size), area, rotated, checkerboard, tex); + // Pattern Preview tiles what is shown: a size-changing preview's area, from its origin. + let (tile, copies) = if area == doc.bounds() || !app.ui.view.pattern_preview { + (size, pattern.clone()) + } else { + let tile = [area.width(), area.height()]; + let v = visible_doc_rect(&xf).translate(-area.x0, -area.y0); + (tile, crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), tile)) + }; + for &c in &copies { + paint_cpu_document(&painter, &pattern_xf(&xf, c, tile), area, rotated, checkerboard, tex); } } // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). From 34f031e313cec269cc36d6a769f8e8b6895a0d1d Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Sat, 24 Oct 2026 14:52:03 +0100 Subject: [PATCH 4/9] fix(ui): draw a channel overlay over a size-changing preview's area The overlay is rendered from the live preview, but the CPU canvas drew it over the document's bounds, stretching a rotated preview's overlay. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 65 +++++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index bb7ca02656d..8400f644617 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3609,6 +3609,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let img_rect = xf.doc_rect(doc.bounds()); // The canvas edge the Line border outlines: a size-changing preview's own (CPU canvas). let mut edge_rect = img_rect; + // The document area the image is drawn over: a size-changing preview's own on the CPU + // canvas (Image › Rotation). Overlays drawn from the same preview follow it. + let mut shown_area = doc.bounds(); // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas // (whose edge blends into them) and without its shadow. let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output); @@ -3695,6 +3698,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let tex = textures.as_ref().map(|t| t.texture); // The area the image covers: a size-changing preview's own (Image › Rotation). let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds); + shown_area = area; if area != doc.bounds() { edge_rect = xf.doc_rect(area); } @@ -3725,18 +3729,21 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) { + // Rendered from the live preview, so over the area the preview is shown in. + let a = shown_area; if view.rotation.abs() > 0.05 { - paint_mapped_image( + paint_mapped_image_at( &painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), - [doc.size.width as f32, doc.size.height as f32], + [a.x0 as f32, a.y0 as f32], + [a.width() as f32, a.height() as f32], Color32::WHITE, ); } else { let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, img_rect, uv, Color32::WHITE); + painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE); } } crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); @@ -4962,12 +4969,7 @@ fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y]; } -/// Textured document quad whose corners follow [`ViewXform`] (rotation + flip). -fn paint_mapped_image(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, size: [f32; 2], tint: Color32) { - paint_mapped_image_at(painter, xf, tex, uv, [0.0, 0.0], size, tint); -} - -/// [`paint_mapped_image`] over the `size` document area starting at `origin`. +/// A texture mapped over the `size` document area starting at `origin` (follows a rotated view). fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { let ([x, y], [w, h]) = (origin, size); let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; @@ -7019,6 +7021,51 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32)); } + /// A channel overlay drawn from a size-changing preview covers the preview's own area, as the + /// image does, not the document's: a 90° rotation of a 64×32 document shows a 32×64 overlay. + #[test] + fn a_channel_overlay_follows_a_size_changing_preview() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + for rotation in [0.0f32, 30.0] { + let view = View { zoom: 4.0, center: [32.0, 16.0], rotation, ..app.ui.views[0].clone() }; + let mut output = ctx.run_ui(Default::default(), |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), view.clone(), true); + }); + output.textures_delta.clear(); + let overlay = crate::channel_view::ensure(&mut app, &ctx, 0).expect("the channel overlay"); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id == overlay => Some(m.clone()), + _ => None, + }) + .expect("the overlay is painted"); + // The quad's sides, in screen points: the two shortest distances from a corner (the + // third is the diagonal; a rotated view turns the quad, not its side lengths). + let v: Vec = mesh.vertices.iter().map(|v| v.pos).collect(); + let mut d: Vec = v[1..4].iter().map(|p| v[0].distance(*p)).collect(); + d.sort_by(f32::total_cmp); + let (short, long) = (d[0], d[1]); + // Which side is the width: the one along the view's x axis turned by the rotation. + let along = |p: Pos2| { + let r = rotation.to_radians(); + ((p - v[0]).x * r.cos() + (p - v[0]).y * r.sin()).abs() + }; + let width = v[1..4].iter().map(|p| along(*p)).fold(0.0f32, f32::max); + assert!((long / short - 2.0).abs() < 0.01, "rotation {rotation}: sides {short}×{long}, the preview's 1:2"); + assert!((width - short).abs() < 0.5, "rotation {rotation}: the short side ({short}) runs across the view (width {width})"); + } + } + #[test] fn inline_filter_preview_is_composited_and_recorded_once() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 487e18d72672ab6ed06bb13353fdf83632352884 Mon Sep 17 00:00:00 2001 From: Ivan Date: Sun, 25 Oct 2026 00:08:14 +0300 Subject: [PATCH 5/9] fix(cli): help after a mistake, and mcp/serve option notes in --help (#7071) The review round of the #7071 stack, which #9167 merged without (it took the pre-review heads): - A bare --help or -h before `--` is help after any parse error, not only after a missing value: `mcp stray.psd --help` and `serve --port abc --port 1 -h` print the subcommand's help. - mcp and serve --help carry #8035's rules: what the automation roots grant, that bridge roots are refused, and that the token flags need --bridge or --port (or PHOTOCRAFT_CONTROL_PORT). - check_server takes the subcommand and whether a transport is set; the bridge-roots check moves next to the other mcp checks. - The server tests match clap's "a value is required for" text, and mcp.md in the book and docs names PHOTOCRAFT_CONTROL_PORT. Co-authored-by: Claude Opus 5.5 --- apps/photocraft-cli/src/args.rs | 56 ++++++++++++++++------------- apps/photocraft-cli/tests/it/cli.rs | 14 ++++++-- book/src/automation/mcp.md | 5 +-- docs/mcp.md | 8 ++--- 4 files changed, 49 insertions(+), 34 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 1a1aa4833e4..d0e299cfde9 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -199,6 +199,10 @@ pub(crate) struct CommandsArgs { } /// Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control `) +/// +/// Headless: each automation root grants that direction of file access; an omitted root denies it. +/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop +/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT). #[derive(Args)] pub(crate) struct McpArgs { /// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means @@ -219,7 +223,8 @@ pub(crate) struct McpArgs { /// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute, /// jobs.list/cancel, engine.commands, /// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, -/// session.list, batch, methods (docs/control-protocol.md#headless-server). +/// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require +/// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token. #[derive(Args)] pub(crate) struct ServeArgs { /// Listen on 127.0.0.1: instead of stdio @@ -326,16 +331,16 @@ fn steps(m: &ArgMatches) -> Vec { /// Parse the arguments (without the binary name). clap reads them as `OsString`s: a path need not /// be valid Unicode (#1108), text must. A flag left out falls back to its environment variable, -/// unless that is empty, and a bad value from one is a usage error naming the variable (#2491). +/// unless that is empty, and a bad value from one is a usage error naming the variable (#2491). A +/// bare `--help` or `-h` is help even after a mistake on the same line (`--out --help`, `mcp +/// stray.psd --help`): clap reports the mistake first. pub(crate) fn parse(args: &[OsString]) -> Result { let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset)); let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned()); let matches = match cmd.try_get_matches_from_mut(argv) { - // Help where a flag's value should be (`--out --help`) is still help: clap reports the - // missing value first. - Err(e) if e.kind() == ErrorKind::InvalidValue && args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => { + Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => { let help = [OsString::from("photocraft-cli"), args.first().cloned().unwrap_or_default(), OsString::from("--help")]; - return Err(Cli::command().try_get_matches_from(help).err().unwrap_or(e)); + return Err(cmd.try_get_matches_from_mut(help).err().unwrap_or(e)); } matches => matches.map_err(|e| name_env_vars(e, &cmd, args))?, }; @@ -359,43 +364,44 @@ pub(crate) fn parse(args: &[OsString]) -> Result { conflict(sub, m, "control_token", "control_token_file")?; } // The roots are the headless engine's: the variable switching to the bridge would - // drop them. + // drop them, and the error names it. if a.bridge_from_env { conflict(sub, m, "automation_read_root", "bridge")?; conflict(sub, m, "automation_write_root", "bridge")?; } + // With --bridge they are the desktop process's to set: accepting them here promises + // authority the bridge can't give (#8035). + if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) { + return Err(sub.error(ErrorKind::ArgumentConflict, BRIDGE_ROOTS)); + } + check_server(sub, m, a.bridge.is_some(), "--bridge")?; } - check_server(cmd.find_subcommand_mut(name), m, "bridge")?; } (Command::Serve(a), Some((name, m))) => { a.port_from_env = from_env(m, "port"); - // Only the TCP server reads a token, so a stale exported pair doesn't stop stdio. - if a.port.is_some() - && let Some(sub) = cmd.find_subcommand_mut(name) - { - conflict(sub, m, "control_token", "control_token_file")?; + if let Some(sub) = cmd.find_subcommand_mut(name) { + // Only the TCP server reads a token, so a stale exported pair doesn't stop stdio. + if a.port.is_some() { + conflict(sub, m, "control_token", "control_token_file")?; + } + check_server(sub, m, a.port.is_some(), "--port")?; } - check_server(cmd.find_subcommand_mut(name), m, "port")?; } _ => {} } Ok(cli) } +const BRIDGE_ROOTS: &str = "configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode"; + /// Refuse `mcp` and `serve` launch options that would otherwise be silently ignored (#8035): a -/// token flag without the bridge or port that reads it (flag or variable; a token variable alone -/// may be a stale export), and bridge roots, which belong to the desktop process: accepting them -/// here promises authority the bridge cannot set. -fn check_server(sub: Option<&mut clap::Command>, m: &ArgMatches, transport: &str) -> Result<(), clap::Error> { - let Some(sub) = sub else { return Ok(()) }; +/// token flag without the bridge or port that reads it (as a flag or its variable). A token +/// variable alone may be a stale export, so it isn't refused. +fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &str) -> Result<(), clap::Error> { for (id, flag) in [("control_token", "--control-token"), ("control_token_file", "--control-token-file")] { - if m.value_source(id) == Some(ValueSource::CommandLine) && !m.contains_id(transport) { - return Err(sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires --{transport}"))); + if m.value_source(id) == Some(ValueSource::CommandLine) && !has_transport { + return Err(sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires {transport}"))); } } - if transport == "bridge" && m.contains_id(transport) && (m.contains_id("automation_read_root") || m.contains_id("automation_write_root")) { - let message = "configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode"; - return Err(sub.error(ErrorKind::ArgumentConflict, message)); - } Ok(()) } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 5d876513855..68547951ef1 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -74,7 +74,15 @@ fn every_subcommand_answers_help() { } } // Help where a flag's value should be is still help, not a missing value or a file named `-h`. - for args in [&["run", "x.png", "--out", "--help"][..], &["commands", "--filter", "-h"], &["mcp", "--bridge", "-h"], &["serve", "--port", "--help"]] { + // So is help after another mistake. + for args in [ + &["run", "x.png", "--out", "--help"][..], + &["commands", "--filter", "-h"], + &["mcp", "--bridge", "-h"], + &["serve", "--port", "--help"], + &["mcp", "stray.psd", "--help"], + &["serve", "--port", "abc", "--port", "1", "-h"], + ] { let o = bin().current_dir(&d).args(args).stdin(Stdio::null()).output().unwrap(); assert_eq!(o.status.code(), Some(0), "{args:?}: {}", String::from_utf8_lossy(&o.stderr)); assert!(String::from_utf8_lossy(&o.stdout).contains(&format!("photocraft-cli {}", args[0])), "{args:?}"); @@ -161,14 +169,14 @@ fn server_modes_reject_ignored_or_conflicting_options() { } for flag in ["--automation-read-root", "--automation-write-root"] { server_usage_error(&[sub, flag, ".", flag, "."], "cannot be used multiple times"); - server_usage_error(&[sub, &format!("{flag}=")], &format!("'{flag} ")); + server_usage_error(&[sub, &format!("{flag}=")], &format!("a value is required for '{flag} ")); server_usage_error(&[sub, flag, "--automation-write-root", "."], &format!("a value is required for '{flag} ")); } let transport = if sub == "mcp" { "--bridge" } else { "--port" }; for flag in [transport, "--control-token", "--control-token-file"] { // Valid values, so the repeat is what is refused (a transport value is parsed first). server_usage_error(&[sub, flag, "7878", &format!("{flag}=7879")], "cannot be used multiple times"); - server_usage_error(&[sub, flag, ""], &format!("'{flag} ")); + server_usage_error(&[sub, flag, ""], &format!("for '{flag} ")); } server_usage_error(&[sub, transport, "7878", "--control-token", "unused", "--control-token-file", "unused"], "cannot be used with"); } diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 9b2e8d7c52a..e9e9521ea6b 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -23,8 +23,9 @@ photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file /private/path/co Use absolute root paths in MCP client configurations, since a relative root is resolved from the client's launch directory. In bridge mode the roots are configured on the desktop app, and root flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and -`--control-token-file` flags require `--bridge` and are mutually exclusive; bridge credentials can -also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option +`--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually +exclusive; bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or +`PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option except `--help`/`-h` takes one non-empty value and cannot be repeated. Stray positional arguments, missing values and options for the wrong mode are usage errors (exit 2) reported on stderr before the server starts. diff --git a/docs/mcp.md b/docs/mcp.md index f5c0b24e11a..75cacd6e419 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -60,14 +60,14 @@ described in [development.md](development.md). UI tools require a running deskto Use absolute root paths in MCP client configurations, since a relative root is resolved from the client's launch directory. In bridge mode, configure roots on the **desktop app**; root flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and -`--control-token-file` flags require `--bridge` and are mutually exclusive. Bridge credentials -can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. +`--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually +exclusive. Bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. MCP and `serve` launch options (all but `--help`/`-h`) take one non-empty value each and cannot be repeated. Missing values, stray positional arguments and options for the wrong mode are usage errors (exit 2), reported on stderr before the server starts; stdout stays available for -protocol messages. For `serve`, explicit credential flags require `--port`; stdio needs no -control token. +protocol messages. For `serve`, explicit credential flags require `--port` (or +`PHOTOCRAFT_CONTROL_PORT`); stdio needs no control token. ## Tools and resources From 6719f1813e84e96129fc31676cc945d51be0e736 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Sun, 25 Oct 2026 05:13:24 +0800 Subject: [PATCH 6/9] Segmentation: anti-aliasing the full-resolution mask skips runs far from its edge (#8554) * Segmentation: anti-aliasing the full-resolution mask skips runs far from its edge Select Subject, Object Selection and Select Sky finish with antialias_u8 over the whole full-resolution mask, which read nine neighbours through a bounds-checked closure for every pixel: 171-185 ms of an 800 ms first Select Subject on 24 MP (ubuntu-latest, 4 cores). A run of 64 pixels whose 3x3 neighbourhood holds one value has no edge pixel, so it is only compared now; other runs take the per-pixel rule as before. The output is byte for byte the same, checked against the per-pixel rule over widths around the run length, single rows and columns, discs, noise and stripes. Part of #211. * Segmentation: the mask's anti-aliasing and its test share one per-pixel rule The 3x3 rule moves into edge_value, which antialias_u8 calls for spans that are not uniform and the test calls for every pixel, so the test checks only that skipping never misses an edge pixel instead of keeping a second copy of the rule. A small case pins the rule's values. --- crates/algo/src/segment/mod.rs | 52 +++++++++++++++++++++++--------- crates/algo/src/segment/tests.rs | 44 +++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 15 deletions(-) diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rs index b30ce909b75..f586453db4a 100644 --- a/crates/algo/src/segment/mod.rs +++ b/crates/algo/src/segment/mod.rs @@ -524,23 +524,24 @@ fn components4(mask: &[bool], w: usize, h: usize) -> (Vec, Vec) { /// rule as the magic wand's anti-aliasing). pub fn antialias_u8(mask: &mut [u8], w: usize, h: usize) { let src = mask.to_vec(); - let at = |x: i32, y: i32, v: u8| if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { v } else { src[y as usize * w + x as usize] }; + // A span whose 3×3 neighbourhood holds one value has no edge pixel, so it is only compared: + // most of a full-resolution mask is far from its boundary. 64 pixels keep the three row + // compares cheap per pixel, and a span that does reach the boundary costs few extra pixels. + const SPAN: usize = 64; + let uniform = |y: usize, x0: usize, x1: usize| { + let (a, b, v) = (x0.saturating_sub(1), (x1 + 1).min(w), src[y * w + x0]); + (y.saturating_sub(1)..(y + 2).min(h)).all(|ny| src[ny * w + a..ny * w + b].iter().all(|n| *n == v)) + }; let row = |y: usize, out: &mut [u8]| { - for (x, o) in out.iter_mut().enumerate() { - let v = src[y * w + x]; - let mut sum = 0u32; - let mut edge = false; - for dy in -1..=1 { - for dx in -1..=1 { - let n = at(x as i32 + dx, y as i32 + dy, v); - edge |= n != v; - sum += n as u32; - } + for (c, span) in out.chunks_mut(SPAN).enumerate() { + let x0 = c * SPAN; + if uniform(y, x0, x0 + span.len()) { + continue; } - if edge { - let avg = sum as f32 / (9.0 * 255.0); - let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg }; - *o = (f * 255.0).round() as u8; + for (i, o) in span.iter_mut().enumerate() { + if let Some(v) = edge_value(&src, w, h, x0 + i, y) { + *o = v; + } } } }; @@ -553,6 +554,27 @@ pub fn antialias_u8(mask: &mut [u8], w: usize, h: usize) { mask.chunks_mut(w).enumerate().for_each(|(y, r)| row(y, r)); } +/// The anti-aliased value of pixel `(x, y)` of `src` (`w` × `h`), or `None` when every neighbour +/// in its 3×3 neighbourhood has its value (neighbours outside the mask count as the pixel itself). +fn edge_value(src: &[u8], w: usize, h: usize, x: usize, y: usize) -> Option { + let v = src[y * w + x]; + let mut sum = 0u32; + let mut edge = false; + for dy in -1..=1 { + for dx in -1..=1 { + let (nx, ny) = (x as i32 + dx, y as i32 + dy); + let n = if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { v } else { src[ny as usize * w + nx as usize] }; + edge |= n != v; + sum += n as u32; + } + } + edge.then(|| { + let avg = sum as f32 / (9.0 * 255.0); + let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg }; + (f * 255.0).round() as u8 + }) +} + /// Shrinks a region's box to its non-zero pixels (`None` if empty). pub fn trim_region(r: Region) -> Option { let w = r.bbox.width() as usize; diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rs index 165272231b5..135c47b2231 100644 --- a/crates/algo/src/segment/tests.rs +++ b/crates/algo/src/segment/tests.rs @@ -903,6 +903,50 @@ fn select_subject_leaves_a_background_coloured_gap_open() { assert!(v > 0.9, "IoU {v}"); } +#[test] +fn antialias_blends_edge_pixels_with_their_neighbourhood() { + // A lone selected pixel keeps most of its coverage and its neighbours get half of a ninth; + // neighbours outside the mask count as the pixel itself. + let mut m = vec![0, 0, 0, 0, 255, 0, 0, 0, 0]; + antialias_u8(&mut m, 3, 3); + assert_eq!(m, [14, 14, 14, 14, 142, 14, 14, 14, 14]); +} + +#[test] +fn antialias_skips_only_spans_without_edge_pixels() { + // Every pixel through the per-pixel rule, no span skipped. + let every_pixel = |mask: &mut [u8], w: usize, h: usize| { + let src = mask.to_vec(); + for y in 0..h { + for x in 0..w { + if let Some(v) = edge_value(&src, w, h, x, y) { + mask[y * w + x] = v; + } + } + } + }; + let mut rng = Rng::new(11); + // Widths around the 64-pixel span, single rows and columns, discs, noise and stripes. + for (w, h) in [(1usize, 1usize), (1, 9), (9, 1), (63, 4), (64, 3), (65, 5), (127, 2), (129, 70), (300, 200)] { + let (cx, cy, r) = (w as f32 * 0.6, h as f32 * 0.4, w.min(h) as f32 / 3.0); + let masks: Vec> = vec![ + vec![255; w * h], + vec![0; w * h], + (0..w * h).map(|i| if ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r { 255 } else { 0 }).collect(), + (0..w * h).map(|_| if rng.f32() < 0.02 { 255 } else { 0 }).collect(), + (0..w * h).map(|_| if rng.f32() < 0.5 { 255 } else { 0 }).collect(), + (0..w * h).map(|i| if (i % w) / 64 % 2 == 0 { 255 } else { 0 }).collect(), + (0..w * h).map(|i| if i % w == w - 1 || i / w == h / 2 { 255 } else { 0 }).collect(), + ]; + for (k, m) in masks.into_iter().enumerate() { + let (mut fast, mut slow) = (m.clone(), m); + antialias_u8(&mut fast, w, h); + every_pixel(&mut slow, w, h); + assert!(fast == slow, "{w}×{h} mask {k}"); + } + } +} + /// Timing on a 6 MP figure, for before/after numbers (`cargo test --release -- --ignored select_subject_timing --nocapture`). #[test] #[ignore = "timing only"] From 9c56f5b9ca9898c53ec446da9ce86ef0ca1ab531 Mon Sep 17 00:00:00 2001 From: Ivan Date: Sun, 25 Oct 2026 00:16:23 +0300 Subject: [PATCH 7/9] refactor(cli): type the mcp/serve option refusals (#7071) The checks parse() runs after clap built their messages from a const and two format! calls. ServerOptionError holds them as thiserror variants beside ValueError, each with the clap ErrorKind it reports as: the PHOTOCRAFT_CONTROL_PORT host:port refusal, bridge roots, and a token flag without its transport. The output is unchanged. Co-authored-by: Claude Opus 5.5 --- apps/photocraft-cli/src/args.rs | 47 ++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index d0e299cfde9..91b99ef33b9 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -257,6 +257,34 @@ enum ValueError { Bridge, } +/// Why `parse` refuses `mcp` or `serve` options clap accepted: clap prints it as a usage error +/// (exit 2). +#[derive(Debug, thiserror::Error)] +enum ServerOptionError { + /// PHOTOCRAFT_CONTROL_PORT holds a port, as for the desktop app's --control: only the flag + /// takes host:port. + #[error("invalid value '{0}' for 'PHOTOCRAFT_CONTROL_PORT': {bridge}", bridge = ValueError::Bridge)] + BridgeVar(String), + /// With --bridge the roots are the desktop process's to set: accepting them here promises + /// authority the bridge can't give (#8035). + #[error("configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode")] + BridgeRoots, + /// A token flag without the bridge or port that reads it would be ignored (#8035). + #[error("{flag} requires {transport}")] + NeedsTransport { flag: &'static str, transport: &'static str }, +} + +impl ServerOptionError { + fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { + let kind = match self { + Self::BridgeVar(_) => ErrorKind::ValueValidation, + Self::BridgeRoots => ErrorKind::ArgumentConflict, + Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument, + }; + cmd.error(kind, self) + } +} + fn tga_bits(s: &str) -> Result { s.parse().ok().and_then(TgaBits::from_bits).ok_or(ValueError::TgaBits) } @@ -350,12 +378,10 @@ pub(crate) fn parse(args: &[OsString]) -> Result { (Command::Run(r), Some((_, m))) => r.steps = steps(m), (Command::Mcp(a), Some((name, m))) => { a.bridge_from_env = from_env(m, "bridge"); - // The variable holds a port, as for the desktop app's --control: only the flag takes - // host:port, which `bridge` lets through. if a.bridge_from_env && let Some(Bridge::Addr(v)) = &a.bridge { - return Err(cmd.error(ErrorKind::ValueValidation, format!("invalid value '{v}' for 'PHOTOCRAFT_CONTROL_PORT': {}", ValueError::Bridge))); + return Err(ServerOptionError::BridgeVar(v.clone()).into_clap(&mut cmd)); } if let Some(sub) = cmd.find_subcommand_mut(name) { // Only the bridge reads a token, so a stale exported pair doesn't stop a headless @@ -369,10 +395,8 @@ pub(crate) fn parse(args: &[OsString]) -> Result { conflict(sub, m, "automation_read_root", "bridge")?; conflict(sub, m, "automation_write_root", "bridge")?; } - // With --bridge they are the desktop process's to set: accepting them here promises - // authority the bridge can't give (#8035). if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) { - return Err(sub.error(ErrorKind::ArgumentConflict, BRIDGE_ROOTS)); + return Err(ServerOptionError::BridgeRoots.into_clap(sub)); } check_server(sub, m, a.bridge.is_some(), "--bridge")?; } @@ -392,15 +416,12 @@ pub(crate) fn parse(args: &[OsString]) -> Result { Ok(cli) } -const BRIDGE_ROOTS: &str = "configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode"; - -/// Refuse `mcp` and `serve` launch options that would otherwise be silently ignored (#8035): a -/// token flag without the bridge or port that reads it (as a flag or its variable). A token -/// variable alone may be a stale export, so it isn't refused. -fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &str) -> Result<(), clap::Error> { +/// Refuse a token flag without the bridge or port that reads it (as a flag or its variable). A +/// token variable alone may be a stale export, so it isn't refused. +fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &'static str) -> Result<(), clap::Error> { for (id, flag) in [("control_token", "--control-token"), ("control_token_file", "--control-token-file")] { if m.value_source(id) == Some(ValueSource::CommandLine) && !has_transport { - return Err(sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires {transport}"))); + return Err(ServerOptionError::NeedsTransport { flag, transport }.into_clap(sub)); } } Ok(()) From fa253cb3726ecef65214cb27944efb29452c545d Mon Sep 17 00:00:00 2001 From: denstu473 <63150090+denstu473@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:54:55 +0200 Subject: [PATCH 8/9] fix(ui): keep repeated Tab presses in text editing (#8889) (#9030) egui queues focus navigation before the type tool consumes Tab. Removing the key event leaves that navigation queued, allowing menu focus to block later Tabs and ordinary text input. Cancel the queued move when inserting a tab. Add a full-app input regression that fails on the second Tab before the fix and verifies three Tab presses, caret positions, and subsequent typing. --- crates/ui-egui/src/type_tool.rs | 7 ++++++- crates/ui-egui/src/type_tool_tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index e8fdbe95d35..2566454754d 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1126,7 +1126,12 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { Key::Enter if m.command => commit_with(app, *m), Key::Enter => insert(app, "\n"), // Photoshop types a tab character; layout advances it to the next tab stop. - Key::Tab if !m.command && !m.alt && !m.shift => insert(app, "\t"), + Key::Tab if !m.command && !m.alt && !m.shift => { + // egui queues focus navigation before this handler runs; consuming the + // key alone would let the menu bar take focus after the first tab (#8889). + ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + insert(app, "\t"); + } Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), // The Type Mask tools: Escape always cancels, leaving the selection as it was. Key::Escape if ed.mask => cancel(app), diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index da8915acedb..bbb0d0679cd 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -969,6 +969,33 @@ fn tab_while_typing_inserts_a_tab() { assert_eq!(h.state().ui.panels.dock, panels, "the panels stay as they were"); } +/// #8889: separate Tab presses must keep inserting text with the menu bar and panels present. +#[test] +fn repeated_tabs_while_typing_keep_keyboard_focus_on_the_canvas() { + let mut app = new_app(); + let id = LayerId(app.run("type.create", json!({"text": "HOHO", "size": 60, "x": 300, "y": 420})).unwrap()["layer"].as_u64().unwrap()); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(32).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let p = glyph(&mut h, id, 1, 0.2); + click(&mut h, p); + assert_eq!(selection(&h), (1, 1)); + let panels = h.state().ui.panels.dock; + for (expected, caret) in [("H\tOHO", 2), ("H\t\tOHO", 3), ("H\t\t\tOHO", 4)] { + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(text(h.state(), id).text, expected); + assert_eq!(selection(&h), (caret, caret)); + assert!(h.state().ui.text_edit.is_some(), "still editing"); + assert_eq!(h.state().ui.panels.dock, panels, "the panels stay as they were"); + } + h.event(egui::Event::Text("typed".into())); + h.run_steps(2); + assert_eq!(text(h.state(), id).text, "H\t\t\ttypedOHO"); +} + #[test] fn text_color_dialog_edits_only_the_selected_range_and_cancel_is_inert() { let mut app = new_app(); From 155d1eac3675d6dff72fe8f6234cfc5f8c2bd948 Mon Sep 17 00:00:00 2001 From: bfenty Date: Sat, 24 Oct 2026 16:55:20 -0500 Subject: [PATCH 9/9] ui: highlight menu rows while dragging with the button held (#9112) Response::hovered is false while the primary button is down, so a press-drag through a menu never moved the highlight and it desynced from the cursor. Hit-test with contains_pointer, which keeps answering while a button is held. Closes #8887 Co-authored-by: bfenty <1398236+bfenty@users.noreply.github.com> --- crates/ui-egui/src/menu_nav.rs | 6 +++++- crates/ui-egui/src/menu_nav_tests.rs | 31 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menu_nav.rs b/crates/ui-egui/src/menu_nav.rs index c9aedd77d74..93b29ce7d91 100644 --- a/crates/ui-egui/src/menu_nav.rs +++ b/crates/ui-egui/src/menu_nav.rs @@ -246,7 +246,11 @@ impl Nav { fn after_row(&mut self, level: usize, i: usize, lit: bool, r: &egui::Response) { let moved = r.ctx.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO); let follow = self.follow == Some(level); - if (moved || follow) && r.hovered() && !lit { + // `hovered` is false while the primary button is held (egui attributes the pointer to + // the pressed widget), so a press-drag through the items never highlighted anything + // (#8887). `contains_pointer` keeps answering while a button is down. + let over = r.contains_pointer(); + if (moved || follow) && over && !lit { if follow { self.follow = None; } diff --git a/crates/ui-egui/src/menu_nav_tests.rs b/crates/ui-egui/src/menu_nav_tests.rs index fcf06ed0282..87c5498f7da 100644 --- a/crates/ui-egui/src/menu_nav_tests.rs +++ b/crates/ui-egui/src/menu_nav_tests.rs @@ -727,6 +727,37 @@ fn press_drag_release_reaches_other_menus_and_submenus() { assert!(Nav::current(&h.ctx).rows.first().is_none_or(|r| r.is_empty()), "and closed the menus"); } +/// Press-and-hold a menu title and drag through the items: the highlight follows the +/// pointer the whole way, down and back up, without lagging or dropping (#8887). +#[test] +fn press_drag_highlight_follows_the_pointer() { + use egui::{Modifiers, PointerButton}; + let mut h = harness((1280.0, 720.0, 1.0)); + let title = h.get_by_label("View").rect().center(); + h.event(egui::Event::PointerMoved(title)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: title, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(2); + let rows = Nav::current(&h.ctx).rows.first().cloned().unwrap_or_default(); + assert!(rows.len() > 4, "the View menu has rows to drag through"); + // Drag down through the first rows, one at a time, still holding the button. + for i in 1..=4 { + let row = rows.get(i).expect("row exists"); + h.event(egui::Event::PointerMoved(row.rect.center())); + h.run_steps(1); + assert_eq!(Nav::current(&h.ctx).highlighted(0), Some(i), "holding and dragging onto row {i} highlights it"); + } + // Back up the way a user overshooting and correcting does. + for i in (1..=3).rev() { + let row = rows.get(i).unwrap(); + h.event(egui::Event::PointerMoved(row.rect.center())); + h.run_steps(1); + assert_eq!(Nav::current(&h.ctx).highlighted(0), Some(i), "dragging back up to row {i} highlights it"); + } + h.event(egui::Event::PointerButton { pos: rows.get(1).unwrap().rect.center(), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + /// A menu bar whose frames are `dt` seconds apart, as with a real pointer sending moves. fn harness_dt(dt: f32) -> Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1280.0, 720.0)).with_step_dt(dt).build_ui_state(