diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 186b42b061..f479e67510 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -101,6 +101,7 @@ use strokes::{HOLD_REPEAT_MS, draw_clone_preview, feed_live_stroke, pointer_butt #[cfg(test)] pub(crate) use strokes::{SPOT_HEALING_TRAIL, live_retouch_points}; pub(crate) use tabs::arranged_cells; +pub(crate) use tabs::tab_title_at; #[cfg(test)] use tabs::{TEAR_OFF, pro_tab_title, tab_context_items, tab_drop_index, tab_move_target, tabs, torn_off}; pub use tabs::{TabStrip, document_area, extra_windows}; diff --git a/crates/ui-egui/src/canvas/select_mask_view.rs b/crates/ui-egui/src/canvas/select_mask_view.rs index e60da1054d..b4962d512d 100644 --- a/crates/ui-egui/src/canvas/select_mask_view.rs +++ b/crates/ui-egui/src/canvas/select_mask_view.rs @@ -57,7 +57,7 @@ impl Mode { Mode::ALL.into_iter().find(|m| m.id() == id) } - fn label(self) -> &'static str { + pub(crate) fn label(self) -> &'static str { match self { Mode::OnionSkin => tl!("Onion Skin"), Mode::MarchingAnts => tl!("Marching Ants"), @@ -70,7 +70,7 @@ impl Mode { } /// The single-letter key that picks this view. - fn key(self) -> egui::Key { + pub(crate) fn key(self) -> egui::Key { match self { Mode::OnionSkin => egui::Key::O, Mode::MarchingAnts => egui::Key::M, @@ -83,7 +83,7 @@ impl Mode { } /// The view's opacity (percent) until it is changed; `None` for views without one. - fn default_opacity(self) -> Option { + pub(crate) fn default_opacity(self) -> Option { match self { Mode::OnionSkin | Mode::Overlay => Some(50.0), Mode::OnBlack | Mode::OnWhite => Some(100.0), @@ -91,7 +91,7 @@ impl Mode { } } - fn next(self) -> Mode { + pub(crate) fn next(self) -> Mode { let i = Mode::ALL.iter().position(|m| *m == self).unwrap_or(0); Mode::ALL.get(i + 1).copied().unwrap_or(Mode::OnionSkin) } @@ -438,6 +438,10 @@ struct View { opacity: f32, show_edge: bool, show_original: bool, + /// Overlay's colour (Photoshop's default rubylith red) and whether it marks the selected + /// areas rather than the masked ones. + color: Color, + selected: bool, } impl View { @@ -449,6 +453,16 @@ impl View { opacity: v.and_then(|v| v.get("opacity")).and_then(Value::as_f64).filter(|o| o.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0) as f32, show_edge: b("showEdge"), show_original: b("showOriginal"), + color: v + .and_then(|v| v.get("color")) + .and_then(Value::as_array) + .filter(|c| c.len() == 3) + .and_then(|c| { + let ch = |i: usize| c.get(i).and_then(Value::as_f64).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0) as f32); + Some(Color::rgb(ch(0)?, ch(1)?, ch(2)?)) + }) + .unwrap_or(Color::rgb(1.0, 0.0, 0.0)), + selected: v.and_then(|v| v.get("indicates")).and_then(Value::as_str) == Some("selected"), } } } @@ -461,16 +475,31 @@ fn length(params: &Value, key: &str, k: u32) -> f64 { /// The preview of the Select and Mask dialog for `doc`: the proxy reduced by `k`, shown in the /// requested view. `None` when the refinement fails or is cancelled. pub fn preview_document(doc: &Document, active: Option, params: &Value, k: u32, cancel: Option<&photocraft_engine::jobs::JobCtx>) -> Option { + let k = k.max(1); + preview_proxy(crate::proxy::proxy_document(doc, k), active, params, k, cancel) +} + +/// [`preview_document`] on `proxy`, the document already reduced by `k` (the Select and Mask +/// workspace builds it itself, its selection already carrying the workspace's tool edits). +pub fn preview_proxy( + mut proxy: Document, + active: Option, + params: &Value, + k: u32, + cancel: Option<&photocraft_engine::jobs::JobCtx>, +) -> Option { let view = View::of(params); let k = k.max(1); - let mut proxy = crate::proxy::proxy_document(doc, k); let active = active.filter(|id| proxy.layer(*id).is_some()); // What Select and Mask starts from: the selection, else the active layer's mask. let original = proxy.selection.clone().or_else(|| active.and_then(|id| proxy.layer(id)).and_then(|l| l.mask.as_ref()).map(|m| m.surface.clone())); let canvas = Rect::new(0, 0, i32::try_from(proxy.size.width).unwrap_or(i32::MAX), i32::try_from(proxy.size.height).unwrap_or(i32::MAX)); let coverage = if view.show_edge { let band = Coverage::edge_band(original.as_ref(), canvas, length(params, "radius", k).round().clamp(1.0, 250.0) as usize); - band.with_brush(scaled_strokes(params, k).as_ref().and_then(|s| photocraft_algo::matting::EdgeBrush::new(s, canvas)).as_ref(), canvas) + // With nothing selected OK refines nothing (`matting::refine_area`), so the brush shows nothing either. + let selects = original.as_ref().is_some_and(|s| !s.content_bounds().intersect(&canvas).is_empty()); + let brush = if selects { scaled_strokes(params, k).and_then(|s| photocraft_algo::matting::EdgeBrush::new(&s, canvas)) } else { None }; + band.with_brush(brush.as_ref(), canvas) } else if view.show_original { Coverage::read(original.as_ref(), canvas) } else { @@ -559,7 +588,10 @@ fn show(doc: &mut Document, active: Option, view: &View, coverage: &Cov doc.selection = Some(coverage.surface(|v| v)); match view.mode { Mode::MarchingAnts => {} - Mode::Overlay => doc.layers.push(veil("Overlay", Color::rgb(1.0, 0.0, 0.0), o, Some(coverage.surface(|v| 1.0 - v)))), + Mode::Overlay => { + let marked = if view.selected { coverage.surface(|v| v) } else { coverage.surface(|v| 1.0 - v) }; + doc.layers.push(veil("Overlay", view.color, o, Some(marked))); + } Mode::OnBlack => doc.layers.push(veil("On Black", Color::BLACK, o, Some(coverage.surface(|v| 1.0 - v)))), Mode::OnWhite => doc.layers.push(veil("On White", Color::WHITE, o, Some(coverage.surface(|v| 1.0 - v)))), Mode::BlackWhite => { @@ -705,6 +737,24 @@ mod tests { assert!(pixel(&edge, 35, 10)[0] > 0.99 && pixel(&edge, 55, 10)[0] < 0.01, "Show Edge includes the painted area"); } + /// Overlay takes Photoshop's colour swatch and Indicates: the masked (default) or the selected + /// areas carry the tint. + #[test] + fn overlay_colour_and_what_it_indicates() { + let doc = half_selected(); + let active = doc.layers.first().map(|l| l.id); + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.02); + let view = |indicates: &str| json!({"__view": {"mode": "overlay", "opacity": 1.0, "color": [0.0, 0.0, 1.0], "indicates": indicates}}); + let masked = preview_document(&doc, active, &view("masked"), 1, None).expect("a preview"); + assert!(near(&pixel(&masked, 35, 10), &[0.0, 0.0, 1.0, 1.0]) && near(&pixel(&masked, 5, 10), &[1.0, 1.0, 1.0, 1.0])); + let selected = preview_document(&doc, active, &view("selected"), 1, None).expect("a preview"); + assert!(near(&pixel(&selected, 5, 10), &[0.0, 0.0, 1.0, 1.0]) && near(&pixel(&selected, 35, 10), &[1.0, 1.0, 1.0, 1.0])); + // A hostile colour falls back to red. + let bad = json!({"__view": {"mode": "overlay", "opacity": 1.0, "color": ["x", 2, null]}}); + let red = preview_document(&doc, active, &bad, 1, None).expect("a preview"); + assert!(near(&pixel(&red, 35, 10), &[1.0, 0.0, 0.0, 1.0])); + } + /// Show Edge shows the band around the selection's edge; Show Original the unrefined selection. #[test] fn show_edge_and_show_original() { diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 82a1e2089f..a3d18fe285 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -436,9 +436,13 @@ fn fit_doc_tabs(natural: &[f32], selected: usize, avail: f32) -> crate::tab_stri /// Photoshop's tab title: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask /// is targeted, "(Quick Mask/8)" in Quick Mask mode; the Background layer's name is omitted. pub(super) fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { + tab_title_at(app, i, app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0)) +} + +/// [`pro_tab_title`] at `zoom` percent (a workspace with its own view, such as Select and Mask). +pub(crate) fn tab_title_at(app: &PhotocraftApp, i: usize, zoom: f32) -> String { use photocraft_engine::channel_cmds::ChannelTarget; let Some(st) = app.session.documents().get(i) else { return String::new() }; - let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); // Quick Mask mode targets the mask, not the layer (see `paint_target`): painting and Free // Transform change the red overlay, so the tab says so, as Photoshop's does. let quick_mask = st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 1db2ec45ad..441dd31433 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -167,7 +167,7 @@ fn full_window_workspaces_are_modal_for_menu_invocations() { app.run("layer.new.layer", json!({})).unwrap(); app.run("edit.fill", json!({"color":"#808080"})).unwrap(); app.run("select.rect", json!({"x":8,"y":8,"width":8,"height":8})).unwrap(); - for workspace in ["filter.liquify", "edit.contentAwareFill", "filter.filterGallery", "filter.adaptiveWideAngle"] { + for workspace in ["filter.liquify", "edit.contentAwareFill", "filter.filterGallery", "filter.adaptiveWideAngle", "select.selectAndMask"] { let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":workspace})); assert_eq!(opened["ok"], true, "{workspace}: {opened}"); assert_eq!(crate::distort_ui::modal_workspace(&app), Some(workspace)); @@ -177,6 +177,7 @@ fn full_window_workspaces_are_modal_for_menu_invocations() { json!({"id":"select.all"}), json!({"id":"view.zoomIn"}), json!({"id":"filter.cameraRaw"}), + json!({"id":"filter.liquify"}), json!({"id":workspace,"params":{"ui":null}}), ] { let blocked = call(&mut app, &ctx, "ui.menu.invoke", request.clone()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a14b42c37f..89954c52ea 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1122,6 +1122,7 @@ pub mod rasterize_prompt; pub mod replace_prompt; pub(super) mod rgb_histogram; pub mod screen_picker; +pub mod select_mask_ui; pub mod shape_dialog; pub(crate) mod shape_fill_ui; pub(super) mod sizing; diff --git a/crates/ui-egui/src/dialogs/distort_ui.rs b/crates/ui-egui/src/dialogs/distort_ui.rs index 3a5c765da6..b5ee13f464 100644 --- a/crates/ui-egui/src/dialogs/distort_ui.rs +++ b/crates/ui-egui/src/dialogs/distort_ui.rs @@ -24,6 +24,8 @@ pub struct Distort { pub liquify: Option, /// Edit › Content-Aware Fill… (caf_ui). pub caf: Option, + /// Select › Select and Mask… (select_mask_ui). + pub select_mask: Option, pub puppet: Option, pub perspective: Option, pub vanishing: Option, @@ -35,7 +37,12 @@ pub struct Distort { impl Distort { pub fn active(&self) -> bool { - self.liquify.is_some() || self.caf.is_some() || self.puppet.is_some() || self.perspective.is_some() || self.vanishing.is_some() + self.liquify.is_some() + || self.caf.is_some() + || self.select_mask.is_some() + || self.puppet.is_some() + || self.perspective.is_some() + || self.vanishing.is_some() } /// Short description for `ui.inspect`. @@ -43,6 +50,7 @@ impl Distort { json!({ "liquify": self.liquify.as_ref().map(|d| d.describe()), "contentAwareFill": self.caf.as_ref().map(|d| d.describe()), + "selectAndMask": self.select_mask.as_ref().map(|d| d.describe()), "puppet": self.puppet.as_ref().map(|p| p.describe()), "perspective": self.perspective.as_ref().map(|p| p.describe()), "vanishingPoint": self.vanishing.as_ref().map(|v| v.describe()), @@ -95,7 +103,9 @@ pub(crate) fn surface_image(surf: &Surface, r: Rect, max_side: usize) -> ColorIm /// Adaptive Wide Angle). These are modal: other menu commands wait for OK or Cancel /// (`menus::modal_allows`). pub(crate) fn modal_workspace(app: &PhotocraftApp) -> Option<&'static str> { - if app.distort.liquify.is_some() { + if app.distort.select_mask.is_some() { + Some("select.selectAndMask") + } else if app.distort.liquify.is_some() { Some("filter.liquify") } else if app.distort.caf.is_some() { Some("edit.contentAwareFill") @@ -116,7 +126,7 @@ fn on_doc(app: &PhotocraftApp, document: DocId) -> bool { active_doc(app) == Some(document) } -/// Drops Liquify / Puppet / Perspective Warp / Vanishing Point / Filter Gallery when the +/// Drops Liquify / Select and Mask / Puppet / Perspective Warp / Vanishing Point / Filter Gallery when the /// document they were opened on is no longer active, so they cannot steal undo, block layer /// delete, or draw another document's pixels (#5115). pub fn cancel_stale(app: &mut PhotocraftApp) { @@ -136,6 +146,10 @@ pub fn cancel_stale(app: &mut PhotocraftApp) { if app.distort.gallery.as_ref().is_some_and(|g| Some(g.document) != active) { app.distort.gallery = None; } + // Its document, or the layer it refines, is no longer the active one (#8896 review). + if crate::select_mask_ui::stale(app).is_some() { + crate::select_mask_ui::cancel(app); + } } /// The document shown on the canvas while Puppet or Perspective Warp previews a layer, or @@ -171,6 +185,9 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val "edit.contentAwareFill" if ui.is_some() && app.distort.caf.is_some() => Some(crate::caf_ui::control(app, ui.unwrap_or(&Value::Null))), // `ui` addresses the workspace: closed, that is an error, not a fill with the defaults. "edit.contentAwareFill" if ui.is_some() => Some(Err("Content-Aware Fill is not open".into())), + "select.selectAndMask" if ui.is_some() && app.distort.select_mask.is_some() => Some(crate::select_mask_ui::control(app, ui.unwrap_or(&Value::Null))), + "select.selectAndMask" if ui.is_some() => Some(Err("Select and Mask is not open".into())), + "select.selectAndMask" => Some(crate::select_mask_ui::open(app).map(|_| json!({"selectAndMask": app.distort.describe()["selectAndMask"]}))), "edit.puppetWarp" | "layer.smartObjects.puppetWarp" if empty => { Some(crate::puppet_ui::begin(app, ctx, id).map(|_| json!({"puppet": app.distort.describe()["puppet"]}))) } @@ -196,6 +213,10 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> crate::caf_ui::pointer(app, ev, mods); return true; } + if app.distort.select_mask.as_ref().is_some_and(|w| on_doc(app, w.document)) { + crate::select_mask_ui::pointer(app, ev, mods); + return true; + } if app.distort.liquify.as_ref().is_some_and(|d| on_doc(app, d.document)) { crate::liquify_ui::pointer(app, ev, mods); return true; @@ -238,6 +259,15 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } return true; } + if app.distort.select_mask.is_some() { + // Enter closes a Polygonal Lasso polygon, else OK; Esc drops one, else Cancel. + if enter(ctx) { + crate::select_mask_ui::enter(app); + } else if esc(ctx) { + crate::select_mask_ui::escape(app); + } + return true; + } if app.distort.liquify.is_some() { if enter(ctx) { let _ = crate::liquify_ui::commit(app); @@ -348,6 +378,7 @@ pub fn drop_foreign(app: &mut PhotocraftApp) { app.distort.liquify = None; // Stops its background preview too; what Apply wrote stays, as with Cancel. crate::caf_ui::cancel(app); + crate::select_mask_ui::cancel(app); app.distort.puppet = None; app.distort.perspective = None; app.distort.vanishing = None; @@ -363,6 +394,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if app.distort.caf.is_some() { crate::caf_ui::show(app, ctx); } + if app.distort.select_mask.is_some() { + crate::select_mask_ui::show(app, ctx); + } if app.distort.gallery.is_some() { crate::gallery_ui::show(app, ctx); } diff --git a/crates/ui-egui/src/dialogs/select_mask_ui.rs b/crates/ui-egui/src/dialogs/select_mask_ui.rs new file mode 100644 index 0000000000..3430569775 --- /dev/null +++ b/crates/ui-egui/src/dialogs/select_mask_ui.rs @@ -0,0 +1,1971 @@ +//! Select › Select and Mask…: Photoshop's Select and Mask workspace (#7069, #8148, TOOL-214-1), a +//! full-window workspace like Content-Aware Fill's. +//! +//! Laid out as Photoshop's: the tool's options bar across the top, the tools on the left (Quick +//! Selection W, Refine Edge Brush R, Brush B, Object Selection W, Lasso and Polygonal Lasso L in +//! one slot, Hand H, Zoom Z; Shift+W and Shift+L cycle), the document under its tab in the middle, +//! shown in the chosen view, and the Properties panel on the right: Remember Settings, View Mode +//! (the views with their letters, Show Edge J, Show Original P, Real-Time Refinement, High Quality +//! Preview, Transparency or Opacity, Overlay's colour and what it indicates), Refine Mode, Edge +//! Detection, Global Refinements (with Clear Selection and Invert) and Output Settings, then +//! Reset, OK and Cancel. The view keys (O M V A T K Y, F cycles, hold X for the image) work as in +//! the dialog this replaces. +//! +//! What the workspace holds is plain data: the tools' edits (`select.refineEdge`'s `edits`), the +//! Refine Edge Brush strokes (`refineStrokes`) and the settings. OK runs `select.refineEdge` with +//! them, one history step; Cancel drops them; Ctrl+Z undoes the last edit or stroke. The preview +//! runs the same edits ([`photocraft_engine::select_mask_edits`]) on a reduced copy (full size +//! with High Quality Preview) in the background and keeps the selection after the edits it has +//! applied, so a new stroke costs only that stroke; then it shows the refined selection in the +//! view ([`crate::select_mask_view::preview_proxy`]). With Real-Time Refinement the stroke being +//! drawn joins the preview while the pointer moves; without, when it is released. +//! +//! Not here yet: Refine Hair (#2671) and Object Aware (a learned model, #2788) are shown but greyed +//! out, and Photoshop's Presets. + +use std::sync::Arc; + +use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2}; +use photocraft_doc::{DocId, Document, LayerId}; +use photocraft_engine::select_mask_edits::{self, MAX_EDIT_POINTS, MAX_EDITS}; +use photocraft_engine::smartselect_cmds::{MAX_STROKE_POINTS, MAX_STROKES}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::select_mask_view::Mode; +use crate::theme::Tokens; +use crate::widgets; + +/// Longest side of the reduced copy the preview runs on (px), unless High Quality Preview. +const PROXY_SIDE: usize = 1600; +const LEFT_W: f32 = 48.0; +const BAR_H: f32 = 36.0; +const TAB_H: f32 = 28.0; +const PANEL_W: f32 = 350.0; +const UNDO_LIMIT: usize = 100; +/// Marching ants with more edges than this are not drawn. +const MAX_ANT_EDGES: usize = 200_000; +/// Bound the temporary dense mask used for marching ants. +const MAX_ANT_PIXELS: usize = 4_000_000; +/// The `prefs.dialogs` key under which Remember Settings keeps the settings. +const REMEMBERED: &str = "select.refineEdge.workspace"; +const CMD: &str = crate::select_mask_view::COMMAND; +/// The Output To targets, in Photoshop's order. +const OUTPUTS: [&str; 6] = ["selection", "layerMask", "newLayer", "newLayerWithMask", "newDocument", "newDocumentWithMask"]; +/// Photoshop's brush sizes (px). +const SIZES: std::ops::RangeInclusive = 1.0..=5000.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SmTool { + Quick, + RefineEdge, + Brush, + Object, + Lasso, + PolygonalLasso, + Hand, + Zoom, +} + +impl SmTool { + fn name(self) -> &'static str { + match self { + SmTool::Quick => "quick", + SmTool::RefineEdge => "refineEdge", + SmTool::Brush => "brush", + SmTool::Object => "object", + SmTool::Lasso => "lasso", + SmTool::PolygonalLasso => "polygonalLasso", + SmTool::Hand => "hand", + SmTool::Zoom => "zoom", + } + } + + fn from_name(s: &str) -> Option { + Some(match s { + "quick" => SmTool::Quick, + "refineEdge" => SmTool::RefineEdge, + "brush" => SmTool::Brush, + "object" => SmTool::Object, + "lasso" => SmTool::Lasso, + "polygonalLasso" => SmTool::PolygonalLasso, + "hand" => SmTool::Hand, + "zoom" => SmTool::Zoom, + _ => return None, + }) + } + + fn icon(self) -> &'static str { + match self { + SmTool::Quick => "quick-selection", + SmTool::RefineEdge => "brush-cleaning", + SmTool::Brush => "brush", + SmTool::Object => "square-dashed-mouse-pointer", + SmTool::Lasso => "lasso", + SmTool::PolygonalLasso => "pentagon", + SmTool::Hand => "hand", + SmTool::Zoom => "zoom-in", + } + } + + fn tip(self) -> String { + let (label, key) = match self { + SmTool::Quick => (tl!("Quick Selection Tool"), "W"), + SmTool::RefineEdge => (tl!("Refine Edge Brush Tool"), "R"), + SmTool::Brush => (tl!("Brush Tool"), "B"), + SmTool::Object => (tl!("Object Selection Tool"), "W"), + SmTool::Lasso => (tl!("Lasso Tool"), "L"), + SmTool::PolygonalLasso => (tl!("Polygonal Lasso Tool"), "L"), + SmTool::Hand => (tl!("Hand Tool"), "H"), + SmTool::Zoom => (tl!("Zoom Tool"), "Z"), + }; + format!("{label} ({key})") + } + + /// Paints with a round brush (size from `[` and `]`). + fn brushes(self) -> bool { + matches!(self, SmTool::Quick | SmTool::RefineEdge | SmTool::Brush) + } + + /// Adds to or subtracts from the selection (the options bar's + and −; Alt swaps them). + fn edits(self) -> bool { + !matches!(self, SmTool::Hand | SmTool::Zoom) + } +} + +/// The Properties panel's settings (kept between uses with Remember Settings). +#[derive(Clone, Debug, PartialEq)] +pub struct SmOpts { + pub view: Mode, + /// Each view's Transparency / Opacity (percent), in [`Mode::ALL`] order. + pub opacity: [f32; 7], + pub show_edge: bool, + pub show_original: bool, + /// Real-Time Refinement: the stroke being drawn joins the preview while the pointer moves. + pub real_time: bool, + /// High Quality Preview: the preview runs on the document at full size. + pub high_quality: bool, + /// Overlay's colour and whether it marks the selected areas (else the masked ones). + pub overlay_color: [u8; 3], + pub indicates_selected: bool, + pub radius: f32, + pub smart_radius: bool, + pub smooth: f32, + pub feather: f32, + pub contrast: f32, + pub shift_edge: f32, + pub decontaminate: bool, + pub amount: f32, + pub output: String, + pub remember: bool, +} + +impl Default for SmOpts { + fn default() -> Self { + SmOpts { + view: Mode::OnionSkin, + opacity: Mode::ALL.map(|m| m.default_opacity().unwrap_or(100.0)), + show_edge: false, + show_original: false, + real_time: true, + high_quality: false, + overlay_color: [255, 0, 0], + indicates_selected: false, + radius: 0.0, + smart_radius: false, + smooth: 0.0, + feather: 0.0, + contrast: 0.0, + shift_edge: 0.0, + decontaminate: false, + amount: 100.0, + output: "selection".into(), + remember: false, + } + } +} + +fn mode_index(m: Mode) -> usize { + Mode::ALL.iter().position(|x| *x == m).unwrap_or(0) +} + +impl SmOpts { + /// Applies the settings named in `v` (control channel and remembered keys); others stay. + pub fn apply(&mut self, v: &Value) -> Result<(), String> { + let flag = |k: &str| v.get(k).and_then(Value::as_bool); + for (k, slot) in [ + ("showEdge", &mut self.show_edge), + ("showOriginal", &mut self.show_original), + ("realTimeRefinement", &mut self.real_time), + ("highQualityPreview", &mut self.high_quality), + ("smartRadius", &mut self.smart_radius), + ("decontaminate", &mut self.decontaminate), + ("remember", &mut self.remember), + ] { + if let Some(b) = flag(k) { + *slot = b; + } + } + for (k, slot, lo, hi) in [ + ("radius", &mut self.radius, 0.0, 250.0), + ("smooth", &mut self.smooth, 0.0, 100.0), + ("feather", &mut self.feather, 0.0, 1000.0), + ("contrast", &mut self.contrast, 0.0, 100.0), + ("shiftEdge", &mut self.shift_edge, -100.0, 100.0), + ("amount", &mut self.amount, 0.0, 100.0), + ] { + if let Some(n) = v.get(k).and_then(Value::as_f64).filter(|n| n.is_finite()) { + *slot = (n as f32).clamp(lo, hi); + } + } + if let Some(m) = v.get("view").and_then(Value::as_str) { + self.view = Mode::from_id(m).ok_or_else(|| format!("bad view `{m}` ({})", Mode::ALL.map(|m| m.id()).join("|")))?; + } + match v.get("opacity") { + // A number: the current view's; an object: per view. + Some(Value::Number(n)) => { + if let Some(n) = n.as_f64().filter(|n| n.is_finite()) { + self.opacity[mode_index(self.view)] = (n as f32).clamp(0.0, 100.0); + } + } + Some(Value::Object(o)) => { + for (k, n) in o { + if let (Some(m), Some(n)) = (Mode::from_id(k), n.as_f64().filter(|n| n.is_finite())) { + self.opacity[mode_index(m)] = (n as f32).clamp(0.0, 100.0); + } + } + } + _ => {} + } + if let Some(c) = v.get("overlayColor").and_then(Value::as_array).filter(|c| c.len() == 3) { + let ch = |i: usize| c.get(i).and_then(Value::as_u64).map(|v| v.min(255) as u8); + if let (Some(r), Some(g), Some(b)) = (ch(0), ch(1), ch(2)) { + self.overlay_color = [r, g, b]; + } + } + match v.get("indicates").and_then(Value::as_str) { + None => {} + Some("masked") => self.indicates_selected = false, + Some("selected") => self.indicates_selected = true, + Some(s) => return Err(format!("bad indicates `{s}` (masked|selected)")), + } + if let Some(o) = v.get("output").and_then(Value::as_str) { + if !OUTPUTS.contains(&o) { + return Err(format!("bad output `{o}` ({})", OUTPUTS.join("|"))); + } + self.output = o.to_string(); + } + self.follow_decontaminate(); + Ok(()) + } + + /// Decontaminating needs new pixels, so (as in Photoshop) it outputs to a new layer or document. + fn follow_decontaminate(&mut self) { + if self.decontaminate && matches!(self.output.as_str(), "selection" | "layerMask") { + self.output = "newLayerWithMask".into(); + } + } + + /// The settings as [`SmOpts::apply`] reads them. + pub fn to_json(&self) -> Value { + let opacity: Map = Mode::ALL.iter().zip(self.opacity).map(|(m, o)| (m.id().to_string(), json!(o))).collect(); + json!({ + "view": self.view.id(), + "opacity": opacity, + "showEdge": self.show_edge, + "showOriginal": self.show_original, + "realTimeRefinement": self.real_time, + "highQualityPreview": self.high_quality, + "overlayColor": self.overlay_color, + "indicates": if self.indicates_selected { "selected" } else { "masked" }, + "radius": self.radius, + "smartRadius": self.smart_radius, + "smooth": self.smooth, + "feather": self.feather, + "contrast": self.contrast, + "shiftEdge": self.shift_edge, + "decontaminate": self.decontaminate, + "amount": self.amount, + "output": self.output, + "remember": self.remember, + }) + } + + /// `select.refineEdge`'s refinement and output params. + fn refine_params(&self) -> Map { + let mut p = Map::new(); + p.insert("radius".into(), json!(self.radius)); + p.insert("smartRadius".into(), json!(self.smart_radius)); + p.insert("smooth".into(), json!(self.smooth)); + p.insert("feather".into(), json!(self.feather)); + p.insert("contrast".into(), json!(self.contrast)); + p.insert("shiftEdge".into(), json!(self.shift_edge)); + p.insert("decontaminate".into(), json!(self.decontaminate)); + p.insert("amount".into(), json!(self.amount)); + p.insert("output".into(), json!(self.output)); + p + } + + /// The preview's view (`select_mask_view`'s `__view`). + fn view_params(&self) -> Value { + let c = self.overlay_color.map(|v| f32::from(v) / 255.0); + json!({ + "mode": self.view.id(), + "opacity": self.opacity[mode_index(self.view)] / 100.0, + "showEdge": self.show_edge, + "showOriginal": self.show_original, + "color": c, + "indicates": if self.indicates_selected { "selected" } else { "masked" }, + }) + } +} + +/// One undoable step. +#[derive(Clone, Debug)] +enum Step { + Edit(Value), + Stroke(Value), + /// A reset, with what it replaced. + State { + edits: Vec, + strokes: Vec, + opts: Box, + }, +} + +/// A press-and-drag on the view with a tool, in document px. +#[derive(Clone, Debug)] +struct Gesture { + tool: SmTool, + add: bool, + points: Vec<[f64; 2]>, +} + +/// The selection after the first `edits` (document coordinates) on the copy reduced by `k`. +#[derive(Clone)] +struct BaseCache { + k: u32, + /// The document revision the base was computed from. + revision: u64, + edits: Vec, + base: Option, +} + +/// A computed preview, ready to upload. +struct Shown { + image: egui::ColorImage, + /// Marching ants (document px) in the Marching Ants view. + ants: Option>, + /// Reduced-copy pixels at least half selected. + selected: usize, + /// How many points of the stroke being drawn it includes ([`usize::MAX`]: every stroke is in). + trail: usize, + /// The document px the image covers (the reduced copy's size × `k`). + covers: [f32; 2], +} + +#[cfg(not(target_arch = "wasm32"))] +type Outcome = Result<(Shown, BaseCache, Arc), String>; + +/// The preview being computed or shown. +#[derive(Default)] +struct Preview { + /// Bumped whenever the state changes; a result for an older generation is dropped. + want: u64, + #[cfg(not(target_arch = "wasm32"))] + running: Option<(u64, u64, std::sync::mpsc::Receiver, photocraft_engine::jobs::JobCtx)>, + shown: u64, + pending: Option, + tex: Option, + ants: Option>, + covers: [f32; 2], + selected: usize, + /// [`Shown::trail`] of the preview shown. + trail: usize, + cache: Option, + /// The reduced copy of the document (its factor and the revision it was made from). + proxy: Option<(u32, u64, Arc)>, + error: Option, +} + +pub struct SelectMaskWorkspace { + /// The document and layer the workspace was opened on: its work applies to them only. + layer: Option, + pub(crate) document: DocId, + canvas: Rect, + /// The document revision the textures were made from. + revision: u64, + /// The targeted layer mask is what is refined (`"target": "mask"`). + target_mask: bool, + pub opts: SmOpts, + pub tool: SmTool, + /// The tools W and L pick: the last of each slot used. + w_tool: SmTool, + l_tool: SmTool, + pub add: bool, + pub quick_size: f64, + pub refine_size: f64, + pub brush_size: f64, + pub hardness: f32, + pub sample_all: bool, + pub edits: Vec, + pub strokes: Vec, + undo: Vec, + redo: Vec, + gesture: Option, + /// The stroke last drawn, until a preview with it arrives (its newest part is drawn over the + /// preview meanwhile, so painting looks continuous). + trail: Option, + /// The Polygonal Lasso's vertices so far, and whether it adds. + poly: Option<(bool, Vec<[f64; 2]>)>, + /// X is held: the image without the view. + hide_view: bool, + /// Document px per reduced-copy px (High Quality Preview uses 1). + k: u32, + pressed: bool, + /// The device's texture side limit, as the context reports it each frame. + texture_limit: usize, + image_tex: Option, + zoom: f32, + center: [f64; 2], + hover: Option<[f64; 2]>, + preview: Preview, + pub error: Option, +} + +impl SelectMaskWorkspace { + pub fn describe(&self) -> Value { + json!({ + "tool": self.tool.name(), + "mode": if self.add { "add" } else { "subtract" }, + "size": self.size(), + "hardness": self.hardness, + "sampleAllLayers": self.sample_all, + "edits": self.edits.len(), + "strokes": self.strokes.len(), + "undo": self.undo.len(), + "redo": self.redo.len(), + "polygon": self.poly.as_ref().map_or(0, |(_, p)| p.len()), + "settings": self.opts.to_json(), + "proxyScale": self.proxy_k(), + "selectedProxyPixels": self.preview.selected, + "previewReady": (self.preview.tex.is_some() || self.preview.pending.is_some()) && self.preview.shown == self.preview.want, + "previewError": self.preview.error, + "error": self.error, + }) + } + + /// The factor the preview runs at. + fn proxy_k(&self) -> u32 { + if self.opts.high_quality { 1 } else { self.k } + } + + /// The current brush tool's size (Quick Selection, Refine Edge Brush, Brush; else the brush's). + fn size(&self) -> f64 { + match self.tool { + SmTool::Quick => self.quick_size, + SmTool::RefineEdge => self.refine_size, + _ => self.brush_size, + } + } + + fn set_size(&mut self, v: f64) { + let v = if v.is_finite() { v.round().clamp(*SIZES.start(), *SIZES.end()) } else { return }; + match self.tool { + SmTool::Quick => self.quick_size = v, + SmTool::RefineEdge => self.refine_size = v, + SmTool::Brush => self.brush_size = v, + _ => {} + } + } + + fn pick(&mut self, t: SmTool) { + self.tool = t; + match t { + SmTool::Quick | SmTool::Object => self.w_tool = t, + SmTool::Lasso | SmTool::PolygonalLasso => self.l_tool = t, + _ => {} + } + if t != SmTool::PolygonalLasso { + self.poly = None; + } + } + + /// The preview is out of date. + fn stale(&mut self) { + self.preview.want += 1; + } + + fn push(&mut self, s: Step) { + self.redo.clear(); + if self.undo.len() == UNDO_LIMIT { + self.undo.remove(0); + } + self.undo.push(s); + } + + fn points_in(list: &[Value]) -> usize { + list.iter().map(|e| e.get("points").and_then(Value::as_array).map_or(0, Vec::len)).sum() + } + + /// An item the engine's limits refuse: say why, and drop what was drawn for it. + fn reject(&mut self, why: String) { + self.error = Some(why); + self.trail = None; + self.stale(); + } + + /// Adds a tool edit (undoable), within the engine's limits. + fn add_edit(&mut self, e: Value) { + if self.edits.len() >= MAX_EDITS { + self.reject(format!("at most {MAX_EDITS} edits: undo some, or reset")); + return; + } + if Self::points_in(&self.edits) + Self::points_in(std::slice::from_ref(&e)) > MAX_EDIT_POINTS { + self.reject(format!("at most {MAX_EDIT_POINTS} points in all edits: undo some, or reset")); + return; + } + self.error = None; + self.edits.push(e.clone()); + self.push(Step::Edit(e)); + self.stale(); + } + + /// Adds a Refine Edge Brush stroke (undoable), within the engine's limits. + fn add_stroke(&mut self, s: Value) { + if self.strokes.len() >= MAX_STROKES { + self.reject(format!("at most {MAX_STROKES} Refine Edge Brush strokes: undo some, or reset")); + return; + } + if Self::points_in(&self.strokes) + Self::points_in(std::slice::from_ref(&s)) > MAX_STROKE_POINTS { + self.reject(format!("at most {MAX_STROKE_POINTS} points in all Refine Edge Brush strokes: undo some, or reset")); + return; + } + self.error = None; + self.strokes.push(s.clone()); + self.push(Step::Stroke(s)); + self.stale(); + } + + /// What `g` adds when it ends: a tool edit or a Refine Edge Brush stroke (`None`: nothing). + fn finish(&self, g: &Gesture) -> Option> { + let round = |p: &[f64; 2]| json!([(p[0] * 10.0).round() / 10.0, (p[1] * 10.0).round() / 10.0]); + let pts: Vec = g.points.iter().map(round).collect(); + let mode = if g.add { "add" } else { "subtract" }; + let first = g.points.first()?; + Some(match g.tool { + SmTool::Quick => Ok(json!({"tool": "quick", "points": pts, "size": self.quick_size, "mode": mode, "sampleAllLayers": self.sample_all})), + SmTool::Brush => Ok(json!({"tool": "brush", "points": pts, "size": self.brush_size, "hardness": self.hardness, "mode": mode})), + SmTool::RefineEdge => Err(json!({"points": pts, "size": self.refine_size, "mode": mode})), + SmTool::Lasso | SmTool::PolygonalLasso if pts.len() >= 3 => Ok(json!({"tool": "lasso", "points": pts, "mode": mode})), + SmTool::Object => { + let last = g.points.last().unwrap_or(first); + let (w, h) = (last[0] - first[0], last[1] - first[1]); + // A click (or a drag of a couple of pixels) picks the object under the pointer. + if w.abs().max(h.abs()) * f64::from(self.zoom.max(0.01)) < 4.0 { + Ok(json!({"tool": "object", "point": round(first), "mode": mode, "sampleAllLayers": self.sample_all})) + } else { + let r = |v: f64| (v * 10.0).round() / 10.0; + Ok(json!({"tool": "object", "rect": [r(first[0]), r(first[1]), r(w), r(h)], "mode": mode, "sampleAllLayers": self.sample_all})) + } + } + _ => return None, + }) + } + + fn end_gesture(&mut self) { + let Some(g) = self.gesture.take() else { return }; + self.trail = Some(g.clone()); + match self.finish(&g) { + Some(Ok(e)) => self.add_edit(e), + Some(Err(s)) => self.add_stroke(s), + None => self.stale(), + } + } + + /// The Polygonal Lasso's polygon closes into an edit. + fn close_polygon(&mut self) { + if let Some((add, points)) = self.poly.take() + && points.len() >= 3 + { + self.gesture = Some(Gesture { tool: SmTool::PolygonalLasso, add, points }); + self.end_gesture(); + } + } + + fn begin(&mut self, p: [f64; 2], alt: bool) { + let add = self.add != alt; + match self.tool { + SmTool::PolygonalLasso => { + let near = |q: &[f64; 2]| (q[0] - p[0]).hypot(q[1] - p[1]) * f64::from(self.zoom.max(0.01)) < 6.0; + match &mut self.poly { + // Clicking the first vertex again closes the polygon. + Some((_, pts)) if pts.len() >= 3 && pts.first().is_some_and(near) => self.close_polygon(), + Some((_, pts)) => pts.push(p), + None => self.poly = Some((add, vec![p])), + } + } + t if t.edits() => { + self.gesture = Some(Gesture { tool: t, add, points: vec![p] }); + self.trail = None; + self.preview.trail = 0; + } + _ => {} + } + } + + fn extend(&mut self, p: [f64; 2]) { + let step = if self.tool.brushes() { (self.size() / 8.0).max(1.0) } else { 0.5 }; + let real_time = self.opts.real_time; + let Some(g) = self.gesture.as_mut() else { return }; + match g.tool { + // Object Selection keeps the press and the current corner. + SmTool::Object => { + g.points.truncate(1); + g.points.push(p); + } + _ => { + if g.points.last().is_some_and(|l| (l[0] - p[0]).hypot(l[1] - p[1]) < step) { + return; + } + g.points.push(p); + } + } + if real_time { + self.stale(); + } + } +} + +/// Undo the last edit, stroke or reset. +fn undo(w: &mut SelectMaskWorkspace) { + w.end_gesture(); + w.poly = None; + let Some(step) = w.undo.pop() else { return }; + let back = match step { + Step::Edit(e) => { + w.edits.pop(); + Step::Edit(e) + } + Step::Stroke(s) => { + w.strokes.pop(); + Step::Stroke(s) + } + Step::State { edits, strokes, opts } => { + let now = Step::State { + edits: std::mem::replace(&mut w.edits, edits), + strokes: std::mem::replace(&mut w.strokes, strokes), + opts: Box::new(w.opts.clone()), + }; + w.opts = *opts; + now + } + }; + w.redo.push(back); + w.error = None; + w.stale(); +} + +fn redo(w: &mut SelectMaskWorkspace) { + w.end_gesture(); + let Some(step) = w.redo.pop() else { return }; + let back = match step { + Step::Edit(e) => { + w.edits.push(e.clone()); + Step::Edit(e) + } + Step::Stroke(s) => { + w.strokes.push(s.clone()); + Step::Stroke(s) + } + Step::State { edits, strokes, opts } => { + let now = Step::State { + edits: std::mem::replace(&mut w.edits, edits), + strokes: std::mem::replace(&mut w.strokes, strokes), + opts: Box::new(w.opts.clone()), + }; + w.opts = *opts; + now + } + }; + w.undo.push(back); + w.error = None; + w.stale(); +} + +/// Reset (the panel's ↺): the settings back to Photoshop's defaults and the edits and strokes +/// dropped, as one undoable step. +fn reset(w: &mut SelectMaskWorkspace) { + w.end_gesture(); + w.poly = None; + let opts = SmOpts { remember: w.opts.remember, ..SmOpts::default() }; + let prev = + Step::State { edits: std::mem::take(&mut w.edits), strokes: std::mem::take(&mut w.strokes), opts: Box::new(std::mem::replace(&mut w.opts, opts)) }; + w.push(prev); + w.error = None; + w.stale(); +} + +/// Opens the workspace on the selection (or the active layer's mask). +pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { + // Opening again would drop the open workspace's work: edit it with `ui`, or cancel it. + if app.distort.select_mask.is_some() { + return Err("Select and Mask is already open".into()); + } + if let Some(Err(why)) = photocraft_engine::commands::find(CMD).map(|c| (c.enabled)(&app.session)) { + return Err(format!("Select and Mask needs a selection or a layer mask ({why})")); + } + // A targeted layer mask is what is refined (Photoshop opens on it from the mask's thumbnail). + let target_mask = app.layer_mask_targeted(); + let st = app.session.active().ok_or("no document")?; + let document = st.doc.id; + let layer = st.active_layer.filter(|id| st.doc.layer(*id).is_some()); + let canvas = st.doc.bounds(); + let revision = st.revision; + let mask_only = st.doc.selection.is_none() && layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); + let k = u32::try_from((canvas.width().max(canvas.height()) as usize).div_ceil(PROXY_SIDE).max(1)).unwrap_or(u32::MAX); + let mut opts = SmOpts::default(); + match app.session.prefs().dialogs.get(REMEMBERED) { + Some(saved) if saved.get("remember").and_then(Value::as_bool) == Some(true) => { + let _ = opts.apply(saved); + } + _ if mask_only || target_mask => opts.output = "layerMask".into(), + _ => {} + } + let mut w = SelectMaskWorkspace { + layer, + document, + canvas, + revision, + target_mask, + opts, + tool: SmTool::Quick, + w_tool: SmTool::Quick, + l_tool: SmTool::Lasso, + add: true, + quick_size: 30.0, + refine_size: 30.0, + brush_size: 30.0, + hardness: 100.0, + sample_all: false, + edits: Vec::new(), + strokes: Vec::new(), + undo: Vec::new(), + redo: Vec::new(), + gesture: None, + trail: None, + poly: None, + hide_view: false, + k, + pressed: false, + texture_limit: 2048, + image_tex: None, + zoom: 0.0, + center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0], + hover: None, + preview: Preview::default(), + error: None, + }; + w.stale(); + app.distort.select_mask = Some(w); + Ok(()) +} + +/// Why the open workspace's work no longer applies: the active document or layer is not the one it +/// was opened on (another tab, or another layer selected by a shortcut or the control channel). +/// `select.refineEdge` works on the active document and layer, so its edits must not run there. +pub(crate) fn stale(app: &PhotocraftApp) -> Option<&'static str> { + let w = app.distort.select_mask.as_ref()?; + let Some(st) = app.session.active().filter(|st| st.doc.id == w.document) else { + return Some(tl!("Select and Mask was closed: its document is no longer the active one")); + }; + let layer = st.active_layer.filter(|id| st.doc.layer(*id).is_some()); + (layer != w.layer).then_some(tl!("Select and Mask was closed: another layer was selected")) +} + +/// Closes a [`stale`] workspace (its work is dropped, the new target untouched): the reason. +fn drop_stale(app: &mut PhotocraftApp) -> Result<(), String> { + match stale(app) { + Some(why) => { + close(app); + app.ui.status = why.into(); + app.ui.status_error = true; + Err(why.into()) + } + None => Ok(()), + } +} + +/// The params OK runs `select.refineEdge` with. +fn commit_params(w: &SelectMaskWorkspace) -> Value { + let mut p = w.opts.refine_params(); + p.insert("sampleAllLayers".into(), json!(w.sample_all)); + if !w.edits.is_empty() { + p.insert("edits".into(), Value::Array(w.edits.clone())); + } + if !w.strokes.is_empty() { + p.insert("refineStrokes".into(), Value::Array(w.strokes.clone())); + } + if w.target_mask { + p.insert("target".into(), json!("mask")); + } + Value::Object(p) +} + +fn remember(app: &mut PhotocraftApp, opts: &SmOpts) { + let v = if opts.remember { opts.to_json() } else { json!({"remember": false}) }; + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), v)); +} + +/// OK: runs `select.refineEdge` and closes. A failure leaves the workspace open with the error in +/// its panel, so nothing painted is lost. +pub fn commit(app: &mut PhotocraftApp) -> Result { + drop_stale(app)?; + let w = app.distort.select_mask.as_mut().ok_or("Select and Mask is not open")?; + w.end_gesture(); + w.close_polygon(); + let (p, opts) = (commit_params(w), w.opts.clone()); + match app.run(CMD, p) { + Ok(v) => { + remember(app, &opts); + close(app); + Ok(v) + } + Err(e) => { + if let Some(w) = app.distort.select_mask.as_mut() { + w.error = Some(e.clone()); + } + app.ui.status = e.clone(); + app.ui.status_error = true; + Err(e) + } + } +} + +/// Cancel (button, Esc): closes; the document is untouched. +pub fn cancel(app: &mut PhotocraftApp) { + close(app); +} + +fn close(app: &mut PhotocraftApp) { + if let Some(w) = app.distort.select_mask.take() { + cancel_preview(w); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn cancel_preview(w: SelectMaskWorkspace) { + if let Some((_, _, _, job)) = w.preview.running { + job.cancel(); + } +} + +#[cfg(target_arch = "wasm32")] +fn cancel_preview(_: SelectMaskWorkspace) {} + +/// Enter: closes a Polygonal Lasso polygon, else OK. True when it closed a polygon. +pub fn enter(app: &mut PhotocraftApp) -> bool { + let Some(w) = app.distort.select_mask.as_mut() else { return false }; + if w.poly.is_some() { + w.close_polygon(); + return true; + } + let _ = commit(app); + false +} + +/// Esc: drops a Polygonal Lasso polygon being drawn, else Cancel. +pub fn escape(app: &mut PhotocraftApp) { + match app.distort.select_mask.as_mut() { + Some(w) if w.poly.is_some() => w.poly = None, + _ => cancel(app), + } +} + +/// Control channel: `select.selectAndMask {"ui": {...}}` while the workspace is open. +pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { + let flag = |k: &str| ui.get(k).and_then(Value::as_bool) == Some(true); + if flag("cancel") { + cancel(app); + return Ok(json!({"cancelled": true})); + } + drop_stale(app)?; + { + let w = app.distort.select_mask.as_mut().ok_or("Select and Mask is not open")?; + let before = w.opts.clone(); + // Everything is read before anything changes, so rejected params change nothing. + let mut o = w.opts.clone(); + o.apply(ui)?; + let tool = match ui.get("tool").and_then(Value::as_str) { + Some(t) => Some(SmTool::from_name(t).ok_or(format!("bad tool `{t}` (quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom)"))?), + None => None, + }; + let add = match ui.get("mode").and_then(Value::as_str) { + None => None, + Some("add") => Some(true), + Some("subtract") => Some(false), + Some(m) => return Err(format!("bad mode `{m}` (add|subtract)")), + }; + let stroke = match ui.get("stroke") { + Some(s) => { + let pts: Vec<[f64; 2]> = + serde_json::from_value(s.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad stroke points: {e}"))?; + if pts.iter().any(|p| !p[0].is_finite() || !p[1].is_finite()) { + return Err("bad stroke points: not finite".into()); + } + Some((pts, s.get("alt").and_then(Value::as_bool).unwrap_or(false))) + } + None => None, + }; + if let Some(t) = tool { + w.pick(t); + } + w.opts = o; + if let Some(add) = add { + w.add = add; + } + if let Some(n) = ui.get("size").and_then(Value::as_f64) { + w.set_size(n); + } + if let Some(n) = ui.get("hardness").and_then(Value::as_f64).filter(|n| n.is_finite()) { + w.hardness = (n as f32).clamp(0.0, 100.0); + } + if let Some(b) = ui.get("sampleAllLayers").and_then(Value::as_bool) { + w.sample_all = b; + } + if let Some(b) = ui.get("hideView").and_then(Value::as_bool) { + w.hide_view = b; + } + if w.opts != before { + w.stale(); + } + if let Some((pts, alt)) = stroke { + if w.tool == SmTool::PolygonalLasso { + w.poly = Some((w.add != alt, pts)); + w.close_polygon(); + } else if let Some((first, rest)) = pts.split_first() { + w.begin(*first, alt); + for p in rest { + w.extend(*p); + } + w.end_gesture(); + } + } + let sample_all = w.sample_all; + for (key, edit) in [ + ("selectSubject", json!({"tool": "subject", "sampleAllLayers": sample_all})), + ("clearSelection", json!({"tool": "clear"})), + ("invert", json!({"tool": "invert"})), + ] { + if flag(key) { + w.add_edit(edit); + } + } + if flag("reset") { + reset(w); + } + if flag("undo") { + undo(w); + } + if flag("redo") { + redo(w); + } + } + if flag("waitPreview") { + wait_preview(app)?; + } + if flag("commit") { + return commit(app).map(|v| json!({"committed": true, "result": v})); + } + Ok(app.distort.select_mask.as_ref().map(SelectMaskWorkspace::describe).unwrap_or(Value::Null)) +} + +/// `e` (document coordinates) on the copy reduced by `k`: points, sizes and rectangles scale by +/// `1 / k`. +fn scale_edit(e: &Value, k: u32) -> Value { + let k = f64::from(k.max(1)); + let mut e = e.clone(); + let Some(o) = e.as_object_mut() else { return e }; + let scale = |v: &mut Value| { + if let Some(n) = v.as_f64() { + *v = json!(n / k); + } + }; + if let Some(pts) = o.get_mut("points").and_then(Value::as_array_mut) { + for p in pts.iter_mut().filter_map(Value::as_array_mut) { + p.iter_mut().for_each(scale); + } + } + for key in ["point", "rect"] { + if let Some(a) = o.get_mut(key).and_then(Value::as_array_mut) { + a.iter_mut().for_each(scale); + } + } + if let Some(size) = o.get("size").and_then(Value::as_f64) { + o.insert("size".into(), json!((size / k).max(1.0))); + } + e +} + +/// What a preview computation needs (moved to a worker thread). +struct Job { + doc: Arc, + revision: u64, + layer: Option, + k: u32, + target_mask: bool, + /// The committed edits and, with Real-Time Refinement, the one being drawn. + edits: Vec, + extra: Option, + /// The refinement params with `__view` and `refineStrokes`. + params: Value, + cache: Option, + proxy: Option>, + display: Option>, + texture_limit: usize, + /// [`Shown::trail`] of this preview. + trail: usize, +} + +fn job(app: &PhotocraftApp) -> Option { + if stale(app).is_some() { + return None; + } + let w = app.distort.select_mask.as_ref()?; + let st = app.session.active()?; + let k = w.proxy_k(); + let mut params = w.opts.refine_params(); + params.insert("sampleAllLayers".into(), json!(w.sample_all)); + params.insert("__view".into(), w.opts.view_params()); + let gesture = w.gesture.as_ref().and_then(|g| w.finish(g)); + let mut strokes = w.strokes.clone(); + let mut extra = None; + match gesture { + Some(Ok(e)) if w.opts.real_time => extra = Some(e), + Some(Err(s)) if w.opts.real_time => strokes.push(s), + _ => {} + } + if !strokes.is_empty() { + params.insert("refineStrokes".into(), Value::Array(strokes)); + } + if w.target_mask { + params.insert("target".into(), json!("mask")); + } + let proxy = w.preview.proxy.as_ref().filter(|(pk, rev, _)| *pk == k && *rev == st.revision).map(|(_, _, d)| Arc::clone(d)); + Some(Job { + doc: Arc::clone(&st.doc), + revision: st.revision, + layer: w.layer, + k, + target_mask: w.target_mask, + edits: w.edits.clone(), + extra, + params: Value::Object(params), + cache: w.preview.cache.clone(), + proxy, + display: crate::canvas::canvas_display(app, &st.doc, None).0, + texture_limit: w.texture_limit, + trail: match &w.gesture { + Some(g) if w.opts.real_time => g.points.len(), + Some(_) => 0, + None => usize::MAX, + }, + }) +} + +/// Unit edges between selected (≥ ½) and unselected pixels of `m` (`w × h`, reduced by `k`), in +/// document px; `None` past [`MAX_ANT_EDGES`]. +fn ant_edges(m: &[f32], w: usize, h: usize, k: f32) -> Option> { + let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && m.get(y as usize * w + x as usize).is_some_and(|v| *v >= 0.5); + let mut out = Vec::new(); + for y in 0..h as i64 { + for x in 0..w as i64 { + if !at(x, y) { + continue; + } + let (fx, fy) = (x as f32, y as f32); + for (n, a, b) in [ + (at(x - 1, y), [fx, fy], [fx, fy + 1.0]), + (at(x + 1, y), [fx + 1.0, fy], [fx + 1.0, fy + 1.0]), + (at(x, y - 1), [fx, fy], [fx + 1.0, fy]), + (at(x, y + 1), [fx, fy + 1.0], [fx + 1.0, fy + 1.0]), + ] { + if !n { + out.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]); + } + } + if out.len() > MAX_ANT_EDGES { + return None; + } + } + } + Some(out) +} + +/// Count selected pixels without allocating a canvas-sized mask. Missing tiles use the surface's +/// default value, including an inverted selection whose default is selected. +fn selected_pixels(selection: Option<&Surface>, area: Rect) -> usize { + let Some(surface) = selection else { return 0 }; + let default_selected = surface.default_pixel().first().is_some_and(|v| *v >= 0.5); + let area_pixels = (area.width() as usize).saturating_mul(area.height() as usize); + let mut count = if default_selected { area_pixels } else { 0 }; + for (coord, _) in surface.tiles() { + let tile_area = coord.rect().intersect(&area); + if tile_area.is_empty() { + continue; + } + let pixels = (tile_area.width() as usize).saturating_mul(tile_area.height() as usize); + if default_selected { + count = count.saturating_sub(pixels); + } + let values = photocraft_algo::selection::mask_from_surface(Some(surface), tile_area); + count = count.saturating_add(values.iter().filter(|v| **v >= 0.5).count()); + } + count +} + +/// Generate ants only when the dense temporary mask fits the preview budget. +fn preview_ants(selection: Option<&Surface>, area: Rect, k: f32) -> Option> { + let (w, h) = (area.width() as usize, area.height() as usize); + if w.checked_mul(h).is_none_or(|n| n > MAX_ANT_PIXELS) { + return sparse_preview_ants(selection?, area, k); + } + let coverage = photocraft_algo::selection::mask_from_surface(selection, area); + ant_edges(&coverage, w, h, k) +} + +/// Follow sparse selections on large canvases without scanning the empty canvas. A selected +/// default or too many stored pixels falls back to omitting ants, as for too many edges. +fn sparse_preview_ants(surface: &Surface, area: Rect, k: f32) -> Option> { + if surface.default_pixel().first().is_some_and(|v| *v >= 0.5) { + return None; + } + let mut work = 0usize; + let mut edges = Vec::new(); + let mut sample = vec![0.0; surface.channels()]; + for (coord, _) in surface.tiles() { + let tile = coord.rect().intersect(&area); + if tile.is_empty() { + continue; + } + work = work.checked_add((tile.width() as usize).checked_mul(tile.height() as usize)?)?; + if work > MAX_ANT_PIXELS { + return None; + } + let coverage = photocraft_algo::selection::mask_from_surface(Some(surface), tile); + for y in tile.y0..tile.y1 { + for x in tile.x0..tile.x1 { + let index = (y - tile.y0) as usize * tile.width() as usize + (x - tile.x0) as usize; + if !coverage.get(index).is_some_and(|v| *v >= 0.5) { + continue; + } + let (fx, fy) = ((x - area.x0) as f32, (y - area.y0) as f32); + for (nx, ny, a, b) in [ + (x - 1, y, [fx, fy], [fx, fy + 1.0]), + (x + 1, y, [fx + 1.0, fy], [fx + 1.0, fy + 1.0]), + (x, y - 1, [fx, fy], [fx + 1.0, fy]), + (x, y + 1, [fx, fy + 1.0], [fx + 1.0, fy + 1.0]), + ] { + let selected = if nx < area.x0 || nx >= area.x1 || ny < area.y0 || ny >= area.y1 { + false + } else { + surface.read_pixel(nx, ny, &mut sample); + sample.first().is_some_and(|v| *v >= 0.5) + }; + if !selected { + edges.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]); + if edges.len() > MAX_ANT_EDGES { + return None; + } + } + } + } + } + } + Some(edges) +} + +/// The preview of `job`: the edits applied (from where the cache left off), the edge refined and +/// the result shown in the view, as an image no wider than the device allows. +fn compute(job: Job, cancel: Option<&photocraft_engine::jobs::JobCtx>) -> Result<(Shown, BaseCache, Arc), String> { + let k = job.k.max(1); + let proxy = job.proxy.unwrap_or_else(|| Arc::new(crate::proxy::proxy_document(&job.doc, k))); + let mut doc = (*proxy).clone(); + let layer = job.layer.filter(|id| doc.layer(*id).is_some()); + let mut params = job.params; + let start = || { + let mask = layer.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref()).map(|m| m.surface.clone()); + if job.target_mask { mask.or_else(|| doc.selection.clone()) } else { doc.selection.clone().or(mask) } + }; + let scaled = |list: &[Value]| -> Result, String> { + let list: Vec = list.iter().map(|e| scale_edit(e, k)).collect(); + select_mask_edits::parse(&json!({ "edits": list })).map_err(|e| e.to_string()) + }; + // With no edits yet, the selection Select and Mask starts from is where the first one starts. + let mut cache = BaseCache { k, revision: job.revision, edits: Vec::new(), base: start() }; + if !job.edits.is_empty() || job.extra.is_some() { + // The selection after the edits already applied, when they still lead the list. + let (from, done) = match job.cache.filter(|c| c.k == k && c.revision == job.revision && job.edits.starts_with(&c.edits)) { + Some(c) => (c.base, c.edits.len()), + None => (start(), 0), + }; + let rest = scaled(job.edits.get(done..).unwrap_or_default())?; + let base = select_mask_edits::apply(&doc, layer, from, &rest); + cache = BaseCache { k, revision: job.revision, edits: job.edits.clone(), base: base.clone() }; + let base = match &job.extra { + Some(e) => select_mask_edits::apply(&doc, layer, base, &scaled(std::slice::from_ref(e))?), + None => base, + }; + // Nothing selected is an empty selection, not "use the layer mask". + doc.selection = Some(base.unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8))); + if let Some(o) = params.as_object_mut() { + o.remove("target"); + } + } + let shown = crate::select_mask_view::preview_proxy(doc, layer, ¶ms, k, cancel); + if cancel.is_some_and(photocraft_engine::jobs::JobCtx::cancelled) { + return Err("cancelled".into()); + } + let shown = shown.ok_or("the preview failed")?; + let (pw, ph) = (shown.size.width as usize, shown.size.height as usize); + let f = crate::filter_preview_ui::texture_factor(shown.size.width, shown.size.height, job.texture_limit) as usize; + let (tw, th) = (pw.div_ceil(f.max(1)), ph.div_ceil(f.max(1))); + let buf = photocraft_compose::render_reduced(&shown, u32::try_from(tw).unwrap_or(1), u32::try_from(th).unwrap_or(1)); + let image = crate::canvas::display_image(job.display.as_deref(), &buf); + let selected = selected_pixels(shown.selection.as_ref(), shown.bounds()); + let mode = params.get("__view").and_then(|v| v.get("mode")).and_then(Value::as_str); + let ants = if mode == Some(Mode::MarchingAnts.id()) { preview_ants(shown.selection.as_ref(), shown.bounds(), k as f32) } else { None }; + let covers = [(pw as f32) * k as f32, (ph as f32) * k as f32]; + Ok((Shown { image, ants, selected, trail: job.trail, covers }, cache, proxy)) +} + +/// Takes the preview of state `generation` (made from document `revision`): the image when it is +/// still the state wanted (or a stroke is being drawn: Real-Time Refinement shows the latest one +/// it has), and the selection after the edits and the reduced copy for the next preview. +fn take_result(w: &mut SelectMaskWorkspace, generation: u64, revision: u64, r: Result<(Shown, BaseCache, Arc), String>) { + // Made from pixels the document no longer has (even mid-stroke). + if revision != w.revision { + return; + } + let pv = &mut w.preview; + match r { + Ok((shown, cache, proxy)) => { + pv.proxy = Some((cache.k, revision, proxy)); + pv.cache = Some(cache); + if generation == pv.want || w.pressed { + pv.trail = shown.trail; + if shown.trail == usize::MAX { + w.trail = None; + } + pv.shown = generation; + pv.selected = shown.selected; + pv.error = None; + pv.pending = Some(shown); + } + } + Err(e) if e == "cancelled" => {} + Err(e) => { + pv.shown = generation; + pv.error = Some(e); + } + } +} + +/// Computes the preview now, on this thread (tests and the control channel). +fn wait_preview(app: &mut PhotocraftApp) -> Result<(), String> { + drop_stale(app)?; + follow_revision(app); + let j = job(app).ok_or("Select and Mask is not open")?; + let revision = j.revision; + let r = compute(j, None); + let w = app.distort.select_mask.as_mut().ok_or("Select and Mask is not open")?; + let err = r.as_ref().err().cloned(); + let generation = w.preview.want; + take_result(w, generation, revision, r); + err.map_or(Ok(()), Err) +} + +/// Starts a background preview when the shown one is out of date, and collects a finished one. +/// While a stroke is drawn with Real-Time Refinement, a running preview is let finish (cancelling +/// it on every move would never show one) and the next starts from the latest state. +#[cfg(not(target_arch = "wasm32"))] +fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(w) = app.distort.select_mask.as_mut() else { return }; + if let Some((generation, revision, rx, _)) = &w.preview.running { + match rx.try_recv() { + Ok(r) => { + let (generation, revision) = (*generation, *revision); + w.preview.running = None; + take_result(w, generation, revision, r); + } + Err(std::sync::mpsc::TryRecvError::Empty) => { + if *generation != w.preview.want + && !w.pressed + && let Some((_, _, _, job)) = &w.preview.running + { + job.cancel(); + } + ctx.request_repaint_after(std::time::Duration::from_millis(30)); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => w.preview.running = None, + } + } + let Some(w) = app.distort.select_mask.as_ref() else { return }; + let waiting = w.pressed && !w.opts.real_time; + if w.preview.running.is_some() || w.preview.shown == w.preview.want || waiting { + return; + } + let generation = w.preview.want; + let Some(j) = job(app) else { return }; + let revision = j.revision; + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let ctl = photocraft_engine::jobs::JobCtx::new(); + let work = ctl.clone(); + let repaint = ctx.clone(); + let spawned = std::thread::Builder::new().name("select-mask-preview".into()).spawn(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compute(j, Some(&work)))).unwrap_or_else(|_| Err("the preview failed".into())); + let _ = tx.send(r); + repaint.request_repaint(); + }); + let Some(w) = app.distort.select_mask.as_mut() else { return }; + match spawned { + Ok(_) => w.preview.running = Some((generation, revision, rx, ctl)), + Err(e) => w.preview.error = Some(format!("could not start the preview: {e}")), + } +} + +/// The web build has no threads: the preview is computed when the pointer comes up. +#[cfg(target_arch = "wasm32")] +fn drive_preview(app: &mut PhotocraftApp, _ctx: &egui::Context) { + let due = app.distort.select_mask.as_ref().is_some_and(|w| w.preview.shown != w.preview.want && !w.pressed); + if due { + let _ = wait_preview(app); + } +} + +/// Pointer in document coordinates (from the view or the control channel). +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + if drop_stale(app).is_err() { + return; + } + let Some(w) = app.distort.select_mask.as_mut() else { return }; + match ev { + ToolEvent::Down { x, y, .. } if w.tool == SmTool::Zoom => { + let f = if mods.alt { 0.5 } else { 2.0 }; + w.zoom = (w.zoom * f).clamp(0.01, 32.0); + w.center = [x, y]; + } + ToolEvent::Down { x, y, .. } => w.begin([x, y], mods.alt), + ToolEvent::Move { x, y, .. } => { + w.hover = Some([x, y]); + w.extend([x, y]); + } + ToolEvent::Up { x, y } => { + w.extend([x, y]); + w.end_gesture(); + } + } +} + +/// The workspace's keys (unless a text field has the keyboard): tools, brush size, views, undo. +pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + use egui::{Key, Modifiers}; + let Some(w) = app.distort.select_mask.as_mut() else { return }; + let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; + if ctx.input_mut(|i| i.consume_key(cmd_shift, Key::Z)) { + redo(w); + return; + } + if ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::Z)) { + undo(w); + return; + } + if egui::Popup::is_any_open(ctx) { + w.hide_view = false; + return; + } + let pressed = |k: Key, m: Modifiers| ctx.input_mut(|i| i.consume_key(m, k)); + if pressed(Key::W, Modifiers::SHIFT) { + w.pick(if w.w_tool == SmTool::Quick { SmTool::Object } else { SmTool::Quick }); + } + if pressed(Key::L, Modifiers::SHIFT) { + w.pick(if w.l_tool == SmTool::Lasso { SmTool::PolygonalLasso } else { SmTool::Lasso }); + } + for (k, t) in + [(Key::W, w.w_tool), (Key::R, SmTool::RefineEdge), (Key::B, SmTool::Brush), (Key::L, w.l_tool), (Key::H, SmTool::Hand), (Key::Z, SmTool::Zoom)] + { + if pressed(k, Modifiers::NONE) { + w.pick(t); + } + } + if pressed(Key::OpenBracket, Modifiers::NONE) { + let s = w.size(); + w.set_size((s * 0.9).min(s - 1.0)); + } + if pressed(Key::CloseBracket, Modifiers::NONE) { + let s = w.size(); + w.set_size((s * 1.1).max(s + 1.0)); + } + if (pressed(Key::Backspace, Modifiers::NONE) || pressed(Key::Delete, Modifiers::NONE)) + && let Some((_, pts)) = w.poly.as_mut() + { + pts.pop(); + if pts.is_empty() { + w.poly = None; + } + } + // The views: their letters, F cycles, J Show Edge, P Show Original; holding X shows the image. + let before = w.opts.clone(); + if pressed(Key::F, Modifiers::NONE) { + w.opts.view = w.opts.view.next(); + } + for m in Mode::ALL { + if pressed(m.key(), Modifiers::NONE) { + w.opts.view = m; + } + } + if pressed(Key::J, Modifiers::NONE) { + w.opts.show_edge = !w.opts.show_edge; + } + if pressed(Key::P, Modifiers::NONE) { + w.opts.show_original = !w.opts.show_original; + } + if w.opts != before { + w.stale(); + } + w.hide_view = ctx.input(|i| i.key_down(Key::X) && !i.modifiers.command && !i.modifiers.alt && !i.modifiers.ctrl); +} + +/// A view: screen px per document px and the document point at the centre of `area`. +#[derive(Clone, Copy)] +struct View { + area: ERect, + zoom: f32, + center: [f64; 2], +} + +impl View { + fn to_screen(self, p: [f64; 2]) -> Pos2 { + let c = self.area.center(); + pos2(c.x + ((p[0] - self.center[0]) as f32) * self.zoom, c.y + ((p[1] - self.center[1]) as f32) * self.zoom) + } + fn to_doc(self, s: Pos2) -> [f64; 2] { + let c = self.area.center(); + [self.center[0] + f64::from((s.x - c.x) / self.zoom), self.center[1] + f64::from((s.y - c.y) / self.zoom)] + } + fn rect(self, r: Rect) -> ERect { + ERect::from_min_max(self.to_screen([f64::from(r.x0), f64::from(r.y0)]), self.to_screen([f64::from(r.x1), f64::from(r.y1)])) + } +} + +/// Upload what changed: the document (for X and until the first preview) and a finished preview. +fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { + let need_image = app.distort.select_mask.as_ref().is_some_and(|w| w.image_tex.is_none()); + if need_image { + let img = app.session.active().map(|st| { + let (cw, ch) = (st.doc.size.width, st.doc.size.height); + let f = crate::filter_preview_ui::texture_factor(cw, ch, PROXY_SIDE); + let buf = photocraft_compose::render_reduced(&st.doc, cw.div_ceil(f.max(1)), ch.div_ceil(f.max(1))); + let (display, _) = crate::canvas::canvas_display(app, &st.doc, None); + crate::canvas::display_image(display.as_deref(), &buf) + }); + if let (Some(w), Some(img)) = (app.distort.select_mask.as_mut(), img) { + w.image_tex = Some(ctx.load_texture("select-mask-image", img, egui::TextureOptions::LINEAR)); + } + } + let Some(w) = app.distort.select_mask.as_mut() else { return }; + if let Some(s) = w.preview.pending.take() { + match &mut w.preview.tex { + Some(t) => t.set(s.image, egui::TextureOptions::LINEAR), + None => w.preview.tex = Some(ctx.load_texture("select-mask-preview", s.image, egui::TextureOptions::LINEAR)), + } + w.preview.ants = s.ants; + w.preview.covers = s.covers; + } +} + +/// A section of the Properties panel: a bold title that folds it, open by default. +fn section(ui: &mut egui::Ui, id: &str, title: &str, body: impl FnOnce(&mut egui::Ui)) { + egui::CollapsingHeader::new(egui::RichText::new(title).strong()).id_salt(id).default_open(true).show(ui, body); +} + +/// The options bar of the current tool. +fn options_bar(ui: &mut egui::Ui, w: &mut SelectMaskWorkspace) -> Option { + let mut edit = None; + crate::icons::button(ui, w.tool.icon(), 26.0, false, &w.tool.tip()); + ui.add_space(6.0); + if w.tool.edits() { + if crate::icons::button(ui, "plus", 26.0, w.add, tl!("Add")).clicked() { + w.add = true; + } + if crate::icons::button(ui, "minus", 26.0, !w.add, tl!("Subtract")).clicked() { + w.add = false; + } + ui.add_space(8.0); + } + if w.tool.brushes() { + ui.label(tl!("Size:")); + let mut size = w.size() as f32; + if widgets::value_field(ui, &mut size, 1.0..=5000.0, " px", 64.0).changed() { + w.set_size(f64::from(size)); + } + ui.add_space(6.0); + } + if w.tool == SmTool::Brush { + ui.label(tl!("Hardness:")); + widgets::value_field(ui, &mut w.hardness, 0.0..=100.0, "%", 56.0); + ui.add_space(6.0); + } + if matches!(w.tool, SmTool::Quick | SmTool::RefineEdge | SmTool::Object) && widgets::checkbox(ui, &mut w.sample_all, tl!("Sample All Layers")).changed() { + w.stale(); + } + if w.tool.edits() { + ui.add_space(8.0); + if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { + edit = Some(json!({"tool": "subject", "sampleAllLayers": w.sample_all})); + } + // Refine Hair needs hair detection PhotoCraft doesn't have yet (#2671): greyed, saying so. + ui.add_enabled_ui(false, |ui| widgets::secondary_button(ui, tl!("Refine Hair"), 0.0)) + .inner + .on_disabled_hover_text(tl!("Refine Hair needs hair detection, which isn't available yet")); + } + edit +} + +/// The Properties panel. Returns the tool edit its buttons made (Clear Selection, Invert). +fn properties(ui: &mut egui::Ui, w: &mut SelectMaskWorkspace, t: &Tokens) -> Option { + let mut edit = None; + ui.spacing_mut().item_spacing.y = 6.0; + widgets::checkbox(ui, &mut w.opts.remember, tl!("Remember Settings")); + widgets::hairline(ui); + section(ui, "sm-view", tl!("View Mode"), |ui| { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.label(egui::RichText::new(tl!("View")).color(t.text_dim)); + let labels: Vec = Mode::ALL.iter().map(|m| format!("{} ({:?})", m.label(), m.key())).collect(); + let options: Vec<(Mode, &str)> = Mode::ALL.iter().zip(&labels).map(|(m, l)| (*m, l.as_str())).collect(); + // The labels carry the view's letter, already translated. + widgets::dropdown_literal(ui, "sm-view-mode", tl!("View"), &mut w.opts.view, &options, 112.0); + }); + // Beside the view list, as Photoshop's; long labels are cut rather than widening the + // panel past its edge (every row below lines up on that edge). + let room = ui.available_width(); + ui.vertical(|ui| { + ui.set_max_width(room); + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + widgets::checkbox(ui, &mut w.opts.show_edge, &format!("{} (J)", tl!("Show Edge"))); + widgets::checkbox(ui, &mut w.opts.show_original, &format!("{} (P)", tl!("Show Original"))); + widgets::checkbox(ui, &mut w.opts.real_time, tl!("Real-Time Refinement")); + widgets::checkbox(ui, &mut w.opts.high_quality, tl!("High Quality Preview")); + }); + }); + let i = mode_index(w.opts.view); + if w.opts.view.default_opacity().is_some() { + let label = if w.opts.view == Mode::OnionSkin { tl!("Transparency") } else { tl!("Opacity") }; + if let Some(o) = w.opts.opacity.get_mut(i) { + widgets::slider_row(ui, label, o, 0.0..=100.0, "%", None); + } + } + if w.opts.view == Mode::Overlay { + ui.horizontal(|ui| { + ui.label(tl!("Color")); + widgets::color_edit_button_srgb(ui, &mut w.opts.overlay_color); + ui.add_space(8.0); + ui.label(tl!("Indicates")); + widgets::dropdown( + ui, + "sm-indicates", + tl!("Indicates"), + &mut w.opts.indicates_selected, + &[(false, tl!("Masked Areas")), (true, tl!("Selected Areas"))], + 120.0, + ); + }); + } + }); + section(ui, "sm-refine-mode", tl!("Refine Mode"), |ui| { + ui.horizontal(|ui| { + let _ = ui.selectable_label(true, tl!("Color Aware")); + // Object Aware needs a learned segmentation model (#2788). + ui.add_enabled_ui(false, |ui| ui.selectable_label(false, tl!("Object Aware"))) + .inner + .on_disabled_hover_text(tl!("Object Aware needs a segmentation model, which isn't available yet")); + }); + }); + section(ui, "sm-edge", tl!("Edge Detection"), |ui| { + widgets::slider_row(ui, tl!("Radius"), &mut w.opts.radius, 0.0..=250.0, " px", None); + widgets::checkbox(ui, &mut w.opts.smart_radius, tl!("Smart Radius")); + }); + section(ui, "sm-global", tl!("Global Refinements"), |ui| { + widgets::slider_row(ui, tl!("Smooth"), &mut w.opts.smooth, 0.0..=100.0, "", None); + widgets::slider_row(ui, tl!("Feather"), &mut w.opts.feather, 0.0..=1000.0, " px", None); + widgets::slider_row(ui, tl!("Contrast"), &mut w.opts.contrast, 0.0..=100.0, "%", None); + widgets::slider_row(ui, tl!("Shift Edge"), &mut w.opts.shift_edge, -100.0..=100.0, "%", None); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Clear Selection"), 0.0).clicked() { + edit = Some(json!({"tool": "clear"})); + } + if widgets::secondary_button(ui, tl!("Invert"), 0.0).clicked() { + edit = Some(json!({"tool": "invert"})); + } + }); + }); + section(ui, "sm-output", tl!("Output Settings"), |ui| { + widgets::checkbox(ui, &mut w.opts.decontaminate, tl!("Decontaminate Colors")); + ui.add_enabled_ui(w.opts.decontaminate, |ui| widgets::slider_row(ui, tl!("Amount"), &mut w.opts.amount, 0.0..=100.0, "%", None)); + w.opts.follow_decontaminate(); + ui.horizontal(|ui| { + ui.label(tl!("Output To")); + let labels = + [tl!("Selection"), tl!("Layer Mask"), tl!("New Layer"), tl!("New Layer With Mask"), tl!("New Document"), tl!("New Document With Mask")]; + // Decontaminating makes new pixels: only the new layer and document targets apply. + let options: Vec<(String, &str)> = OUTPUTS + .iter() + .zip(labels) + .filter(|(o, _)| !w.opts.decontaminate || !matches!(**o, "selection" | "layerMask")) + .map(|(o, l)| (o.to_string(), l)) + .collect(); + widgets::dropdown(ui, "sm-output-to", tl!("Output To"), &mut w.opts.output, &options, 170.0); + }); + }); + if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { + ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); + } + edit +} + +/// The document changed under the workspace: new textures, a new preview, and nothing of the old +/// one shown or reused. +fn follow_revision(app: &mut PhotocraftApp) { + let rev = app.session.active().map(|s| s.revision); + if let Some(w) = app.distort.select_mask.as_mut() + && Some(w.revision) != rev + { + w.revision = rev.unwrap_or(w.revision); + w.image_tex = None; + w.preview.tex = None; + w.preview.pending = None; + w.preview.cache = None; + w.stale(); + } +} + +/// Draws the document, the refined edge, the stroke being drawn and the polygon in progress. +fn paint_canvas(ui: &mut egui::Ui, ctx: &egui::Context, w: &mut SelectMaskWorkspace, t: &Tokens, painter: &egui::Painter, resp: &egui::Response, area: ERect) { + let v = View { area, zoom: w.zoom, center: w.center }; + let clip = painter.with_clip_rect(area); + let img = v.rect(w.canvas); + let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + widgets::checker(&clip, img.intersect(area), 8.0); + let preview = w.preview.tex.as_ref().filter(|_| !w.hide_view); + match (preview, &w.image_tex) { + (Some(tex), _) => { + // The reduced copy's last row and column may reach past the canvas. + let covers = ERect::from_min_size(img.min, vec2(w.preview.covers[0] * v.zoom, w.preview.covers[1] * v.zoom)); + clip.with_clip_rect(img.intersect(area)).image(tex.id(), covers, uv, Color32::WHITE); + } + (None, Some(tex)) => { + clip.image(tex.id(), img, uv, Color32::WHITE); + } + (None, None) => {} + } + // Marching Ants: the refined selection's edge, black dashes on white. + if !w.hide_view + && w.opts.view == Mode::MarchingAnts + && let Some(edges) = &w.preview.ants + { + let phase = (ui.input(|i| i.time) * 8.0) as usize; + for e in edges { + let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); + let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); + clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); + } + ctx.request_repaint_after(std::time::Duration::from_millis(120)); + } + if w.preview.shown != w.preview.want && !w.pressed { + let sp = ERect::from_min_size(area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); + ui.put(sp, egui::Spinner::new().size(16.0)); + } + // The stroke being drawn: the part the preview doesn't show yet (all of it without + // Real-Time Refinement), joined to the part it does, so the stroke follows the pointer. + let ink = Color32::from_rgba_unmultiplied(t.accent.r(), t.accent.g(), t.accent.b(), 110); + if let Some(g) = w.gesture.as_ref().or(w.trail.as_ref()) { + let line: Vec = g.points.iter().map(|p| v.to_screen(*p)).collect(); + match g.tool { + SmTool::Quick | SmTool::Brush | SmTool::RefineEdge if w.preview.trail != usize::MAX => { + let tail = line.get(w.preview.trail.saturating_sub(1)..).unwrap_or_default(); + let r = w.size() as f32 * 0.5 * v.zoom; + for p in tail { + clip.circle_filled(*p, r, ink); + } + if tail.len() > 1 { + clip.add(egui::Shape::line(tail.to_vec(), Stroke::new(2.0 * r, ink))); + } + } + SmTool::Lasso => { + clip.add(egui::Shape::line(line, Stroke::new(1.0, t.accent))); + } + SmTool::Object => { + if let (Some(a), Some(b)) = (line.first(), line.last()) { + clip.rect_stroke(ERect::from_two_pos(*a, *b), 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Middle); + } + } + _ => {} + } + } + if let Some((_, pts)) = &w.poly { + let mut line: Vec = pts.iter().map(|p| v.to_screen(*p)).collect(); + if let Some(hp) = resp.hover_pos() { + line.push(hp); + } + clip.add(egui::Shape::line(line, Stroke::new(1.0, t.accent))); + } +} + +/// The cursor over the document, and the image's outline. +fn paint_cursor(ctx: &egui::Context, w: &mut SelectMaskWorkspace, clip: &egui::Painter, resp: &egui::Response, v: View, pan: bool, alt: bool) { + let (img, t) = (v.rect(w.canvas), Tokens::get(ctx)); + // The cursor: Photoshop's hand while panning (closed while dragging), the brush's circle + // (with + or −), the zoom glass, else a crosshair. + if let Some(hp) = resp.hover_pos() { + w.hover = Some(v.to_doc(hp)); + } + if pan && (resp.dragged() || resp.is_pointer_button_down_on()) { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } else if let Some(hp) = resp.hover_pos() { + if pan { + ctx.set_cursor_icon(egui::CursorIcon::Grab); + } else if w.tool.brushes() { + let r = (w.size() as f32 * 0.5 * v.zoom).max(2.0); + clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK)); + clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE)); + let add = w.add != alt; + for s in [Stroke::new(2.5, Color32::from_black_alpha(140)), Stroke::new(1.0, Color32::from_white_alpha(220))] { + clip.line_segment([hp - vec2(3.0, 0.0), hp + vec2(3.0, 0.0)], s); + if add { + clip.line_segment([hp - vec2(0.0, 3.0), hp + vec2(0.0, 3.0)], s); + } + } + ctx.set_cursor_icon(egui::CursorIcon::None); + } else { + ctx.set_cursor_icon(match w.tool { + SmTool::Zoom if alt => egui::CursorIcon::ZoomOut, + SmTool::Zoom => egui::CursorIcon::ZoomIn, + _ => egui::CursorIcon::Crosshair, + }); + } + } + clip.rect_stroke(img, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); +} + +/// Pan, zoom-click and tool gestures on the document, as events for `pointer`. +#[allow(clippy::too_many_arguments)] +fn canvas_input( + ui: &egui::Ui, + ctx: &egui::Context, + w: &mut SelectMaskWorkspace, + resp: &egui::Response, + v: View, + pan: bool, + events: &mut Vec, + mods: &mut egui::Modifiers, +) { + if pan && resp.dragged() { + let dl = resp.drag_delta(); + w.center = [w.center[0] - f64::from(dl.x / w.zoom), w.center[1] - f64::from(dl.y / w.zoom)]; + } else if w.tool == SmTool::PolygonalLasso && !pan { + *mods = ui.input(|i| i.modifiers); + if resp.double_clicked() { + w.close_polygon(); + } else if resp.clicked() + && let Some(pp) = resp.interact_pointer_pos() + { + let q = v.to_doc(pp); + events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 }); + } + } else if !pan + && resp.is_pointer_button_down_on() + && let Some(pp) = resp.interact_pointer_pos() + { + let q = v.to_doc(pp); + *mods = ui.input(|i| i.modifiers); + if w.pressed { + events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: 1.0 }); + ctx.request_repaint(); + } else { + w.pressed = true; + events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 }); + } + } + if w.pressed && !resp.is_pointer_button_down_on() { + w.pressed = false; + let q = w.hover.unwrap_or(w.center); + events.push(ToolEvent::Up { x: q[0], y: q[1] }); + } +} + +/// Draws the workspace (a full-window layer over the app). +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + follow_revision(app); + upload(app, ctx); + let title = app.distort.select_mask.as_ref().map(|w| { + crate::canvas::tab_title_at( + app, + app.session.documents().iter().position(|d| d.doc.id == w.document).unwrap_or(0), + if w.zoom > 0.0 { w.zoom * 100.0 } else { 100.0 }, + ) + }); + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let mut action: Option<&str> = None; + let mut events: Vec = Vec::new(); + let mut mods = egui::Modifiers::NONE; + let mut edit: Option = None; + let mut do_reset = false; + egui::Area::new(egui::Id::unique("select-mask-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { + let Some(w) = app.distort.select_mask.as_mut() else { return }; + let before = (w.opts.clone(), w.sample_all); + w.texture_limit = ctx.input(|i| i.max_texture_side); + let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover()); + let painter = ui.painter().clone(); + painter.rect_filled(full, 0.0, t.chrome); + // The options bar across the top, as Photoshop's. + let bar = ERect::from_min_size(full.min, vec2(full.width(), BAR_H)); + painter.rect_filled(bar, 0.0, t.dock); + painter.line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.separator)); + let mut bui = ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some(e) = options_bar(&mut bui, w) { + edit = Some(e); + } + let body = ERect::from_min_max(pos2(full.left(), bar.bottom()), full.max); + // The tools on the left: Lasso and Polygonal Lasso share a slot (right-click to pick). + let left = ERect::from_min_size(body.min, vec2(LEFT_W, body.height())); + painter.rect_filled(left, 0.0, t.dock); + painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); + let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); + strip.spacing_mut().item_spacing.y = 4.0; + for slot in [SmTool::Quick, SmTool::RefineEdge, SmTool::Brush, SmTool::Object, w.l_tool, SmTool::Hand, SmTool::Zoom] { + let r = crate::icons::button(&mut strip, slot.icon(), 34.0, w.tool == slot, &slot.tip()); + if r.clicked() { + w.pick(slot); + } + if matches!(slot, SmTool::Lasso | SmTool::PolygonalLasso) { + // The slot's flyout triangle, as the main toolbar's. + let c = r.rect.right_bottom() - vec2(3.0, 3.0); + painter.add(egui::Shape::convex_polygon(vec![c, c - vec2(5.0, 0.0), c - vec2(0.0, 5.0)], t.icon, Stroke::NONE)); + r.context_menu(|ui| { + for l in [SmTool::Lasso, SmTool::PolygonalLasso] { + if ui.selectable_label(w.tool == l, l.tip()).clicked() { + w.pick(l); + ui.close(); + } + } + }); + } + } + // The Properties panel on the right. + let right = ERect::from_min_size(pos2(body.right() - PANEL_W, body.top()), vec2(PANEL_W, body.height())); + painter.rect_filled(right, 0.0, t.dock); + painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); + let head = ERect::from_min_size(right.min, vec2(PANEL_W, TAB_H)); + painter.line_segment([head.left_bottom(), head.right_bottom()], Stroke::new(1.0, t.separator)); + painter.text(head.left_center() + vec2(12.0, 0.0), Align2::LEFT_CENTER, tl!("Properties"), FontId::proportional(12.0), t.text); + let mut props = ui.new_child( + egui::UiBuilder::new().max_rect(ERect::from_min_max(head.left_bottom() + vec2(14.0, 10.0), pos2(right.right() - 14.0, right.bottom() - 56.0))), + ); + egui::ScrollArea::vertical().id_salt("sm-props").show(&mut props, |ui| { + if let Some(e) = properties(ui, w, &t) { + edit = Some(e); + } + }); + // Reset at the left, OK and Cancel against the right edge. + let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 46.0), vec2(PANEL_W - 20.0, 32.0)); + painter.line_segment([pos2(right.left(), foot.top() - 6.0), pos2(right.right(), foot.top() - 6.0)], Stroke::new(1.0, t.separator)); + let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); + if widgets::secondary_button(&mut fb, tl!("Cancel"), 70.0).clicked() { + action = Some("cancel"); + } + if widgets::primary_button(&mut fb, tl!("OK"), 64.0).clicked() { + action = Some("ok"); + } + fb.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 24.0, false, tl!("Reset")).clicked() { + do_reset = true; + } + }); + // The document under its tab. + let doc_area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(right.left(), body.bottom())); + let tab = ERect::from_min_size(doc_area.min, vec2(doc_area.width(), TAB_H)); + painter.rect_filled(tab, 0.0, t.dock); + painter.line_segment([tab.left_bottom(), tab.right_bottom()], Stroke::new(1.0, t.separator)); + let title = title.clone().unwrap_or_default(); + let galley = painter.layout_no_wrap(title, FontId::proportional(12.0), t.text); + let tab_w = (galley.size().x + 28.0).min(tab.width()); + let active_tab = ERect::from_min_size(tab.min, vec2(tab_w, TAB_H)); + painter.rect_filled(active_tab, 0.0, t.canvas); + painter.galley(pos2(active_tab.left() + 14.0, active_tab.center().y - galley.size().y / 2.0), galley, t.text); + let area = ERect::from_min_max(pos2(doc_area.left(), tab.bottom()), doc_area.max); + painter.rect_filled(area, 0.0, t.canvas); + let (cw, chh) = (w.canvas.width() as f32, w.canvas.height() as f32); + if w.zoom <= 0.0 { + w.zoom = ((area.width() - 40.0) / cw.max(1.0)).min((area.height() - 40.0) / chh.max(1.0)).clamp(0.01, 4.0); + } + let resp = ui.interact(area, egui::Id::unique("select-mask-view"), Sense::click_and_drag()); + // Over the image the keys are the workspace's: a panel button clicked last keeps the focus + // otherwise, and Space (held to pan) would press it again. A number being typed keeps it. + if resp.hovered() + && !ctx.text_edit_focused() + && let Some(focus) = ctx.memory(|m| m.focused()) + { + ctx.memory_mut(|m| m.surrender_focus(focus)); + } + if resp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 + && let Some(hp) = resp.hover_pos() + { + let v = View { area, zoom: w.zoom, center: w.center }; + let at = v.to_doc(hp); + w.zoom = (w.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + let after = View { area, zoom: w.zoom, center: w.center }.to_doc(hp); + w.center = [w.center[0] + at[0] - after[0], w.center[1] + at[1] - after[1]]; + } + } + let v = View { area, zoom: w.zoom, center: w.center }; + paint_canvas(ui, ctx, w, &t, &painter, &resp, area); + // Space, the middle button or the Hand pan. The Polygonal Lasso takes clicks: each adds a + // vertex, a double-click closes. + let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == SmTool::Hand; + paint_cursor(ctx, w, &painter.with_clip_rect(area), &resp, v, pan, ui.input(|i| i.modifiers.alt)); + canvas_input(ui, ctx, w, &resp, v, pan, &mut events, &mut mods); + if (w.opts.clone(), w.sample_all) != before { + w.stale(); + } + }); + for ev in events { + pointer(app, ev, mods); + } + if let Some(w) = app.distort.select_mask.as_mut() { + if let Some(e) = edit { + w.add_edit(e); + } + if do_reset { + reset(w); + } + } + drive_preview(app, ctx); + match action { + Some("ok") => { + let _ = commit(app); + } + Some("cancel") => cancel(app), + _ => {} + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs new file mode 100644 index 0000000000..7df542fe74 --- /dev/null +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -0,0 +1,794 @@ +use super::*; +use egui::{Key, Modifiers}; +use egui_kittest::kittest::{NodeT, Queryable}; + +/// A 160 × 100 document: warm on the left (x < 80), cool on the right, with the top-left +/// 20 × 20 selected. +fn app_with_selection() -> PhotocraftApp { + app_sized(160, 100) +} + +fn app_sized(w: i32, h: i32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": w, "height": h, "depth": 8})).unwrap(); + app.session + .edit("paint", |doc, _| { + let s = doc.layers[0].surface_mut().unwrap(); + s.fill_rect(Rect::new(0, 0, w / 2, h), &[0.85, 0.55, 0.25, 1.0]); + s.fill_rect(Rect::new(w / 2, 0, w, h), &[0.15, 0.35, 0.75, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + app.session.prefs.edit(|p| { + p.dialogs.remove(REMEMBERED); + }); + app.sync_views(); + app +} + +fn ws(app: &PhotocraftApp) -> &SelectMaskWorkspace { + app.distort.select_mask.as_ref().unwrap() +} + +fn ui(app: &mut PhotocraftApp, v: Value) -> Value { + control(app, &v).unwrap() +} + +fn selected(app: &mut PhotocraftApp) -> u64 { + ui(app, json!({"waitPreview": true}))["selectedProxyPixels"].as_u64().unwrap() +} + +fn cov(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0)) +} + +/// Photoshop opens on Quick Selection adding, the Onion Skin view, Real-Time Refinement on, and +/// output to the selection. +#[test] +fn opens_like_photoshop() { + let mut app = app_with_selection(); + crate::menus::invoke(&mut app, &egui::Context::default(), "select.selectAndMask", json!({})).unwrap(); + let d = ws(&app).describe(); + assert_eq!((d["tool"].as_str(), d["mode"].as_str(), d["size"].as_f64()), (Some("quick"), Some("add"), Some(30.0))); + let s = &d["settings"]; + assert_eq!((s["view"].as_str(), s["output"].as_str()), (Some("onionSkin"), Some("selection"))); + assert_eq!((s["realTimeRefinement"].as_bool(), s["highQualityPreview"].as_bool(), s["remember"].as_bool()), (Some(true), Some(false), Some(false))); + assert_eq!((s["opacity"]["onionSkin"].as_f64(), s["opacity"]["onBlack"].as_f64()), (Some(50.0), Some(100.0))); + assert_eq!(selected(&mut app), 400, "the 20 × 20 selection"); + assert!(ws(&app).describe()["previewReady"].as_bool().unwrap()); +} + +#[test] +fn opening_needs_a_selection_or_a_layer_mask() { + let mut app = app_with_selection(); + app.session.execute("select.deselect", json!({})).unwrap(); + assert!(open(&mut app).is_err()); + assert!(app.distort.select_mask.is_none()); + // `ui` addresses an open workspace only. + let e = crate::distort_ui::menu(&mut app, &egui::Context::default(), "select.selectAndMask", &json!({"ui": {}})).unwrap(); + assert!(e.is_err()); +} + +/// Every tool's stroke is an edit (the Refine Edge Brush's a stroke), each one undoable. +#[test] +fn tools_make_edits_and_undo_and_redo_them() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let before = selected(&mut app); + // Quick Selection across the cool half grows the selection over it. + ui(&mut app, json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}})); + let quick = selected(&mut app); + assert!(quick > before + 3000, "{before} → {quick}"); + // Brush, Lasso and Polygonal Lasso subtract with Alt. + ui(&mut app, json!({"tool": "brush", "size": 10, "hardness": 50, "stroke": {"points": [[100.0, 10.0], [100.0, 90.0]], "alt": true}})); + let brushed = selected(&mut app); + assert!(brushed < quick, "{quick} → {brushed}"); + ui(&mut app, json!({"tool": "lasso", "mode": "subtract", "stroke": {"points": [[140.0, 0.0], [160.0, 0.0], [160.0, 100.0], [140.0, 100.0]]}})); + ui(&mut app, json!({"tool": "polygonalLasso", "mode": "add", "stroke": {"points": [[30.0, 30.0], [50.0, 30.0], [50.0, 50.0]]}})); + ui(&mut app, json!({"tool": "refineEdge", "stroke": {"points": [[80.0, 20.0], [80.0, 80.0]]}})); + let d = ws(&app).describe(); + assert_eq!((d["edits"].as_u64(), d["strokes"].as_u64(), d["undo"].as_u64()), (Some(4), Some(1), Some(5))); + let e = &ws(&app).edits; + assert_eq!( + (e[1]["tool"].as_str(), e[1]["mode"].as_str(), e[1]["hardness"].as_f64(), e[1]["size"].as_f64()), + (Some("brush"), Some("subtract"), Some(50.0), Some(10.0)) + ); + assert_eq!((e[2]["tool"].as_str(), e[2]["mode"].as_str()), (Some("lasso"), Some("subtract"))); + assert_eq!((e[3]["tool"].as_str(), e[3]["points"].as_array().map(Vec::len)), (Some("lasso"), Some(3))); + // Undo everything but the Quick Selection stroke, then redo the Brush's. + for _ in 0..4 { + ui(&mut app, json!({"undo": true})); + } + assert_eq!(selected(&mut app), quick); + ui(&mut app, json!({"redo": true})); + assert_eq!(selected(&mut app), brushed); + // A new edit drops what could be redone. + ui(&mut app, json!({"invert": true})); + assert_eq!(ws(&app).describe()["redo"].as_u64(), Some(0)); +} + +/// Object Selection: a click picks the object under it, a drag the object in the rectangle. +#[test] +fn object_selection_clicks_and_drags() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ws_mut(&mut app).zoom = 1.0; + ui(&mut app, json!({"tool": "object", "stroke": {"points": [[120.0, 50.0], [121.0, 50.0]]}})); + ui(&mut app, json!({"stroke": {"points": [[90.0, 10.0], [150.0, 90.0]]}})); + let e = &ws(&app).edits; + assert_eq!(e[0]["point"], json!([120.0, 50.0])); + assert_eq!(e[1]["rect"], json!([90.0, 10.0, 60.0, 80.0])); +} + +fn ws_mut(app: &mut PhotocraftApp) -> &mut SelectMaskWorkspace { + app.distort.select_mask.as_mut().unwrap() +} + +/// Select Subject, Clear Selection and Invert are edits too; Reset drops everything at once, +/// undoably. +#[test] +fn buttons_and_reset() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"clearSelection": true})); + assert_eq!(selected(&mut app), 0); + ui(&mut app, json!({"invert": true})); + assert_eq!(selected(&mut app), 160 * 100); + ui(&mut app, json!({"selectSubject": true})); + assert_eq!(ws(&app).edits.last().and_then(|e| e["tool"].as_str()), Some("subject")); + ui(&mut app, json!({"radius": 12, "view": "blackWhite", "remember": true})); + let d = ui(&mut app, json!({"reset": true})); + assert_eq!((d["edits"].as_u64(), d["settings"]["radius"].as_f64(), d["settings"]["view"].as_str()), (Some(0), Some(0.0), Some("onionSkin"))); + assert_eq!(d["settings"]["remember"].as_bool(), Some(true), "Reset keeps Remember Settings"); + assert_eq!(selected(&mut app), 400); + let d = ui(&mut app, json!({"undo": true})); + assert_eq!((d["edits"].as_u64(), d["settings"]["radius"].as_f64()), (Some(3), Some(12.0))); +} + +/// OK runs `select.refineEdge` with the edits, strokes and settings: one history step, the same +/// result as the command with those params, and the workspace closes. +#[test] +fn ok_is_one_step_and_matches_the_command() { + let mut app = app_with_selection(); + let mut direct = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"radius": 2, "stroke": {"points": [[120.0, 50.0]]}})); + ui(&mut app, json!({"tool": "brush", "stroke": {"points": [[40.0, 60.0], [60.0, 60.0]]}})); + let params = commit_params(ws(&app)); + let steps = app.session.active().unwrap().history.past_len(); + let r = ui(&mut app, json!({"commit": true})); + assert_eq!(r["committed"], json!(true)); + assert!(app.distort.select_mask.is_none(), "OK closes"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Select and Mask")); + direct.session.execute(CMD, params).unwrap(); + for (x, y) in [(5, 5), (120, 50), (50, 60), (50, 80), (79, 50)] { + assert_eq!(cov(&app, x, y), cov(&direct, x, y), "({x}, {y})"); + } + assert!(cov(&app, 120, 50) > 0.5 && cov(&app, 50, 60) > 0.5 && cov(&app, 50, 80) < 0.5); +} + +/// Cancel leaves the document as it was. +#[test] +fn cancel_changes_nothing() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"invert": true, "radius": 10})); + let steps = app.session.active().unwrap().history.past_len(); + let r = ui(&mut app, json!({"cancel": true})); + assert_eq!(r["cancelled"], json!(true)); + assert!(app.distort.select_mask.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert!(cov(&app, 5, 5) > 0.99 && cov(&app, 100, 50) < 0.01); +} + +/// Remember Settings keeps the settings for the next time; without it the workspace opens on +/// Photoshop's defaults. +#[test] +fn remember_settings() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"remember": true, "radius": 7, "view": "overlay", "overlayColor": [0, 0, 255], "commit": true})); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + open(&mut app).unwrap(); + let s = ws(&app).describe()["settings"].clone(); + assert_eq!((s["radius"].as_f64(), s["view"].as_str(), s["overlayColor"].clone()), (Some(7.0), Some("overlay"), json!([0, 0, 255]))); + ui(&mut app, json!({"remember": false, "commit": true})); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + open(&mut app).unwrap(); + let s = ws(&app).describe()["settings"].clone(); + assert_eq!((s["radius"].as_f64(), s["view"].as_str()), (Some(0.0), Some("onionSkin"))); +} + +/// Decontaminate Colors makes new pixels, so it outputs to a new layer (as Photoshop does). +#[test] +fn decontaminate_outputs_to_a_new_layer() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let d = ui(&mut app, json!({"decontaminate": true})); + assert_eq!(d["settings"]["output"].as_str(), Some("newLayerWithMask")); + let d = ui(&mut app, json!({"output": "newDocument"})); + assert_eq!(d["settings"]["output"].as_str(), Some("newDocument")); + let d = ui(&mut app, json!({"output": "selection"})); + assert_eq!(d["settings"]["output"].as_str(), Some("newLayerWithMask")); +} + +/// A layer mask without a selection (or the targeted mask) is refined and output to the mask. +#[test] +fn a_layer_mask_opens_on_the_mask() { + let mut app = app_with_selection(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + // Revealing the selection uses it up (#8381), leaving the mask alone. + app.session.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_none()); + open(&mut app).unwrap(); + assert_eq!(ws(&app).describe()["settings"]["output"].as_str(), Some("layerMask")); + assert_eq!(selected(&mut app), 400, "the mask is what is shown"); +} + +/// Bad control params are errors, never a panic, and change nothing. +#[test] +fn hostile_control_params_are_errors() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + for bad in [ + json!({"tool": "wand"}), + json!({"mode": "intersect"}), + json!({"view": "sideways"}), + json!({"output": "printer"}), + json!({"indicates": "both"}), + json!({"stroke": {"points": "x"}}), + json!({"stroke": {"points": [[1.0]]}}), + ] { + assert!(control(&mut app, &bad).is_err(), "{bad}"); + } + for odd in [json!({"size": -5}), json!({"size": 1e12}), json!({"hardness": 500}), json!({"radius": 1e9, "opacity": -3}), json!({"stroke": {"points": []}})] + { + control(&mut app, &odd).unwrap(); + } + let d = ws(&app).describe(); + assert_eq!((d["tool"].as_str(), d["edits"].as_u64()), (Some("quick"), Some(0))); + assert_eq!((d["size"].as_f64(), d["hardness"].as_f64(), d["settings"]["radius"].as_f64()), (Some(5000.0), Some(100.0), Some(250.0))); + assert!(control(&mut app, &json!({"waitPreview": true})).is_ok(), "the clamped settings still preview"); +} + +/// High Quality Preview runs on the document at full size; otherwise on a copy at most 1600 px. +#[test] +fn high_quality_preview_is_full_size() { + let mut app = app_sized(3300, 60); + open(&mut app).unwrap(); + assert_eq!(ws(&app).describe()["proxyScale"].as_u64(), Some(3)); + let reduced = selected(&mut app); + assert!((40..=60).contains(&reduced), "{reduced} reduced px of the 20 × 20 selection"); + assert_eq!(ui(&mut app, json!({"highQualityPreview": true}))["proxyScale"].as_u64(), Some(1)); + assert_eq!(selected(&mut app), 400); +} + +/// Edits scale with the reduced copy: points, rectangles and sizes by 1 / k. +#[test] +fn edits_scale_to_the_reduced_copy() { + let e = json!({"tool": "quick", "points": [[30.0, 60.0]], "size": 30.0, "rect": [3, 6, 9, 12], "point": [15, 3]}); + assert_eq!(scale_edit(&e, 3), json!({"tool": "quick", "points": [[10.0, 20.0]], "size": 10.0, "rect": [1.0, 2.0, 3.0, 4.0], "point": [5.0, 1.0]})); + assert_eq!(scale_edit(&json!({"size": 2.0}), 4)["size"], json!(1.0), "never below a pixel"); + assert_eq!(scale_edit(&json!("x"), 2), json!("x")); +} + +/// With Real-Time Refinement the stroke being drawn is in the preview before it is released. +#[test] +fn real_time_refinement_previews_the_stroke_being_drawn() { + for real_time in [true, false] { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"realTimeRefinement": real_time})); + let before = selected(&mut app); + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 120.0, y: 50.0, pressure: 1.0 }, Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Move { x: 130.0, y: 50.0, pressure: 1.0 }, Modifiers::NONE); + let during = selected(&mut app); + assert_eq!(during > before, real_time, "real time {real_time}: {before} → {during}"); + // The preview knows how much of the stroke it shows: the rest is drawn over it. + assert_eq!(ws(&app).preview.trail, if real_time { 2 } else { 0 }); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 130.0, y: 50.0 }, Modifiers::NONE); + assert!(ws(&app).trail.is_some(), "the released stroke stays drawn until its preview comes"); + assert!(selected(&mut app) > before); + assert_eq!(ws(&app).edits.len(), 1); + assert!(ws(&app).trail.is_none() && ws(&app).preview.trail == usize::MAX, "then the preview shows all of it"); + } +} + +/// A stroke refused at the engine's limits leaves nothing drawn: no trail, and a preview without it. +#[test] +fn a_refused_stroke_leaves_no_trail_or_preview() { + for tool in ["quick", "refineEdge"] { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"tool": tool})); + let w = ws_mut(&mut app); + if tool == "quick" { + w.edits = vec![json!({"tool": "invert"}); MAX_EDITS]; + } else { + w.strokes = vec![json!({"points": []}); MAX_STROKES]; + } + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 120.0, y: 50.0, pressure: 1.0 }, Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Move { x: 130.0, y: 50.0, pressure: 1.0 }, Modifiers::NONE); + let want = ws(&app).preview.want; + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 130.0, y: 50.0 }, Modifiers::NONE); + let w = ws(&app); + assert!(w.error.as_deref().is_some_and(|e| e.starts_with("at most")), "{tool}: {:?}", w.error); + assert!(w.trail.is_none(), "{tool}: the refused stroke is not drawn"); + assert!(w.preview.want > want, "{tool}: a new preview drops the refused stroke"); + } +} + +/// Opening again while the workspace is open keeps its work and says why. +#[test] +fn opening_again_keeps_the_open_workspace() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}})); + let e = crate::menus::invoke(&mut app, &egui::Context::default(), "select.selectAndMask", json!({})); + assert!(e.is_err_and(|e| e.contains("already open"))); + assert_eq!(ws(&app).edits.len(), 1, "the edit survives"); +} + +/// The preview keeps the selection after the edits it applied and starts the next from there: +/// after undo it starts over. +#[test] +fn the_preview_reuses_the_edits_it_applied() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[120.0, 50.0]]}})); + selected(&mut app); + assert_eq!(ws(&app).preview.cache.as_ref().map(|c| c.edits.len()), Some(1)); + ui(&mut app, json!({"tool": "brush", "stroke": {"points": [[40.0, 60.0]]}})); + let both = selected(&mut app); + assert_eq!(ws(&app).preview.cache.as_ref().map(|c| c.edits.len()), Some(2)); + ui(&mut app, json!({"undo": true})); + let one = selected(&mut app); + assert!(one < both); + assert_eq!(ws(&app).preview.cache.as_ref().map(|c| c.edits.len()), Some(1)); +} + +/// The selection the edits made on an older document is not reused: a Quick Selection stroke +/// on a repainted image previews what OK would commit. +#[test] +fn the_preview_recomputes_the_edits_after_the_document_changes() { + let warm = |app: &mut PhotocraftApp| { + app.session + .edit("paint", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 160, 100), &[0.85, 0.55, 0.25, 1.0]); + Ok(()) + }) + .unwrap(); + }; + let stroke = json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}}); + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, stroke.clone()); + let two_tone = selected(&mut app); + // The pixels change under the workspace (a control-channel command) before it redraws. + warm(&mut app); + let after = selected(&mut app); + let mut fresh = app_with_selection(); + warm(&mut fresh); + open(&mut fresh).unwrap(); + ui(&mut fresh, stroke); + let expected = selected(&mut fresh); + assert_ne!(two_tone, expected, "the repaint changes what the stroke selects"); + assert_eq!(after, expected); + assert_eq!(ws(&app).preview.cache.as_ref().map(|c| c.revision), app.session.active().map(|s| s.revision)); +} + +/// A request with a bad field is refused whole: the valid fields before it change nothing either. +#[test] +fn a_refused_request_changes_nothing() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let before = ws(&app).describe(); + for bad in [ + json!({"tool": "brush", "mode": "invalid"}), + json!({"tool": "brush", "mode": "subtract", "size": 80, "radius": 40, "stroke": {"points": "x"}}), + json!({"hardness": 10, "sampleAllLayers": true, "hideView": true, "stroke": {"points": [[1.0]]}}), + ] { + assert!(control(&mut app, &bad).is_err(), "{bad}"); + assert_eq!(ws(&app).describe(), before, "{bad}"); + assert!(!ws(&app).hide_view && !ws(&app).sample_all, "{bad}"); + } +} + +/// With nothing selected OK refines nothing, so Show Edge shows no Refine Edge Brush stroke. +#[test] +fn show_edge_shows_no_stroke_without_a_selection() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"clearSelection": true, "showEdge": true})); + let empty = selected(&mut app); + ui(&mut app, json!({"tool": "refineEdge", "stroke": {"points": [[40.0, 20.0], [40.0, 80.0]]}})); + assert_eq!(selected(&mut app), empty); + ui(&mut app, json!({"commit": true})); + assert_eq!(cov(&app, 40, 50), 0.0, "and OK selects nothing there"); +} + +/// A preview of pixels the document no longer has is never shown, even mid-stroke, and the old one +/// goes when the document changes. +#[test] +fn a_preview_of_an_old_revision_is_dropped() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + selected(&mut app); + assert!(ws(&app).preview.pending.is_some()); + let j = job(&app).unwrap(); + let old = j.revision; + let late = compute(j, None); + app.session.execute("select.all", json!({})).unwrap(); + follow_revision(&mut app); + assert!(ws(&app).preview.pending.is_none() && ws(&app).preview.tex.is_none(), "the old preview is gone"); + let w = ws_mut(&mut app); + w.pressed = true; + let generation = w.preview.want; + take_result(w, generation, old, late); + assert!(w.preview.pending.is_none() && w.preview.cache.is_none() && w.preview.shown != generation); +} + +/// Sends `key` with `modifiers` through the workspace's key handling. +fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) { + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + let input = egui::RawInput { events: vec![ev], ..Default::default() }; + ctx.run_ui(input, |ui| keys(app, ui.ctx())).textures_delta.clear(); +} + +/// Photoshop's keys: W, R, B, L, H, Z pick the tools (Shift+W and Shift+L cycle their slots), +/// [ and ] size the brush, the view letters, F, J and P the view, Ctrl+Z undoes. +#[test] +fn keys_like_photoshop() { + let mut app = app_with_selection(); + let ctx = egui::Context::default(); + open(&mut app).unwrap(); + let tool = |app: &PhotocraftApp| ws(app).tool; + for (key, mods, want) in [ + (Key::R, Modifiers::NONE, SmTool::RefineEdge), + (Key::B, Modifiers::NONE, SmTool::Brush), + (Key::W, Modifiers::NONE, SmTool::Quick), + (Key::W, Modifiers::SHIFT, SmTool::Object), + (Key::H, Modifiers::NONE, SmTool::Hand), + (Key::W, Modifiers::NONE, SmTool::Object), + (Key::L, Modifiers::NONE, SmTool::Lasso), + (Key::L, Modifiers::SHIFT, SmTool::PolygonalLasso), + (Key::Z, Modifiers::NONE, SmTool::Zoom), + (Key::L, Modifiers::NONE, SmTool::PolygonalLasso), + (Key::B, Modifiers::NONE, SmTool::Brush), + ] { + press(&mut app, &ctx, key, mods); + assert_eq!(tool(&app), want, "{mods:?}+{key:?}"); + } + press(&mut app, &ctx, Key::CloseBracket, Modifiers::NONE); + assert_eq!(ws(&app).brush_size, 33.0); + press(&mut app, &ctx, Key::OpenBracket, Modifiers::NONE); + assert_eq!(ws(&app).brush_size, 30.0); + let view = |app: &PhotocraftApp| ws(app).opts.view; + for (key, want) in [ + (Key::K, Mode::BlackWhite), + (Key::A, Mode::OnBlack), + (Key::T, Mode::OnWhite), + (Key::V, Mode::Overlay), + (Key::Y, Mode::OnLayers), + (Key::M, Mode::MarchingAnts), + (Key::F, Mode::Overlay), + (Key::O, Mode::OnionSkin), + ] { + press(&mut app, &ctx, key, Modifiers::NONE); + assert_eq!(view(&app), want, "{key:?}"); + } + press(&mut app, &ctx, Key::J, Modifiers::NONE); + press(&mut app, &ctx, Key::P, Modifiers::NONE); + assert!(ws(&app).opts.show_edge && ws(&app).opts.show_original); + ui(&mut app, json!({"invert": true})); + press(&mut app, &ctx, Key::Z, Modifiers::COMMAND); + assert_eq!(ws(&app).edits.len(), 0); + press(&mut app, &ctx, Key::Z, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(ws(&app).edits.len(), 1); +} + +/// The Polygonal Lasso takes clicks: Enter closes the polygon (not OK), Esc drops it (not Cancel), +/// clicking the first vertex closes it too. +#[test] +fn polygonal_lasso_enter_and_escape() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ws_mut(&mut app).zoom = 1.0; + ui(&mut app, json!({"tool": "polygonalLasso"})); + let click = |app: &mut PhotocraftApp, x: f64, y: f64| crate::distort_ui::pointer(app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::NONE); + for (x, y) in [(30.0, 30.0), (60.0, 30.0), (60.0, 60.0)] { + click(&mut app, x, y); + } + assert_eq!(ws(&app).describe()["polygon"].as_u64(), Some(3)); + assert!(enter(&mut app), "Enter closes the polygon"); + assert!(app.distort.select_mask.is_some(), "and leaves the workspace open"); + assert_eq!(ws(&app).edits.len(), 1); + click(&mut app, 30.0, 30.0); + click(&mut app, 60.0, 30.0); + escape(&mut app); + assert!(app.distort.select_mask.is_some() && ws(&app).poly.is_none(), "Esc drops the polygon only"); + for (x, y) in [(70.0, 70.0), (90.0, 70.0), (90.0, 90.0), (71.0, 71.0)] { + click(&mut app, x, y); + } + assert_eq!(ws(&app).edits.len(), 2, "clicking the first vertex closes it"); + escape(&mut app); + assert!(app.distort.select_mask.is_none(), "Esc with no polygon cancels"); +} + +/// The workspace draws: tools on the left, the options bar, the Properties panel with Photoshop's +/// sections and buttons; clicking a tool picks it, OK commits. +#[test] +fn renders_photoshops_layout() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + for label in [ + "Remember Settings", + "View Mode", + "Real-Time Refinement", + "High Quality Preview", + "Refine Mode", + "Color Aware", + "Edge Detection", + "Smart Radius", + "Global Refinements", + "Clear Selection", + "Invert", + "Output Settings", + "Decontaminate Colors", + "Select Subject", + "Refine Hair", + "Sample All Layers", + "OK", + "Cancel", + ] { + assert!(h.query_by_label_contains(label).is_some(), "{label} is shown"); + } + assert!(h.get_by_label("Refine Hair").accesskit_node().is_disabled(), "Refine Hair is greyed out"); + h.get_by_label("Brush Tool (B)").click(); + h.run_steps(2); + assert_eq!(h.state().distort.select_mask.as_ref().map(|w| w.tool), Some(SmTool::Brush)); + assert!(h.query_by_label_contains("Hardness").is_some(), "the Brush's options bar"); + h.get_by_label("Invert").click(); + h.run_steps(2); + assert_eq!(h.state().distort.select_mask.as_ref().map(|w| w.edits.len()), Some(1)); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().distort.select_mask.is_none(), "OK closes"); + let app = h.state(); + assert!(cov(app, 5, 5) < 0.01 && cov(app, 100, 50) > 0.99, "the inverted selection"); +} + +/// Panning shows Photoshop's hand: open while Space is held (or the Hand tool is picked), closed +/// while dragging; and Space doesn't press the panel button clicked last. +#[test] +fn panning_shows_the_hand() { + use egui::{PointerButton, Pos2}; + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"tool": "brush"})); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::distort_ui::keys(app, &ctx); + keys(app, &ctx); + show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + // Click Invert, then move over the image. + h.get_by_label("Invert").click(); + h.run_steps(2); + assert_eq!(h.state().distort.select_mask.as_ref().map(|w| w.edits.len()), Some(1)); + let over = Pos2::new(LEFT_W + 300.0, BAR_H + TAB_H + 300.0); + h.event(egui::Event::PointerMoved(over)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the brush's own cursor"); + let space = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, pressed: bool| { + h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + }; + space(&mut h, true); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "Space: the open hand"); + assert_eq!(h.state().distort.select_mask.as_ref().map(|w| w.edits.len()), Some(1), "Space didn't press Invert again"); + let centre = h.state().distort.select_mask.as_ref().map(|w| w.center).unwrap(); + h.event(egui::Event::PointerButton { pos: over, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for dx in [5.0, 20.0, 40.0] { + h.event(egui::Event::PointerMoved(Pos2::new(over.x + dx, over.y))); + h.run_steps(1); + } + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Grabbing, "dragging: the closed hand"); + h.event(egui::Event::PointerButton { pos: Pos2::new(over.x + 40.0, over.y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + space(&mut h, false); + let w = h.state().distort.select_mask.as_ref().unwrap(); + assert!(w.center[0] < centre[0], "the view panned: {:?} → {:?}", centre, w.center); + assert!(w.edits.len() == 1 && w.strokes.is_empty(), "panning painted nothing"); + // The Hand tool shows the open hand without Space. + h.state_mut().distort.select_mask.as_mut().unwrap().pick(SmTool::Hand); + h.event(egui::Event::PointerMoved(over)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Grab); +} + +/// The greyed Object Aware and Refine Hair say why they can't be used. +#[test] +fn greyed_controls_explain_themselves() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + for (label, why) in [("Object Aware", "segmentation model"), ("Refine Hair", "hair detection")] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} is greyed"); + assert!(h.query_by_label_contains(why).is_none(), "{label}: no tooltip before hovering"); + let at = h.get_by_label(label).rect().center(); + h.hover_at(at); + h.run_steps(8); + assert!(h.query_by_label_contains(why).is_some(), "{label}: hovering says why"); + h.hover_at(egui::pos2(700.0, 450.0)); + h.run_steps(4); + } +} + +fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let (req, _rx) = crate::control::ControlRequest::new(method, params); + match crate::control::handle(app, &egui::Context::default(), &req) { + crate::control::Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +/// A second document with its own selection, the first one active again. +fn two_documents() -> PhotocraftApp { + let mut app = app_with_selection(); + app.session.execute("file.new", json!({"width": 160, "height": 100, "depth": 8})).unwrap(); + app.session.execute("select.rect", json!({"x": 100, "y": 50, "width": 30, "height": 30})).unwrap(); + assert!(app.session.set_active(0)); + app.sync_views(); + app +} + +fn fingerprint(app: &PhotocraftApp, i: usize) -> (u64, Option, Option) { + let st = &app.session.documents()[i]; + let sel = st.doc.selection.as_ref(); + (st.revision, sel.map(|s| s.sample_channel(10, 10, 0)), sel.map(|s| s.sample_channel(120, 50, 0))) +} + +/// The #8896 review: a document switch and OK queued on the control channel, with no frame +/// between them, must not apply the first document's edits to the second. +#[test] +fn ok_after_a_document_switch_changes_neither_document() { + let mut app = two_documents(); + open(&mut app).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}})); + let before = (fingerprint(&app, 0), fingerprint(&app, 1)); + let switched = call(&mut app, "engine.execute", json!({"command": "document.activate", "params": {"document": 1}})); + assert_eq!(app.session.active_index(), Some(1), "{switched}"); + let r = call(&mut app, "ui.menu.invoke", json!({"command": "select.selectAndMask", "params": {"ui": {"commit": true}}})); + assert!(r.get("error").is_some(), "the stale OK is refused: {r}"); + assert_eq!((fingerprint(&app, 0), fingerprint(&app, 1)), before, "neither document changed"); + assert!(app.distort.select_mask.is_none(), "the stale workspace is closed"); +} + +/// Every route into the workspace checks its document: control edits, the preview and pointer +/// events on another document are refused, and none of them edits that document. +#[test] +fn control_preview_and_pointer_on_another_document_are_refused() { + for route in ["control", "preview", "pointer"] { + let mut app = two_documents(); + open(&mut app).unwrap(); + let before = fingerprint(&app, 1); + assert!(app.session.set_active(1)); + match route { + "control" => assert!(control(&mut app, &json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}})).is_err()), + "preview" => assert!(control(&mut app, &json!({"waitPreview": true})).is_err()), + _ => { + let ev = ToolEvent::Down { x: 120.0, y: 50.0, pressure: 1.0 }; + crate::distort_ui::pointer(&mut app, ev, egui::Modifiers::NONE); + } + } + assert!(app.distort.select_mask.is_none(), "{route}: the stale workspace is closed"); + assert_eq!(fingerprint(&app, 1), before, "{route}: the other document is untouched"); + } +} + +/// Selecting another layer in the same document (a shortcut, or the control channel between +/// requests) must not send a layer-mask OK to that layer. +#[test] +fn ok_after_a_layer_switch_leaves_the_new_layer_alone() { + let mut app = app_with_selection(); + let first = app.session.active().unwrap().active_layer.unwrap(); + let other = app.run("layer.new.layer", json!({"name": "Other"})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); + app.run("layer.select", json!({"layer": first.0})).unwrap(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "layerMask"})); + let revision = app.session.active().unwrap().revision; + call(&mut app, "engine.execute", json!({"command": "layer.select", "params": {"layer": other.0}})); + let revision_after_select = app.session.active().unwrap().revision; + let r = call(&mut app, "ui.menu.invoke", json!({"command": "select.selectAndMask", "params": {"ui": {"commit": true}}})); + assert!(r.get("error").is_some(), "the stale OK is refused: {r}"); + let st = app.session.active().unwrap(); + assert!(st.doc.layer(other).unwrap().mask.is_none(), "no mask on the newly selected layer"); + assert!(st.doc.layer(first).unwrap().mask.is_none(), "nor on the first"); + assert!(st.doc.selection.is_some(), "the selection stands"); + assert!(revision_after_select >= revision && st.revision == revision_after_select, "nothing was edited after the switch"); + assert!(app.distort.select_mask.is_none()); +} + +/// The reason a stale workspace was closed is user-visible text: it is shown in the status bar and +/// returned to the control channel in the language in use, and every catalogue has it (#8896). +#[test] +fn the_reason_a_stale_workspace_closed_is_translated() { + let document = "Select and Mask was closed: its document is no longer the active one"; + let layer = "Select and Mask was closed: another layer was selected"; + for lang in crate::i18n::Lang::all().filter(|l| l.code() != "en") { + for (reason, english) in [("document", document), ("layer", layer)] { + assert!(crate::i18n::has(lang, english), "{}: no row for the {reason} reason", lang.code()); + let shown = crate::i18n::tr(lang, english); + let mut app = if reason == "document" { two_documents() } else { app_with_selection() }; + let first = app.session.active().unwrap().active_layer.unwrap(); + let other = (reason == "layer").then(|| app.run("layer.new.layer", json!({"name": "Other"})).unwrap()["layer"].as_u64().map(LayerId).unwrap()); + app.run("layer.select", json!({"layer": first.0})).unwrap(); + open(&mut app).unwrap(); + crate::i18n::with_language(lang, || { + match other { + Some(other) => drop(app.session.execute("layer.select", json!({"layer": other.0}))), + None => assert!(app.session.set_active(1)), + } + let err = commit(&mut app).expect_err(&format!("{} / {reason}: the stale OK is refused", lang.code())); + assert_eq!(err, shown, "{}: the error is translated", lang.code()); + assert_eq!(app.ui.status, shown, "{}: the status is translated", lang.code()); + }); + assert_ne!(shown, english, "{}: the {reason} reason reads differently from English", lang.code()); + } + } +} + +#[test] +fn sparse_large_preview_counts_coverage_without_a_dense_canvas_mask() { + let area = Rect::new(0, 0, 100_000, 100_000); + let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); + selection.write_pixel(99_999, 99_999, &[1.0]); + selection.write_pixel(2, 3, &[0.5]); + selection.write_pixel(-1, -1, &[1.0]); + assert_eq!(selected_pixels(Some(&selection), area), 2); + assert_eq!(preview_ants(Some(&selection), area, 1.0).unwrap().len(), 8); + let small = Rect::new(0, 0, 10, 10); + assert_eq!(selected_pixels(Some(&selection), small), 1); + assert_eq!(preview_ants(Some(&selection), small, 1.0).unwrap().len(), 4); + + let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]); + inverted.write_pixel(2, 3, &[0.0]); + let smaller = Rect::new(0, 0, 1000, 1000); + assert_eq!(selected_pixels(Some(&inverted), smaller), 999_999); + assert_eq!(selected_pixels(None, area), 0); +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ad024ccd97..97a77d2dab 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4200,6 +4200,20 @@ cameraRaw Dehaze Odstranění oparu Not rendered: this adjustment ({key}) is kept as imported. Nevykresleno: tato úprava ({key}) je ponechána tak, jak byla importována. # Print preview image (#8236) Print preview image Print preview image + Color Aware Podle barev + Decontaminate Colors Dekontaminovat barvy + Edge Detection Detekce okraje + Global Refinements Globální upřesnění + High Quality Preview Náhled ve vysoké kvalitě + Object Aware Podle objektů + Real-Time Refinement Upřesnění v reálném čase + Refine Edge Brush Tool Nástroj štětec pro upřesnění okraje + Refine Hair Upřesnit vlasy + Refine Mode Režim upřesnění + Remember Settings Zapamatovat nastavení + View Mode Režim zobrazení + Object Aware needs a segmentation model, which isn't available yet Režim Podle objektů vyžaduje segmentační model, který zatím není k dispozici + Refine Hair needs hair detection, which isn't available yet Upřesnit vlasy vyžaduje detekci vlasů, která zatím není k dispozici # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Krychle odstínu Brightness Cube Krychle jasu @@ -4217,6 +4231,8 @@ cameraRaw Dehaze Odstranění oparu Grayscale Ramp Přechod stupňů šedi Current Colors Aktuální barvy Make Ramp Web Safe Omezit pruh na webové barvy + Select and Mask was closed: its document is no longer the active one Vybrat a maskovat bylo zavřeno: jeho dokument již není aktivní + Select and Mask was closed: another layer was selected Vybrat a maskovat bylo zavřeno: byla vybrána jiná vrstva # Art History Brush (#213). Art History Brush Štětec umělecké historie Art History Brush Tool Nástroj štětec umělecké historie diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c1dfc027ed..7c27df11cd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3468,6 +3468,21 @@ curves Smooth Glätten Not rendered: this adjustment ({key}) is kept as imported. Nicht dargestellt: Diese Einstellung ({key}) wird wie importiert beibehalten. # Print preview image (#8236) Print preview image Print preview image + Clear Selection Auswahl löschen + Color Aware Farbbezogen + Decontaminate Colors Farben dekontaminieren + Edge Detection Kantenerkennung + Global Refinements Globale Verbesserungen + High Quality Preview Hochwertige Vorschau + Object Aware Objektbezogen + Real-Time Refinement Verbesserung in Echtzeit + Refine Edge Brush Tool Kante-verbessern-Pinsel-Werkzeug + Refine Hair Haare verbessern + Refine Mode Verbesserungsmodus + Remember Settings Einstellungen merken + View Mode Ansichtsmodus + Object Aware needs a segmentation model, which isn't available yet Objektbezogen benötigt ein Segmentierungsmodell, das noch nicht verfügbar ist + Refine Hair needs hair detection, which isn't available yet Haare verbessern benötigt eine Haarerkennung, die noch nicht verfügbar ist # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Farbtonwürfel Brightness Cube Helligkeitswürfel @@ -3485,6 +3500,8 @@ curves Smooth Glätten Grayscale Ramp Graustufenbalken Current Colors Aktuelle Farben Make Ramp Web Safe Farbbalken auf Webfarben beschränken + Select and Mask was closed: its document is no longer the active one Auswählen und maskieren wurde geschlossen: Das zugehörige Dokument ist nicht mehr aktiv + Select and Mask was closed: another layer was selected Auswählen und maskieren wurde geschlossen: Es wurde eine andere Ebene ausgewählt # Art History Brush (#213). Art History Brush Künstlerischer Protokollpinsel Art History Brush Tool Künstlerischer-Protokollpinsel-Werkzeug diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b2b35dbbdc..c3facf56a0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4155,6 +4155,20 @@ curves Smooth Εξομάλυνση Not rendered: this adjustment ({key}) is kept as imported. Δεν αποδίδεται: αυτή η προσαρμογή ({key}) διατηρείται όπως εισήχθη. # Print preview image (#8236) Print preview image Print preview image + Color Aware Με βάση το χρώμα + Decontaminate Colors Απολύμανση χρωμάτων + Edge Detection Ανίχνευση άκρης + Global Refinements Καθολικές βελτιώσεις + High Quality Preview Προεπισκόπηση υψηλής ποιότητας + Object Aware Με βάση το αντικείμενο + Real-Time Refinement Βελτίωση σε πραγματικό χρόνο + Refine Edge Brush Tool Εργαλείο πινέλου βελτίωσης ακμής + Refine Hair Βελτίωση μαλλιών + Refine Mode Λειτουργία βελτίωσης + Remember Settings Απομνημόνευση ρυθμίσεων + View Mode Λειτουργία προβολής + Object Aware needs a segmentation model, which isn't available yet Η λειτουργία Με βάση το αντικείμενο χρειάζεται μοντέλο τμηματοποίησης, που δεν είναι ακόμη διαθέσιμο + Refine Hair needs hair detection, which isn't available yet Η Βελτίωση μαλλιών χρειάζεται ανίχνευση μαλλιών, που δεν είναι ακόμη διαθέσιμη # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Κύβος απόχρωσης Brightness Cube Κύβος φωτεινότητας @@ -4171,6 +4185,8 @@ curves Smooth Εξομάλυνση Grayscale Ramp Διαβάθμιση του γκρι Current Colors Τρέχοντα χρώματα Make Ramp Web Safe Μόνο χρώματα ιστού στη διαβάθμιση + Select and Mask was closed: its document is no longer the active one Η Επιλογή και μάσκα έκλεισε: το έγγραφό της δεν είναι πλέον το ενεργό + Select and Mask was closed: another layer was selected Η Επιλογή και μάσκα έκλεισε: επιλέχθηκε άλλο επίπεδο # Art History Brush (#213). Art History Brush Tool Πινέλο ιστορικού τέχνης (Art History Brush Tool) Tight Short Σφιχτό κοντό diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b42f3be02c..4299cc0496 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4417,6 +4417,20 @@ navigator Zoom Zoom Not rendered: this adjustment ({key}) is kept as imported. No se renderiza: este ajuste ({key}) se conserva tal como se importó. # Print preview image (#8236) Print preview image Print preview image + Color Aware Según color + Decontaminate Colors Descontaminar colores + Edge Detection Detección de bordes + Global Refinements Perfeccionamientos globales + High Quality Preview Previsualización de alta calidad + Object Aware Según objeto + Real-Time Refinement Perfeccionamiento en tiempo real + Refine Edge Brush Tool Herramienta Pincel para perfeccionar bordes + Refine Hair Perfeccionar pelo + Refine Mode Modo de perfeccionamiento + Remember Settings Recordar ajustes + View Mode Modo de visualización + Object Aware needs a segmentation model, which isn't available yet Según objeto necesita un modelo de segmentación que aún no está disponible + Refine Hair needs hair detection, which isn't available yet Perfeccionar pelo necesita detección de pelo, que aún no está disponible # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo de tono Brightness Cube Cubo de brillo @@ -4433,6 +4447,8 @@ navigator Zoom Zoom Grayscale Ramp Rampa de escala de grises Current Colors Colores actuales Make Ramp Web Safe Hacer rampa segura para web + Select and Mask was closed: its document is no longer the active one Se cerró Seleccionar y aplicar máscara: su documento ya no es el activo + Select and Mask was closed: another layer was selected Se cerró Seleccionar y aplicar máscara: se seleccionó otra capa # Art History Brush (#213). Art History Brush Tool Herramienta Pincel histórico artístico Tight Short Corto apretado diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3bad30d474..4fbc29fe39 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4497,6 +4497,20 @@ shape Appearance Apparence Not rendered: this adjustment ({key}) is kept as imported. Non rendu : ce réglage ({key}) est conservé tel qu'importé. # Print preview image (#8236) Print preview image Print preview image + Color Aware Selon la couleur + Decontaminate Colors Décontaminer les couleurs + Edge Detection Détection des contours + Global Refinements Améliorations globales + High Quality Preview Aperçu haute qualité + Object Aware Selon l'objet + Real-Time Refinement Amélioration en temps réel + Refine Edge Brush Tool Outil Pinceau d'amélioration du contour + Refine Hair Améliorer les cheveux + Refine Mode Mode d'amélioration + Remember Settings Mémoriser les paramètres + View Mode Mode d'affichage + Object Aware needs a segmentation model, which isn't available yet Selon l'objet nécessite un modèle de segmentation, pas encore disponible + Refine Hair needs hair detection, which isn't available yet Améliorer les cheveux nécessite une détection des cheveux, pas encore disponible # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cube de teinte Brightness Cube Cube de luminosité @@ -4513,6 +4527,8 @@ shape Appearance Apparence Grayscale Ramp Barre de niveaux de gris Current Colors Couleurs actuelles Make Ramp Web Safe Limiter la barre aux couleurs Web + Select and Mask was closed: its document is no longer the active one Sélectionner et masquer a été fermé : son document n’est plus le document actif + Select and Mask was closed: another layer was selected Sélectionner et masquer a été fermé : un autre calque a été sélectionné # Art History Brush (#213). Art History Brush Tool Outil Pinceau d'historique artistique Tight Short Serré court diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3d6ddab7cb..8e304dc355 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -539,6 +539,23 @@ cameraRaw Yellow पीला Missing delete command हटाने का कमांड नहीं मिला Invalid delete command हटाने का कमांड अमान्य है Layer deleted, but confirmation preference could not be saved: {error} लेयर हटा दी गई, लेकिन पुष्टि की प्राथमिकता सहेजी नहीं जा सकी: {error} + Clear Selection चयन साफ़ करें + Color Aware रंग-आधारित + Decontaminate Colors रंग शुद्ध करें + Edge Detection किनारा पहचान + Global Refinements वैश्विक परिशोधन + High Quality Preview उच्च गुणवत्ता पूर्वावलोकन + Object Aware ऑब्जेक्ट-आधारित + Real-Time Refinement रियल-टाइम परिशोधन + Refine Edge Brush Tool किनारा परिशोधन ब्रश टूल + Refine Hair बाल परिशोधित करें + Refine Mode परिशोधन मोड + Remember Settings सेटिंग्स याद रखें + View Mode दृश्य मोड + Object Aware needs a segmentation model, which isn't available yet ऑब्जेक्ट-आधारित के लिए सेगमेंटेशन मॉडल चाहिए, जो अभी उपलब्ध नहीं है + Refine Hair needs hair detection, which isn't available yet बाल परिशोधित करने के लिए बालों की पहचान चाहिए, जो अभी उपलब्ध नहीं है + Select and Mask was closed: its document is no longer the active one चयन और मास्क बंद कर दिया गया: उसका दस्तावेज़ अब सक्रिय नहीं है + Select and Mask was closed: another layer was selected चयन और मास्क बंद कर दिया गया: दूसरी लेयर चुनी गई # Art History Brush (#213). Art History Brush आर्ट हिस्ट्री ब्रश Style शैली diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d632cb52f1..59c727ab13 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4369,6 +4369,20 @@ cameraRaw Yellow Sárga Not rendered: this adjustment ({key}) is kept as imported. Nem jelenik meg: ez a korrekció ({key}) importált állapotában marad. # Print preview image (#8236) Print preview image Print preview image + Color Aware Színalapú + Decontaminate Colors Színek fertőtlenítése + Edge Detection Élészlelés + Global Refinements Globális finomítások + High Quality Preview Kiváló minőségű előnézet + Object Aware Objektumalapú + Real-Time Refinement Valós idejű finomítás + Refine Edge Brush Tool Élfinomító ecset eszköz + Refine Hair Haj finomítása + Refine Mode Finomítási mód + Remember Settings Beállítások megjegyzése + View Mode Nézetmód + Object Aware needs a segmentation model, which isn't available yet Az Objektumalapú módhoz szegmentálási modell kell, amely még nem érhető el + Refine Hair needs hair detection, which isn't available yet A Haj finomításához hajfelismerés kell, amely még nem érhető el # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Színárnyalat-kocka Brightness Cube Fényerő-kocka @@ -4385,6 +4399,8 @@ cameraRaw Yellow Sárga Grayscale Ramp Szürkeárnyalatos sáv Current Colors Aktuális színek Make Ramp Web Safe Sáv korlátozása webes színekre + Select and Mask was closed: its document is no longer the active one A Kijelölés és maszk bezárult: a dokumentuma már nem az aktív + Select and Mask was closed: another layer was selected A Kijelölés és maszk bezárult: másik réteg lett kijelölve # Art History Brush (#213). Art History Brush Tool Művészi előzményecset eszköz Tight Short Szoros, rövid diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 771e04e80a..e68b0a7886 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3470,6 +3470,21 @@ curves Smooth Haluskan Not rendered: this adjustment ({key}) is kept as imported. Tidak dirender: penyesuaian ini ({key}) disimpan seperti saat diimpor. # Print preview image (#8236) Print preview image Print preview image + Clear Selection Hapus Seleksi + Color Aware Berbasis Warna + Decontaminate Colors Dekontaminasi Warna + Edge Detection Deteksi Tepi + Global Refinements Penyempurnaan Global + High Quality Preview Pratinjau Kualitas Tinggi + Object Aware Berbasis Objek + Real-Time Refinement Penyempurnaan Waktu Nyata + Refine Edge Brush Tool Alat Kuas Perhalus Tepi + Refine Hair Perhalus Rambut + Refine Mode Mode Penyempurnaan + Remember Settings Ingat Pengaturan + View Mode Mode Tampilan + Object Aware needs a segmentation model, which isn't available yet Berbasis Objek memerlukan model segmentasi, yang belum tersedia + Refine Hair needs hair detection, which isn't available yet Perhalus Rambut memerlukan deteksi rambut, yang belum tersedia # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Kubus Hue Brightness Cube Kubus Kecerahan @@ -3486,6 +3501,8 @@ curves Smooth Haluskan Grayscale Ramp Gradasi Grayscale Current Colors Warna Saat Ini Make Ramp Web Safe Jadikan Gradasi Aman untuk Web + Select and Mask was closed: its document is no longer the active one Seleksi dan Mask ditutup: dokumennya tidak lagi aktif + Select and Mask was closed: another layer was selected Seleksi dan Mask ditutup: layer lain dipilih # Art History Brush (#213). Art History Brush Tool Alat Kuas riwayat artistik Tight Short Rapet pendek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b1598ac237..c1cb47ef59 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4572,6 +4572,20 @@ shape Appearance Aspetto Not rendered: this adjustment ({key}) is kept as imported. Non renderizzato: questa regolazione ({key}) viene conservata come importata. # Print preview image (#8236) Print preview image Print preview image + Color Aware In base al colore + Decontaminate Colors Decontamina colori + Edge Detection Rilevamento bordi + Global Refinements Perfezionamenti globali + High Quality Preview Anteprima di alta qualità + Object Aware In base all'oggetto + Real-Time Refinement Perfezionamento in tempo reale + Refine Edge Brush Tool Strumento Pennello per migliorare il bordo + Refine Hair Migliora capelli + Refine Mode Metodo di perfezionamento + Remember Settings Ricorda impostazioni + View Mode Modalità di visualizzazione + Object Aware needs a segmentation model, which isn't available yet In base all'oggetto richiede un modello di segmentazione, non ancora disponibile + Refine Hair needs hair detection, which isn't available yet Migliora capelli richiede il rilevamento dei capelli, non ancora disponibile # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo tonalità Brightness Cube Cubo luminosità @@ -4588,6 +4602,8 @@ shape Appearance Aspetto Grayscale Ramp Barra scala di grigio Current Colors Colori correnti Make Ramp Web Safe Limita la barra ai colori web + Select and Mask was closed: its document is no longer the active one Seleziona e maschera è stato chiuso: il suo documento non è più quello attivo + Select and Mask was closed: another layer was selected Seleziona e maschera è stato chiuso: è stato selezionato un altro livello # Art History Brush (#213). Art History Brush Tool Strumento Pennello storia artistica Tight Short Corto stretto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 435813b0c7..708f63a6d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4134,6 +4134,21 @@ curves Smooth スムーズ Not rendered: this adjustment ({key}) is kept as imported. レンダリングされません: この調整({key})はインポートされたまま保持されます。 # Print preview image (#8236) Print preview image Print preview image + Clear Selection 選択範囲をクリア + Color Aware カラー認識 + Decontaminate Colors 不要なカラーの除去 + Edge Detection エッジの検出 + Global Refinements グローバル調整 + High Quality Preview 高品質プレビュー + Object Aware オブジェクト認識 + Real-Time Refinement リアルタイム調整 + Refine Edge Brush Tool 境界線調整ブラシツール + Refine Hair 髪の毛を調整 + Refine Mode 調整モード + Remember Settings 設定を保存 + View Mode 表示モード + Object Aware needs a segmentation model, which isn't available yet オブジェクト認識にはセグメンテーションモデルが必要ですが、まだ利用できません + Refine Hair needs hair detection, which isn't available yet 髪の毛を調整には髪の毛の検出が必要ですが、まだ利用できません # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相キューブ Brightness Cube 明るさキューブ @@ -4150,6 +4165,8 @@ curves Smooth スムーズ Grayscale Ramp グレースケールランプ Current Colors 現在のカラー Make Ramp Web Safe ランプを Web セーフにする + Select and Mask was closed: its document is no longer the active one 「選択とマスク」を閉じました: 対象のドキュメントがアクティブではなくなりました + Select and Mask was closed: another layer was selected 「選択とマスク」を閉じました: 別のレイヤーが選択されました # Art History Brush (#213). Art History Brush Tool アートヒストリーブラシツール Tight Short タイト・ショート diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 30ab8cb165..51804edaa1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3666,6 +3666,21 @@ curves Smooth 매끄럽게 Not rendered: this adjustment ({key}) is kept as imported. 렌더링되지 않음: 이 조정({key})은 가져온 상태 그대로 유지됩니다. # Print preview image (#8236) Print preview image Print preview image + Clear Selection 선택 영역 지우기 + Color Aware 색상 인식 + Decontaminate Colors 색상 정화 + Edge Detection 가장자리 감지 + Global Refinements 전역 다듬기 + High Quality Preview 고품질 미리 보기 + Object Aware 개체 인식 + Real-Time Refinement 실시간 다듬기 + Refine Edge Brush Tool 가장자리 다듬기 브러시 도구 + Refine Hair 머리카락 다듬기 + Refine Mode 다듬기 모드 + Remember Settings 설정 기억 + View Mode 보기 모드 + Object Aware needs a segmentation model, which isn't available yet 개체 인식에는 분할 모델이 필요하지만 아직 사용할 수 없습니다 + Refine Hair needs hair detection, which isn't available yet 머리카락 다듬기에는 머리카락 감지가 필요하지만 아직 사용할 수 없습니다 # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 색조 큐브 Brightness Cube 밝기 큐브 @@ -3683,6 +3698,8 @@ curves Smooth 매끄럽게 Grayscale Ramp 회색 음영 램프 Current Colors 현재 색상 Make Ramp Web Safe 램프를 웹 안전 색상으로 만들기 + Select and Mask was closed: its document is no longer the active one 선택 및 마스크가 닫혔습니다: 해당 문서가 더 이상 활성 문서가 아닙니다 + Select and Mask was closed: another layer was selected 선택 및 마스크가 닫혔습니다: 다른 레이어가 선택되었습니다 # Art History Brush (#213). Art History Brush 아트 히스토리 브러시 Art History Brush Tool 아트 히스토리 브러시 도구 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d03260ecaf..5a2164c97e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4215,6 +4215,20 @@ curves Smooth Vloeiend maken Not rendered: this adjustment ({key}) is kept as imported. Niet weergegeven: deze aanpassing ({key}) blijft behouden zoals geïmporteerd. # Print preview image (#8236) Print preview image Print preview image + Color Aware Kleurbewust + Decontaminate Colors Kleuren zuiveren + Edge Detection Randdetectie + Global Refinements Globale verfijningen + High Quality Preview Voorvertoning in hoge kwaliteit + Object Aware Objectbewust + Real-Time Refinement Verfijning in realtime + Refine Edge Brush Tool Gereedschap Penseel Rand verfijnen + Refine Hair Haar verfijnen + Refine Mode Verfijningsmodus + Remember Settings Instellingen onthouden + View Mode Weergavemodus + Object Aware needs a segmentation model, which isn't available yet Objectbewust vereist een segmentatiemodel dat nog niet beschikbaar is + Refine Hair needs hair detection, which isn't available yet Haar verfijnen vereist haardetectie die nog niet beschikbaar is # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Kleurtoonkubus Brightness Cube Helderheidskubus @@ -4231,6 +4245,8 @@ curves Smooth Vloeiend maken Grayscale Ramp Grijswaardenbalk Current Colors Huidige kleuren Make Ramp Web Safe Balk beperken tot webkleuren + Select and Mask was closed: its document is no longer the active one Selecteren en maskeren is gesloten: het document is niet meer het actieve document + Select and Mask was closed: another layer was selected Selecteren en maskeren is gesloten: er is een andere laag geselecteerd # Art History Brush (#213). Art History Brush Tool Artistiek historiepenseel Tight Short Strak kort diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ba41a4e34d..679d90ed34 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4072,6 +4072,21 @@ curves Smooth Wygładź Not rendered: this adjustment ({key}) is kept as imported. Nie jest renderowana: ta korekta ({key}) jest zachowana w postaci zaimportowanej. # Print preview image (#8236) Print preview image Print preview image + Clear Selection Wyczyść zaznaczenie + Color Aware Według kolorów + Decontaminate Colors Odkażanie kolorów + Edge Detection Wykrywanie krawędzi + Global Refinements Dopracowanie globalne + High Quality Preview Podgląd wysokiej jakości + Object Aware Według obiektów + Real-Time Refinement Dopracowanie w czasie rzeczywistym + Refine Edge Brush Tool Narzędzie Pędzel dopracowania krawędzi + Refine Hair Dopracuj włosy + Refine Mode Tryb dopracowania + Remember Settings Zapamiętaj ustawienia + View Mode Tryb widoku + Object Aware needs a segmentation model, which isn't available yet Tryb Według obiektów wymaga modelu segmentacji, który nie jest jeszcze dostępny + Refine Hair needs hair detection, which isn't available yet Dopracowanie włosów wymaga wykrywania włosów, które nie jest jeszcze dostępne # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Sześcian odcienia Brightness Cube Sześcian jasności @@ -4088,6 +4103,8 @@ curves Smooth Wygładź Grayscale Ramp Pasek skali szarości Current Colors Bieżące kolory Make Ramp Web Safe Ogranicz pasek do kolorów internetowych + Select and Mask was closed: its document is no longer the active one Zamknięto Zaznacz i maskuj: jego dokument nie jest już aktywny + Select and Mask was closed: another layer was selected Zamknięto Zaznacz i maskuj: wybrano inną warstwę # Art History Brush (#213). Art History Brush Tool Narzędzie Pędzel historii artystycznej Tight Short Ścisły krótki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f3335cd9c6..57d0fcc985 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4385,6 +4385,20 @@ layerLabel No Color Sem cor Not rendered: this adjustment ({key}) is kept as imported. Não renderizado: este ajuste ({key}) é mantido como foi importado. # Print preview image (#8236) Print preview image Print preview image + Color Aware Com reconhecimento de cor + Decontaminate Colors Descontaminar cores + Edge Detection Detecção de borda + Global Refinements Refinamentos globais + High Quality Preview Visualização de alta qualidade + Object Aware Com reconhecimento de objeto + Real-Time Refinement Refinamento em tempo real + Refine Edge Brush Tool Ferramenta Pincel de refinamento de borda + Refine Hair Refinar cabelo + Refine Mode Modo de refinamento + Remember Settings Lembrar configurações + View Mode Modo de exibição + Object Aware needs a segmentation model, which isn't available yet Com reconhecimento de objeto requer um modelo de segmentação, ainda não disponível + Refine Hair needs hair detection, which isn't available yet Refinar cabelo requer detecção de cabelo, ainda não disponível # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo de matiz Brightness Cube Cubo de brilho @@ -4401,6 +4415,8 @@ layerLabel No Color Sem cor Grayscale Ramp Rampa de tons de cinza Current Colors Cores atuais Make Ramp Web Safe Tornar rampa segura para a Web + Select and Mask was closed: its document is no longer the active one Selecionar e mascarar foi fechado: o documento dele não está mais ativo + Select and Mask was closed: another layer was selected Selecionar e mascarar foi fechado: outra camada foi selecionada # Art History Brush (#213). Art History Brush Tool Ferramenta Pincel do histórico da arte Tight Short Curto cerrado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b74c398312..c1be00b842 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4658,6 +4658,20 @@ shape Appearance Оформление Not rendered: this adjustment ({key}) is kept as imported. Не отображается: эта коррекция ({key}) сохранена как при импорте. # Print preview image (#8236) Print preview image Print preview image + Color Aware С учетом цвета + Decontaminate Colors Очистить цвета + Edge Detection Обнаружение краев + Global Refinements Глобальное уточнение + High Quality Preview Высококачественный просмотр + Object Aware С учетом объектов + Real-Time Refinement Уточнение в реальном времени + Refine Edge Brush Tool Инструмент «Кисть уточнения края» + Refine Hair Уточнить волосы + Refine Mode Режим уточнения + Remember Settings Запомнить параметры + View Mode Режим просмотра + Object Aware needs a segmentation model, which isn't available yet Для режима «С учетом объектов» нужна модель сегментации, которая пока недоступна + Refine Hair needs hair detection, which isn't available yet Для уточнения волос нужно распознавание волос, которое пока недоступно # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Куб цветового тона Brightness Cube Куб яркости @@ -4674,6 +4688,8 @@ shape Appearance Оформление Grayscale Ramp Шкала градаций серого Current Colors Текущие цвета Make Ramp Web Safe Сделать шкалу безопасной для web + Select and Mask was closed: its document is no longer the active one Окно «Выделение и маска» закрыто: его документ больше не активен + Select and Mask was closed: another layer was selected Окно «Выделение и маска» закрыто: выбран другой слой # Art History Brush (#213). Art History Brush Tool Инструмент «Кисть истории искусств» Tight Short Плотный короткий diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index a81eb06da2..94ac9b7f2b 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4514,6 +4514,20 @@ shape Appearance Izgled Not rendered: this adjustment ({key}) is kept as imported. Није приказано: ово прилагођавање ({key}) је задржано онако како је увезено. # Print preview image (#8236) Print preview image Print preview image + Color Aware Prema boji + Decontaminate Colors Dekontaminiraj boje + Edge Detection Detekcija ivice + Global Refinements Globalna doterivanja + High Quality Preview Pregled visokog kvaliteta + Object Aware Prema objektu + Real-Time Refinement Doterivanje u realnom vremenu + Refine Edge Brush Tool Alatka četkica za doterivanje ivice + Refine Hair Doteraj kosu + Refine Mode Režim doterivanja + Remember Settings Zapamti podešavanja + View Mode Režim prikaza + Object Aware needs a segmentation model, which isn't available yet Režim Prema objektu zahteva model segmentacije, koji još nije dostupan + Refine Hair needs hair detection, which isn't available yet Doterivanje kose zahteva detekciju kose, koja još nije dostupna # PhotoCraft release checks. Check for Updates… Proveri ažuriranja… PhotoCraft Updates Ažuriranja za PhotoCraft @@ -4543,6 +4557,8 @@ shape Appearance Izgled Grayscale Ramp Skala nijansi sive Current Colors Trenutne boje Make Ramp Web Safe Učini skalu bezbednom za veb + Select and Mask was closed: its document is no longer the active one Izaberi i maskiraj je zatvoren: njegov dokument više nije aktivan + Select and Mask was closed: another layer was selected Izaberi i maskiraj je zatvoren: izabran je drugi sloj # Art History Brush (#213). Art History Brush Tool Alatka umetnička četkica istorije Tight Short Usko kratko diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f5b9d13fd6..b02cd742b7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4183,6 +4183,20 @@ cameraData Lens Lens Not rendered: this adjustment ({key}) is kept as imported. Görüntülenmiyor: bu ayarlama ({key}) içe aktarıldığı gibi korunuyor. # Print preview image (#8236) Print preview image Baskı Önizleme Görüntüsü + Color Aware Renge Duyarlı + Decontaminate Colors Renkleri Arındır + Edge Detection Kenar Algılama + Global Refinements Genel Hassaslaştırmalar + High Quality Preview Yüksek Kaliteli Önizleme + Object Aware Nesneye Duyarlı + Real-Time Refinement Gerçek Zamanlı Hassaslaştırma + Refine Edge Brush Tool Kenarı Hassaslaştırma Fırçası Aracı + Refine Hair Saçı Hassaslaştır + Refine Mode Hassaslaştırma Modu + Remember Settings Ayarları Hatırla + View Mode Görünüm Modu + Object Aware needs a segmentation model, which isn't available yet Nesneye Duyarlı mod henüz kullanılamayan bir bölütleme modeli gerektirir + Refine Hair needs hair detection, which isn't available yet Saçı Hassaslaştır henüz kullanılamayan saç algılama gerektirir # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Renk Tonu Küpü Brightness Cube Parlaklık Küpü @@ -4199,6 +4213,8 @@ cameraData Lens Lens Grayscale Ramp Gri Tonlama Şeridi Current Colors Geçerli Renkler Make Ramp Web Safe Şeridi Web Renkleriyle Sınırla + Select and Mask was closed: its document is no longer the active one Seç ve Maskele kapatıldı: belgesi artık etkin değil + Select and Mask was closed: another layer was selected Seç ve Maskele kapatıldı: başka bir katman seçildi # Art History Brush (#213). Art History Brush Tool Sanat Tarihi Fırçası Aracı Tight Short Sıkı Kısa diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8d911b19a8..00d192a037 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4165,6 +4165,21 @@ curves Smooth Згладити Not rendered: this adjustment ({key}) is kept as imported. Не відображається: це коригування ({key}) збережено як було імпортовано. # Print preview image (#8236) Print preview image Print preview image + Clear Selection Очистити виділення + Color Aware З урахуванням кольору + Decontaminate Colors Очистити кольори + Edge Detection Виявлення краю + Global Refinements Глобальне уточнення + High Quality Preview Високоякісний перегляд + Object Aware З урахуванням об'єктів + Real-Time Refinement Уточнення в реальному часі + Refine Edge Brush Tool Інструмент «Пензель уточнення краю» + Refine Hair Уточнити волосся + Refine Mode Режим уточнення + Remember Settings Запам'ятати параметри + View Mode Режим перегляду + Object Aware needs a segmentation model, which isn't available yet Для режиму «З урахуванням об'єктів» потрібна модель сегментації, яка ще недоступна + Refine Hair needs hair detection, which isn't available yet Для уточнення волосся потрібне розпізнавання волосся, яке ще недоступне # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Куб тону Brightness Cube Куб яскравості @@ -4181,6 +4196,8 @@ curves Smooth Згладити Grayscale Ramp Шкала градацій сірого Current Colors Поточні кольори Make Ramp Web Safe Зробити шкалу безпечною для вебу + Select and Mask was closed: its document is no longer the active one Вікно «Виділити та маскувати» закрито: його документ більше не активний + Select and Mask was closed: another layer was selected Вікно «Виділити та маскувати» закрито: вибрано інший шар # Art History Brush (#213). Art History Brush Tool Інструмент «Художній пензель історії» Tight Short Щільний короткий diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f348662975..00bf1b520c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3948,6 +3948,21 @@ curves Smooth Làm mượt Not rendered: this adjustment ({key}) is kept as imported. Không được kết xuất: điều chỉnh này ({key}) được giữ nguyên như khi nhập. # Print preview image (#8236) Print preview image Print preview image + Clear Selection Xóa vùng chọn + Color Aware Nhận biết màu + Decontaminate Colors Khử nhiễm màu + Edge Detection Phát hiện cạnh + Global Refinements Tinh chỉnh tổng thể + High Quality Preview Xem trước chất lượng cao + Object Aware Nhận biết đối tượng + Real-Time Refinement Tinh chỉnh theo thời gian thực + Refine Edge Brush Tool Công cụ cọ tinh chỉnh cạnh + Refine Hair Tinh chỉnh tóc + Refine Mode Chế độ tinh chỉnh + Remember Settings Ghi nhớ cài đặt + View Mode Chế độ xem + Object Aware needs a segmentation model, which isn't available yet Nhận biết đối tượng cần mô hình phân đoạn, hiện chưa có + Refine Hair needs hair detection, which isn't available yet Tinh chỉnh tóc cần tính năng phát hiện tóc, hiện chưa có # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Khối sắc màu Brightness Cube Khối độ sáng @@ -3965,6 +3980,8 @@ curves Smooth Làm mượt Grayscale Ramp Dải thang xám Current Colors Màu hiện tại Make Ramp Web Safe Giới hạn dải màu ở màu web + Select and Mask was closed: its document is no longer the active one Đã đóng Chọn và Mặt nạ: tài liệu của nó không còn là tài liệu đang hoạt động + Select and Mask was closed: another layer was selected Đã đóng Chọn và Mặt nạ: một lớp khác đã được chọn # Art History Brush (#213). Art History Brush Cọ lịch sử nghệ thuật Art History Brush Tool Công cụ Cọ lịch sử nghệ thuật diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9f437214a..1b423c1c29 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3117,6 +3117,21 @@ curves Smooth 平滑 Not rendered: this adjustment ({key}) is kept as imported. 未渲染:此调整({key})按导入时的原样保留。 # Print preview image (#8236) Print preview image 打印预览图像 + Clear Selection 清除选区 + Color Aware 颜色识别 + Decontaminate Colors 净化颜色 + Edge Detection 边缘检测 + Global Refinements 全局调整 + High Quality Preview 高品质预览 + Object Aware 对象识别 + Real-Time Refinement 实时调整 + Refine Edge Brush Tool 调整边缘画笔工具 + Refine Hair 调整细线 + Refine Mode 调整模式 + Remember Settings 记住设置 + View Mode 视图模式 + Object Aware needs a segmentation model, which isn't available yet 对象识别需要分割模型,目前尚不可用 + Refine Hair needs hair detection, which isn't available yet 调整细线需要毛发检测,目前尚不可用 # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相立方体 @@ -3142,6 +3157,8 @@ curves Smooth 平滑 Exported {path} 已导出 {path} Exported {n} files 已导出 {n} 个文件 Driver: {driver} 驱动程序:{driver} + Select and Mask was closed: its document is no longer the active one 已关闭“选择与蒙版”:其文档不再是当前文档 + Select and Mask was closed: another layer was selected 已关闭“选择与蒙版”:已选择另一个图层 # Art History Brush (#213). Art History Brush 艺术历史画笔 Art History Brush Tool 艺术历史画笔工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9d46dcb21e..b44c261364 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3081,6 +3081,21 @@ curves Smooth 平滑 Not rendered: this adjustment ({key}) is kept as imported. 未算繪:此調整({key})依匯入時的原樣保留。 # Print preview image (#8236) Print preview image Print preview image + Clear Selection 清除選取範圍 + Color Aware 顏色感知 + Decontaminate Colors 淨化顏色 + Edge Detection 邊緣偵測 + Global Refinements 整體調整 + High Quality Preview 高品質預視 + Object Aware 物件感知 + Real-Time Refinement 即時調整 + Refine Edge Brush Tool 調整邊緣筆刷工具 + Refine Hair 調整毛髮 + Refine Mode 調整模式 + Remember Settings 記住設定 + View Mode 檢視模式 + Object Aware needs a segmentation model, which isn't available yet 物件感知需要分割模型,目前尚無法使用 + Refine Hair needs hair detection, which isn't available yet 調整毛髮需要毛髮偵測,目前尚無法使用 # Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相立方體 Brightness Cube 亮度立方體 @@ -3098,6 +3113,8 @@ curves Smooth 平滑 Grayscale Ramp 灰階色帶 Current Colors 目前色彩 Make Ramp Web Safe 讓色帶成為網頁安全色 + Select and Mask was closed: its document is no longer the active one 已關閉「選取並遮住」:其文件已不是使用中的文件 + Select and Mask was closed: another layer was selected 已關閉「選取並遮住」:已選取另一個圖層 # Art History Brush (#213). Art History Brush 藝術歷史畫筆 Art History Brush Tool 藝術歷史畫筆工具 diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 40ebeb1804..b6d0ffac31 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -552,6 +552,10 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.distort.caf.is_some() && !ctx.text_edit_focused() { crate::caf_ui::keys(app, ctx); } + // And Select and Mask's tools, views and brush size. + if app.distort.select_mask.is_some() && !ctx.text_edit_focused() { + crate::select_mask_ui::keys(app, ctx); + } true } @@ -559,7 +563,7 @@ fn handle_modal_canvas_keys(app: &mut PhotocraftApp, ctx: &egui::Context, focus: use crate::shortcut_dispatch::{Focus, dispatch_pressed}; // Dialogs (and Liquify's panel while one of its controls has focus) keep canvas zoom; a // focused text field keeps its keys. - let liquify_focus = (app.distort.liquify.is_some() || app.distort.caf.is_some()) && focus != Focus::None; + let liquify_focus = (app.distort.liquify.is_some() || app.distort.caf.is_some() || app.distort.select_mask.is_some()) && focus != Focus::None; if liquify_focus || !app.ui.dialogs.is_empty() || app.discard.is_some() { if focus != Focus::Text { nav_keys(app, ctx); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5a9227dded..35a3b0d851 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -149,6 +149,7 @@ pub use dialogs::rasterize_prompt; pub use dialogs::replace_prompt; use dialogs::rgb_histogram; pub use dialogs::screen_picker; +pub use dialogs::select_mask_ui; pub use dialogs::shape_dialog; pub(crate) use dialogs::shape_fill_ui; use dialogs::sizing; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 850ac92fdd..7987536f74 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -405,7 +405,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } Ok(json!({"dialog": crate::fill_ui::open(app)})) } - "select.selectAndMask" => Ok(json!({"dialog": crate::filter_dialog::open(app, "select.refineEdge")})), + // Photoshop's workspace (select_mask_ui); `distort_ui::menu` routes it first. + "select.selectAndMask" => crate::select_mask_ui::open(app).map(|_| json!({"selectAndMask": app.distort.describe()["selectAndMask"]})), // Select › Transform Selection from the menu: the interactive box (with params: the engine). "select.transformSelection" if params.as_object().is_none_or(|o| o.is_empty()) => { crate::transform_tool::begin_selection(app, ctx).map(|_| json!({"transform": app.ui.transform})) diff --git a/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs b/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs index 0c217dd3d0..65496cbe30 100644 --- a/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs +++ b/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs @@ -153,8 +153,8 @@ fn mask_double_click_launches_select_and_mask_with_preference() { let at = masks.iter().find(|(kind, _)| *kind == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center(); double_click(&mut h, at); assert!(h.state().ui.mask_target); - let dialog = h.state().ui.dialogs.last().expect("select and mask dialog should be opened"); - assert_eq!(dialog.fields.get("__command").and_then(|v| v.as_str()), Some("select.refineEdge")); + let w = h.state().distort.describe()["selectAndMask"].clone(); + assert_eq!(w["settings"]["output"].as_str(), Some("layerMask"), "the Select and Mask workspace opens on the mask: {w}"); } #[test] diff --git a/crates/ui-egui/src/panels/mask_properties_tests.rs b/crates/ui-egui/src/panels/mask_properties_tests.rs index 782337ed36..0fcc9de195 100644 --- a/crates/ui-egui/src/panels/mask_properties_tests.rs +++ b/crates/ui-egui/src/panels/mask_properties_tests.rs @@ -293,21 +293,22 @@ fn refine_invert_inverts_the_mask_and_leaves_the_layer_alone() { } #[test] -fn refine_row_opens_the_select_and_mask_and_color_range_dialogs() { - for (label, open) in [("Select and Mask…", "select.refineEdge"), ("Color Range…", crate::color_range_ui::COMMAND)] { - let mut h = harness(false, crate::theme::ThemeKind::Pro); - assert!(h.state().ui.dialogs.is_empty()); - h.get_by_label(label).click(); - h.run_steps(3); - let dialogs = &h.state().ui.dialogs; - assert_eq!(dialogs.len(), 1, "{label} opens one dialog"); - let fields = &dialogs[0].fields; - let opened = fields.get("__command").and_then(Value::as_str).unwrap_or(crate::color_range_ui::COMMAND); - assert_eq!(opened, open, "{label} opened {opened}"); - if open == crate::color_range_ui::COMMAND { - assert!(crate::color_range_ui::owns(fields), "the Color Range dialog, not the generic one"); - } - } +fn refine_row_opens_the_select_and_mask_workspace_and_color_range_dialog() { + // Select and Mask… opens Photoshop's workspace on the targeted mask. + let mut h = harness(false, crate::theme::ThemeKind::Pro); + h.get_by_label("Select and Mask…").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "a workspace, not a dialog"); + let w = h.state().distort.describe()["selectAndMask"].clone(); + assert_eq!(w["settings"]["output"].as_str(), Some("layerMask"), "it refines the mask: {w}"); + // Color Range… opens its own dialog. + let mut h = harness(false, crate::theme::ThemeKind::Pro); + assert!(h.state().ui.dialogs.is_empty()); + h.get_by_label("Color Range…").click(); + h.run_steps(3); + let dialogs = &h.state().ui.dialogs; + assert_eq!(dialogs.len(), 1, "Color Range… opens one dialog"); + assert!(crate::color_range_ui::owns(&dialogs[0].fields), "the Color Range dialog, not the generic one"); } /// A Studio-layout theme's floating Properties card, with no mask targeted. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e13f64fedc..a99b863d31 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -72,6 +72,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. + - Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …). - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized. - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. diff --git a/docs/gaps.md b/docs/gaps.md index 93655f892c..d8157a6522 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -73,8 +73,10 @@ what an agent can't finish alone. - **Estimate:** 60–100 h (2–9 h each, per the calibration). ### G7. Workspaces shown as parameter dialogs -- **Missing:** Select and Mask workspace layout - (TOOL-214-1, Refine Hair #2671; its view modes preview live since #1754, Refine Edge Brush #2972); Content-Aware Fill workspace with a paintable sampling area +- **Missing:** Select and Mask's Refine Hair (#2671), Object Aware refine mode (#2788) and Presets + (TOOL-214-1; the workspace landed 2026-10-23, #7069, #8148: Photoshop's layout with its own + Quick Selection, Refine Edge Brush, Brush, Object Selection, Lasso and Polygonal Lasso, Hand and + Zoom, the view modes since #1754, Real-Time Refinement and High Quality Preview); Content-Aware Fill workspace with a paintable sampling area (TOOL-214-15); Vanishing Point plane editor (TOOL-214-14). Content-Aware Move's live preview of the result is done (TOOL-213-4, 2026-10-16, #6680: every selection the command takes, coarse first for large ones, then the exact result), as are Transform On Drop and Content-Aware Scale @@ -400,6 +402,7 @@ what an agent can't finish alone. |---|---|---| | 2026-10-27 | minor | G9: 12 of 181 preferences do nothing, the scorecard's count with integration batch 9 (#9775) on main; no estimate changed | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-23 | minor | G7: Select and Mask workspace (Photoshop's layout, its tools as `select.refineEdge` edits, Real-Time Refinement, High Quality Preview), #7069, #8148; Refine Hair, Object Aware and Presets remain; no estimate changed | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/scorecard.md b/docs/scorecard.md index 076537a3a2..a58474a1c0 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -170,7 +170,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-213-13 | Brush regression tests: no seams, hard edge, zero-scatter defaults, ABR never black | done | [#213](https://github.com/storytold/photocraft/issues/213) | Seam, hard-edge and zero-scatter tests in brush_tests.rs; ABR tip colour test in abr_map/tests.rs | | TOOL-213-14 | Tablet: no OS arrow cursor over the canvas on macOS, Windows and Linux | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Brush tools set CursorIcon::None (canvas.rs:1259-1275); not verified per OS | | TOOL-213-18 | Pattern Stamp tool: sibling of Clone Stamp in the S flyout | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::PatternStamp in the S group; paint.patternStamp stamps the Patterns-panel tile with Aligned and Impressionist (an approximation: it jitters each dab's tile phase, not Photoshop's smeared impressionist look); engine tests cover depths, seams, hostile input | -| TOOL-214-1 | Select and Mask workspace: view modes, Refine Edge brush, 6 outputs | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.refineEdge dialog with a live preview in Photoshop's view modes: Onion Skin, Marching Ants, Overlay, On Black, On White, Black & White, On Layers, per-view Opacity, Show Edge (J), Show Original (P), F cycles, X shows the image (select_mask_view.rs, #1754); Refine Edge Brush (R, size, Expand Detection Area / Restore Original Edge, Alt swaps) paints select.refineEdge refineStrokes, estimated by colour-line matting (matting/brush.rs, #2972); outputs Selection, Layer Mask, New Layer, New Layer with Mask, New Document, New Document with Mask (#2998); the workspace tools Quick Selection, Brush, Lasso, Object Selection, Select Subject, Clear Selection and Invert run as select.refineEdge edits, drivable by agents (#7069); no workspace layout or toolbar yet | +| TOOL-214-1 | Select and Mask workspace: view modes, Refine Edge brush, 6 outputs | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Photoshop's full-window Select and Mask workspace (select_mask_ui.rs, #7069, #8148); OK applies select.refineEdge. Live preview in Photoshop's view modes: Onion Skin, Marching Ants, Overlay, On Black, On White, Black & White, On Layers, per-view Opacity, Show Edge (J), Show Original (P), F cycles, X shows the image (select_mask_view.rs, #1754); Refine Edge Brush (R, size, Expand Detection Area / Restore Original Edge, Alt swaps) paints select.refineEdge refineStrokes, estimated by colour-line matting (matting/brush.rs, #2972); outputs Selection, Layer Mask, New Layer, New Layer with Mask, New Document, New Document with Mask (#2998); the workspace has the options bar, tools Quick Selection W, Refine Edge Brush R, Brush B, Object Selection W, Lasso and Polygonal Lasso L, Hand H, Zoom Z, Properties with Remember Settings, View Mode (Real-Time Refinement, High Quality Preview, Overlay colour and Indicates), Refine Mode, Edge Detection, Global Refinements with Clear Selection and Invert, Output Settings; the tools run as select.refineEdge edits; Ctrl+Z per edit; no Refine Hair (#2671), Object Aware (#2788) or Presets | | TOOL-214-2 | Marquee: Shift square, Alt from centre, live W x H readout | done | [#214](https://github.com/storytold/photocraft/issues/214) | canvas.rs marquee_corners: Shift square or circle, Alt from the centre, live W x H readout beside the cursor (marquee_readout); marquee_tests.rs | | TOOL-214-3 | Color Range test: Sampled Colors at Fuzziness 0 selects the exact match only | done | [#214](https://github.com/storytold/photocraft/issues/214) | color_range_fuzziness_zero_selects_exact_match_only in selection_cmds.rs asserts exact match is selected and 1-level-off pixels are rejected at fuzziness 0; tonal presets covered in color_range_presets | | TOOL-214-4 | Move tool: box-select layers, Auto-Select hover outline, double-click fit, drag to a tab | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Auto-Select hover outline (Preferences › Tools › Show Highlight on Rollover, #2834) and box-select layers from an empty spot (move_box.rs:59, layer.selectInRect, #2844) done; dragging layers with the Move tool (or from the Layers panel) onto another document's tab copies them there (layer_transfer.rs:162, layer.copyToDocument, #589/#851); double-click fit and dragging a selection's pixels to another document open | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26b95ea479..503ed28d1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -75,7 +75,7 @@ Weights reflect what a working Photoshop user depends on (photographers, retouch | Dimension | Weight | % ready | Remaining (agent-h) | Evidence | Detail | |---|---:|---:|---:|---|---| -| Features in depth (tools, layers, selections, type, filters, transforms) | 25% | 55% | 600–1,000 | Scorecard checklists: Tools 20 done / 15 partial / 6 missing, Type 5 / 5 / 0 (2026-10-22, area type partial), Automation 3 / 2 / 6. 14 tools missing; Select and Mask, Vanishing Point and Content-Aware Fill are parameter dialogs, not workspaces; type on a path partial; paragraph direction buttons exist but the visual RTL caret is missing | [gaps.md](gaps.md) | +| Features in depth (tools, layers, selections, type, filters, transforms) | 25% | 55% | 600–1,000 | Scorecard checklists: Tools 20 done / 15 partial / 6 missing, Type 5 / 5 / 0 (2026-10-22, area type partial), Automation 3 / 2 / 6. 14 tools missing; Vanishing Point and Content-Aware Fill are parameter dialogs, not workspaces (Select and Mask is one since 2026-10-23); type on a path partial; paragraph direction buttons exist but the visual RTL caret is missing | [gaps.md](gaps.md) | | UI / UX fidelity and feel | 15% | 40% | 350–600 | ~150 open UI issues; Workspace checklist 13 / 5 / 5 (2026-10-12; 5 / 7 / 11 on 2026-10-10); 12 of 178 preferences do nothing (scorecard, 2026-10-25; was 27 of 156); no floating panel groups, thin Color panel, brush lag and pressure jumps reported | [ui-parity.md](ui-parity.md), [brush-parity.md](brush-parity.md) | | File formats and fidelity | 15% | 60% | 300–500 | PSD oracle on Photoshop-authored files 133/256 (52%); io corpus 146/170 (86%); psd-tools 236/309 (76%); round trips ~100% of corpus; but users report Photoshop refusing our files (#1281, #2469; a text-layer case, #2374, was fixed 2026-10-10); no Photoshop PDF, EPS, JPEG 2000, JPEG XL, AVIF read, CR3 | [file-format-parity.md](file-format-parity.md) | | Performance | 10% | 25% | 200–350 | 3 of 25 budgeted scenarios meet budget (baseline 2026-10-05); 150-layer nudge crashes the GPU path (P12); layer move on 15000×10000 16-bit 2.7 s p50; users report brush and cursor lag (#2619, #2566, #1994) | [scorecard.md](scorecard.md#performance) | @@ -168,7 +168,7 @@ parity for the area and are already contained in the dimension rows above. | Area | % | Hours | Notes | |---|---:|---:|---| | Layers, groups, masks, blend modes, smart objects, layer styles | 65% | 150–250 | Broad and GPU-accelerated. Open: a single pixel layer copies its pixels without its mask and styles (UI-217-23: smart object, type, shape, group, fill and adjustment layers and multi-layer selections copy and paste whole), smart-object perspective (FILE-215-6), a user contour library (FILE-215-15). Multi-layer Smart Object conversion (#2052, #2651), Stamp Visible (UI-217-22) and mask targeting by command (#2458) are done | -| Selections, Select and Mask, channels | 55% | 120–200 | All selection tools, single row/column marquee included (#2837). Select and Mask is a dialog with Photoshop's view modes, a Refine Edge Brush and six outputs, not a workspace (TOOL-214-1), no Refine Hair (#2671); Select Subject/Sky classical, 559 ms p50 on 24 MP vs a 100 ms budget | +| Selections, Select and Mask, channels | 55% | 120–200 | All selection tools, single row/column marquee included (#2837). Select and Mask is Photoshop's workspace with its own tools (Quick Selection, Refine Edge Brush, Brush, Object Selection, Lasso, Polygonal Lasso), view modes and six outputs (TOOL-214-1, #7069, #8148), no Refine Hair (#2671), Object Aware or Presets; Select Subject/Sky classical, 559 ms p50 on 24 MP vs a 100 ms budget | | Painting and brush engine | 55% | 150–250 | Every Brush Settings section exists; feel is the gap: lag on big brushes, pressure jumps, smoothing and edge quality reports ([brush-parity.md](brush-parity.md)) | | Retouching (healing, clone, patch, remove, content-aware) | 50% | 100–180 | Remove tool non-generative; Content-Aware Fill has no workspace (TOOL-214-15); no live stroke preview for the Mixer Brush yet (TOOL-213-7) | | Transform, warp, puppet, perspective, liquify | 55% | 100–180 | Free Transform modifiers right, with a right-click transform menu (TOOL-214-5) and H/V skew fields; Puppet Warp mesh follows the object outline (TOOL-214-6); Liquify called "useless" by a user (#2606) | @@ -581,6 +581,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-23 | minor | Select and Mask is Photoshop's workspace with its own tools (#7069, #8148); TOOL-214-1 stays partial (Refine Hair, Object Aware, Presets); percentages and estimates unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 9311cc1869..2eb93d4c7e 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -115,7 +115,7 @@ id = "TOOL-214-1" target = "Select and Mask workspace: view modes, Refine Edge brush, 6 outputs" status = "partial" issue = 214 -note = "select.refineEdge dialog with a live preview in Photoshop's view modes: Onion Skin, Marching Ants, Overlay, On Black, On White, Black & White, On Layers, per-view Opacity, Show Edge (J), Show Original (P), F cycles, X shows the image (select_mask_view.rs, #1754); Refine Edge Brush (R, size, Expand Detection Area / Restore Original Edge, Alt swaps) paints select.refineEdge refineStrokes, estimated by colour-line matting (matting/brush.rs, #2972); outputs Selection, Layer Mask, New Layer, New Layer with Mask, New Document, New Document with Mask (#2998); the workspace tools Quick Selection, Brush, Lasso, Object Selection, Select Subject, Clear Selection and Invert run as select.refineEdge edits, drivable by agents (#7069); no workspace layout or toolbar yet" +note = "Photoshop's full-window Select and Mask workspace (select_mask_ui.rs, #7069, #8148); OK applies select.refineEdge. Live preview in Photoshop's view modes: Onion Skin, Marching Ants, Overlay, On Black, On White, Black & White, On Layers, per-view Opacity, Show Edge (J), Show Original (P), F cycles, X shows the image (select_mask_view.rs, #1754); Refine Edge Brush (R, size, Expand Detection Area / Restore Original Edge, Alt swaps) paints select.refineEdge refineStrokes, estimated by colour-line matting (matting/brush.rs, #2972); outputs Selection, Layer Mask, New Layer, New Layer with Mask, New Document, New Document with Mask (#2998); the workspace has the options bar, tools Quick Selection W, Refine Edge Brush R, Brush B, Object Selection W, Lasso and Polygonal Lasso L, Hand H, Zoom Z, Properties with Remember Settings, View Mode (Real-Time Refinement, High Quality Preview, Overlay colour and Indicates), Refine Mode, Edge Detection, Global Refinements with Clear Selection and Invert, Output Settings; the tools run as select.refineEdge edits; Ctrl+Z per edit; no Refine Hair (#2671), Object Aware (#2788) or Presets" [[item]] id = "TOOL-214-2"