diff --git a/crates/ui-egui/src/canvas/channel_view.rs b/crates/ui-egui/src/canvas/channel_view.rs index 6399ece211..83513cb43d 100644 --- a/crates/ui-egui/src/canvas/channel_view.rs +++ b/crates/ui-egui/src/canvas/channel_view.rs @@ -471,7 +471,7 @@ fn render_with_source( /// `r` of a one-channel surface sampled every `factor` px, mapped to colours row by row (in /// parallel off the web). -fn mask_px(s: &Surface, r: Rect, factor: u32, color: impl Fn(f32) -> Color32 + Sync) -> Vec { +pub(crate) fn mask_px(s: &Surface, r: Rect, factor: u32, color: impl Fn(f32) -> Color32 + Sync) -> Vec { let (w, h) = (r.width().div_ceil(factor) as usize, r.height().div_ceil(factor) as usize); let mut px = vec![Color32::TRANSPARENT; w * h]; let row = |y: usize, out: &mut [Color32]| { diff --git a/crates/ui-egui/src/canvas/raster_source.rs b/crates/ui-egui/src/canvas/raster_source.rs index 2bdedb0ac0..96831e1913 100644 --- a/crates/ui-egui/src/canvas/raster_source.rs +++ b/crates/ui-egui/src/canvas/raster_source.rs @@ -1,6 +1,6 @@ //! A document's canvas pictures as the framework's raster displays read them: [`PhotoComposite`], the composite with -//! the live preview and the colour management folded in, and [`ChannelOverlay`], the Channels panel's view, which a -//! second display draws over the composite or the GPU picture. +//! the live preview and the colour management folded in, and [`ChannelOverlay`], the Channels panel's view and the +//! Adjustment Brush's mask tint, which a second display draws over the composite or the GPU picture. use std::collections::VecDeque; use std::sync::Arc; @@ -24,6 +24,10 @@ const LOG_LEN: usize = 8; #[cfg(test)] mod tests; +#[cfg(test)] +#[path = "../tools/adjustment_brush_overlay_tests.rs"] +mod adjustment_brush_overlay_tests; + /// What a source's picture showed at one [`Revision`]: the state [`damage_since`] compares. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Shown { @@ -250,13 +254,61 @@ impl RasterSource for PhotoComposite<'_> { } } +/// The Adjustment Brush's Overlay (#12520): a magenta tint over what the active adjustment layer's mask reveals, +/// scaled by the mask value (white: the full tint, black: none). The tint's colour and opacity were not measured; +/// this is the layer mask rubylith's 50 %, in magenta. It shows while the Adjustment Brush is the tool and its +/// Overlay box is ticked, and only over an adjustment layer with a mask. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct MaskTint { + layer: photocraft_doc::LayerId, +} + +impl MaskTint { + const OPACITY: f32 = 0.5; + + /// The tint document `idx` shows; `None` while it shows none. + fn of(app: &PhotocraftApp, idx: usize) -> Option { + if app.ui.tool != crate::state::Tool::AdjustmentBrush || !app.ui.tool_options.adjustment_brush_overlay { + return None; + } + let st = app.session.documents().get(idx)?; + let layer = st.active_layer?; + let l = st.doc.layer(layer)?; + (matches!(l.content, photocraft_doc::LayerContent::Adjustment(_)) && l.mask.is_some()).then_some(MaskTint { layer }) + } + + /// Changes with the layer tinted, so another layer redraws everything. The constant ("masktint") keeps it apart + /// from a channel view's key alone. + fn key(&self) -> u64 { + 0x6d61_736b_7469_6e74 ^ self.layer.0.rotate_left(29) + } + + /// `px` (`r` of `doc` at `factor`, premultiplied; `None`: transparent) with the tint over it. `px` unchanged + /// when `doc` has no such layer or mask, as a preview of another layout may not. + fn over(&self, doc: &Document, r: DRect, factor: u32, px: Option>) -> Option> { + let Some(mask) = doc.layer(self.layer).and_then(|l| l.mask.as_ref()) else { return px }; + let tint = super::channel_view::mask_px(&mask.surface, r, factor, |g| { + let a = (g.clamp(0.0, 1.0) * Self::OPACITY * 255.0 + 0.5) as u8; + Color32::from_rgba_premultiplied(a, 0, a, a) + }); + Some(match px { + Some(px) => px.into_iter().zip(tint).map(|(under, over)| under.blend(over)).collect(), + None => tint, + }) + } +} + /// Document `idx`'s channel or mask view on one display (Quick Mask, a layer mask, alpha or single colour -/// channels), drawn by a second `RasterDisplay` over the canvas picture. It shows the live preview the canvas picture -/// shows, and also an adjustment's proxy preview, which the GPU picture draws and [`PhotoComposite`] does not. -/// Built once per pass, only while the view is not the plain composite. +/// channels), and the Adjustment Brush's mask tint over it, drawn by a second `RasterDisplay` over the canvas picture. +/// It shows the live preview the canvas picture shows, and also an adjustment's proxy preview, which the GPU picture +/// draws and [`PhotoComposite`] does not. Built once per pass, only while the view is not the plain composite or the +/// tint shows. pub(crate) struct ChannelOverlay<'a> { picture: Picture<'a>, - overlay: Overlay, + overlay: Option, + tint: Option, + /// The overlay's key with the tint's folded in. + key: u64, revision: Revision, log: Option<&'a SourceLog>, } @@ -265,28 +317,36 @@ pub(crate) struct ChannelOverlay<'a> { pub(crate) struct OverlayPrep { idx: usize, picture: CanvasPicture, - overlay: Overlay, + overlay: Option, + tint: Option, + key: u64, revision: Revision, log_key: (photocraft_doc::DocId, u32), } impl OverlayPrep { /// Document `idx`'s view on `output` (`None`: the main window's display); `None` when no such document is open or - /// it shows the plain composite. `live` is the gradient a tool proposes this pass. + /// it shows the plain composite and no mask tint. `live` is the gradient a tool proposes this pass. pub(crate) fn new(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, output: Option, live: LiveProposal<'_>) -> Option { let p = canvas_picture(app, ctx, idx, output, ProxyPreview::Preview, live)?; - let overlay = Overlay::of(app, idx, &p.doc, output)?; - let shown = OverlayShown { picture: Shown::of(&p, 0), view: overlay.key }; - let revision = shown.picture.revision(p.id, overlay.key); + let overlay = Overlay::of(app, idx, &p.doc, output); + let tint = MaskTint::of(app, idx); + if overlay.is_none() && tint.is_none() { + return None; + } + let key = overlay.as_ref().map_or(0, |o| o.key) ^ tint.map_or(0, |t| t.key()); + let shown = OverlayShown { picture: Shown::of(&p, 0), view: key }; + let revision = shown.picture.revision(p.id, key); let log_key = cache_key(p.id, output); app.raster_logs.entry(log_key).or_default().overlay.record(revision, shown); - Some(OverlayPrep { idx, picture: p, overlay, revision, log_key }) + Some(OverlayPrep { idx, picture: p, overlay, tint, key, revision, log_key }) } /// The source over `app`, the app this was prepared with. pub(crate) fn source(self, app: &PhotocraftApp) -> ChannelOverlay<'_> { let log = app.raster_logs.get(&self.log_key).map(|l| &l.overlay); - ChannelOverlay { picture: Picture::new(app, self.idx, self.picture, 0), overlay: self.overlay, revision: self.revision, log } + let picture = Picture::new(app, self.idx, self.picture, 0); + ChannelOverlay { picture, overlay: self.overlay, tint: self.tint, key: self.key, revision: self.revision, log } } } @@ -304,8 +364,8 @@ impl RasterSource for ChannelOverlay<'_> { return Some(PixelRect::default()); } let seen = self.log?.find(since)?; - // Another view, look or display transform draws everything differently. - if seen.view != self.overlay.key { + // Another view, look, display transform or tinted layer draws everything differently. + if seen.view != self.key { return None; } self.picture.damage(seen.picture) @@ -315,7 +375,12 @@ impl RasterSource for ChannelOverlay<'_> { let doc = &self.picture.doc; self.picture.read(region, factor, out, |area, factor| { let w = area.width().div_ceil(factor) as usize; - self.overlay.render(doc, area, factor).map(|px| (w, px)) + let px = self.overlay.as_ref().and_then(|o| o.render(doc, area, factor)); + let px = match &self.tint { + Some(tint) => tint.over(doc, area, factor, px), + None => px, + }; + px.map(|px| (w, px)) }); } } diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs index b82f1c9fc0..870ec61fef 100644 --- a/crates/ui-egui/src/tools/adjustment_brush.rs +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -151,8 +151,11 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo // Present but inert: what it does was not measured. let choose = tl!("Choose an object and have the adjustment applied to it"); IconButton::new(IconId::new("square-dashed-mouse-pointer")).label(choose).tooltip(choose).enabled(false).show(ui); - // Its tint over the painted mask is its own item (#12520). - Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)).label(tl!("Overlay").to_owned()).show(ui); + // On, the canvas tints what the active adjustment layer's mask reveals (`raster_source::MaskTint`, #12520). + Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)) + .label(tl!("Overlay").to_owned()) + .tooltip(tl!("Turn the overlay on or off to quickly see the affected areas").to_owned()) + .show(ui); Divider::vertical().show(ui); let mut alerts = Vec::new(); diff --git a/crates/ui-egui/src/tools/adjustment_brush_overlay_tests.rs b/crates/ui-egui/src/tools/adjustment_brush_overlay_tests.rs new file mode 100644 index 0000000000..595099aa78 --- /dev/null +++ b/crates/ui-egui/src/tools/adjustment_brush_overlay_tests.rs @@ -0,0 +1,131 @@ +//! #12520: the Adjustment Brush's Overlay box tints what the active adjustment layer's mask +//! reveals on the canvas, in magenta scaled by the mask value, and changes nothing in the document. + +use craft::ui::canvas::{PixelRect, RasterSource}; +use egui::{Color32, ColorImage, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::OverlayPrep; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A 200 x 200 document whose active layer is an adjustment layer made by one Adjustment Brush +/// stroke across row 60 (a 100 px soft round), over a grey painted layer. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + app.ui.tool = Tool::AdjustmentBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.sync_views(); + tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 60.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 160.0, y: 60.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 160.0, y: 60.0 }, Modifiers::NONE); + app.sync_views(); + assert!(matches!(active(&app).content, photocraft_doc::LayerContent::Adjustment(_)), "the stroke made an adjustment layer"); + app +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn mask_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + active(app).mask.as_ref().expect("a mask").surface.sample_channel(x, y, 0) +} + +fn prep(app: &mut PhotocraftApp) -> Option { + let ctx = app.ctx().clone(); + OverlayPrep::new(app, &ctx, 0, None, None) +} + +/// What the canvas's second display draws over pixel (x, y); `None` while it draws nothing. +fn over(app: &mut PhotocraftApp, x: i32, y: i32) -> Option { + let prep = prep(app)?; + let source = prep.source(app); + let mut out = ColorImage::filled([1, 1], Color32::TRANSPARENT); + source.read(PixelRect::new(x, y, x + 1, y + 1), 1, &mut out); + Some(out.pixels[0]) +} + +#[test] +fn the_box_is_off_with_its_tooltip_and_ticking_it_changes_nothing_in_the_document() { + let app = app(); + assert!(!app.ui.tool_options.adjustment_brush_overlay, "off by default"); + let before = app.session.active().map(|st| (st.revision, st.history.past_len())).unwrap(); + crate::theme::install_fonts(app.ctx()); + crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro()); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut Box| { + crate::panels::options_bar(app, ui); + }, + app, + ); + h.run_steps(4); + let tip = h.get_by_label("Overlay").accesskit_node().description().map(|d| d.to_string()); + assert_eq!(tip.as_deref(), Some("Turn the overlay on or off to quickly see the affected areas")); + h.get_by_label("Overlay").click(); + h.run_steps(4); + assert!(h.state().ui.tool_options.adjustment_brush_overlay, "ticked"); + let after = h.state().session.active().map(|st| (st.revision, st.history.past_len())).unwrap(); + assert_eq!(after, before, "no document change and no history state"); +} + +#[test] +fn ticked_it_tints_what_the_mask_reveals_in_magenta_scaled_by_the_mask_value() { + let mut app = app(); + app.ui.tool_options.adjustment_brush_overlay = true; + // The middle of the stroke, its soft edge, and a pixel the stroke never reached. + let (full, edge, none) = ((100, 60), (100, 100), (100, 180)); + assert!(mask_at(&app, full.0, full.1) > mask_at(&app, edge.0, edge.1), "the stroke's middle reveals more than its edge"); + assert!(mask_at(&app, edge.0, edge.1) > 0.0 && mask_at(&app, none.0, none.1) == 0.0); + let [full, edge, none] = [full, edge, none].map(|(x, y)| over(&mut app, x, y).expect("the tint draws")); + for c in [full, edge] { + assert!(c.r() == c.b() && c.g() == 0, "magenta: {c:?}"); + } + assert!(full.a() > edge.a() && edge.a() > 0, "scaled by the mask value: {full:?} over {edge:?}"); + assert!(full.a() < 255, "the picture still shows through: {full:?}"); + assert_eq!(none, Color32::TRANSPARENT, "nothing where the mask hides"); +} + +#[test] +fn unticked_another_layer_kind_or_another_tool_shows_no_tint() { + let mut app = app(); + assert!(prep(&mut app).is_none(), "unticked: the plain composite, nothing over it"); + app.ui.tool_options.adjustment_brush_overlay = true; + assert!(prep(&mut app).is_some(), "ticked"); + + app.ui.tool = Tool::Brush; + assert!(prep(&mut app).is_none(), "another tool"); + app.ui.tool = Tool::AdjustmentBrush; + + let doc = &app.session.active().unwrap().doc; + let pixel = doc.walk().into_iter().find(|(.., l)| matches!(l.content, photocraft_doc::LayerContent::Raster(_))).map(|(.., l)| l.id.0).unwrap(); + app.run("layer.select", json!({"layer": pixel})).unwrap(); + assert!(!matches!(active(&app).content, photocraft_doc::LayerContent::Adjustment(_))); + assert!(prep(&mut app).is_none(), "a pixel layer active"); +} + +#[test] +fn the_tint_shows_over_a_channel_view_and_ticking_it_redraws_that_view() { + let mut app = app(); + // Quick Mask over everything right of x = 100: a red rubylith there. + app.run("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap(); + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + let untinted = prep(&mut app).expect("the Quick Mask view").revision; + let ruby = over(&mut app, 150, 60).unwrap(); + assert!(ruby.r() > 0 && ruby.b() == 0, "the rubylith alone: {ruby:?}"); + + app.ui.tool_options.adjustment_brush_overlay = true; + let tinted = prep(&mut app).unwrap(); + assert_ne!(tinted.revision, untinted); + assert_eq!(tinted.source(&app).damage(untinted), None, "a texture of the untinted view is redrawn whole"); + let both = over(&mut app, 150, 60).unwrap(); + assert!(both.b() > 0 && both.r() > both.b(), "the tint over the rubylith: {both:?}"); + assert_eq!(over(&mut app, 150, 180).unwrap(), ruby, "only the rubylith where the mask hides"); +}