diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index e1f0fc4ce23..904f118c08a 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -455,7 +455,37 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings { b } -/// `paint.stroke`: the Brush (and Eraser) tool. +/// When a stroke gets its first dab only although its path reaches past that dab: the distance +/// in pixels between dabs, as the paint crate steps them (`size × spacing` at the first point's +/// pressure), is longer than the whole path. A large brush with a large `spacing` does that +/// without any other sign (#8389). Returns that pitch and a warning naming it; `None` when the +/// stroke keeps its coverage or Spacing is off (dabs then follow the stroke's speed, not a pitch). +/// Whether the first dab covers the path is judged by that dab's own diameter, so a light first +/// point that shrinks a pressure-sized dab still warns. +fn spacing_warning(brush: &BrushSettings, pts: &[StrokePoint]) -> Option<(f64, String)> { + use photocraft_paint::dynamics::{DabBuilder, StepInput, apply_pose, base_diameter}; + let brush = brush.bounded_for_render(); + let first = pts.first()?; + if !brush.spacing_enabled { + return None; + } + let first = apply_pose(&brush, *first); + let pitch = DabBuilder::new(&brush).step_len(&first); + let step = StepInput { point: first, direction: 0.0, initial_direction: 0.0, step: 0 }; + let diameter = base_diameter(&brush, &step).max(1.0); + let length: f64 = pts.windows(2).map(|w| (w[1].x - w[0].x).hypot(w[1].y - w[0].y)).filter(|d| d.is_finite()).sum(); + (length > f64::from(diameter) / 2.0 && pitch > length).then(|| { + let dab = if (diameter - brush.size).abs() < 0.05 { format!("size {}", brush.size) } else { format!("the first dab's {diameter:.1} px (size {} at its pressure)", brush.size) }; + let warning = format!( + "spacing {} × {dab} puts dabs {pitch:.1} px apart, more than the {length:.1} px path, so the stroke got only its first dab; lower `spacing` for a continuous stroke", + brush.spacing + ); + (pitch, warning) + }) +} + +/// `paint.stroke`: the Brush (and Eraser) tool. When the spacing left the stroke with its first +/// dab only, the result also has the dab `pitch` in pixels and `warnings` saying so (#8389). pub fn paint_stroke(s: &mut Session, p: &Value) -> Result { let pts = parse_points(p, "paint.stroke")?; let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p); @@ -463,7 +493,13 @@ pub fn paint_stroke(s: &mut Session, p: &Value) -> Result { if flag(p, "fill", false) { return fill_region(s, p, label, brush, pts); } - stroke_with(s, "paint.stroke", p, label, brush, pts, false) + let warning = spacing_warning(&brush, &pts); + let mut r = stroke_with(s, "paint.stroke", p, label, brush, pts, false)?; + if let Some((pitch, warning)) = warning { + r["pitch"] = json!(pitch); + r["warnings"] = json!([warning]); + } + Ok(r) } /// `paint.stroke {fill: true}`: fill the region enclosed by `points` (their polygon) with the diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index ed9f7cfd203..c345876e771 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -1533,6 +1533,56 @@ fn brush_and_pencil_paint_a_cmyk_pick_with_the_picked_inks() { } } +/// The `paint.stroke` result's `warnings`, as strings (an absent list reads as empty). +fn stroke_warnings(r: &Value) -> Vec { + r["warnings"].as_array().map(|w| w.iter().filter_map(|m| m.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +/// #8389: `spacing` multiplies the brush diameter, so `size: 150, spacing: 5` steps dabs 750 px +/// apart and a 320 px stroke gets its first dab only. The result reports that pitch and warns +/// instead of losing the rest of the stroke's coverage silently. +#[test] +fn a_stroke_shorter_than_its_dab_pitch_reports_the_pitch_and_warns() { + let mut s = session(400, 400); + let r = s.execute("paint.stroke", json!({"points": [[200, 40], [200, 360]], "size": 150, "spacing": 5, "color": "#ff0000"})).unwrap(); + assert_eq!(r["pitch"].as_f64(), Some(750.0), "{r}"); + let warnings = stroke_warnings(&r); + assert_eq!(warnings.len(), 1, "{r}"); + assert!(warnings[0].contains("750") && warnings[0].contains("320"), "names the pitch and the path length: {r}"); + // Only the first dab landed: the far end of the stroke is untouched. + assert_eq!(rgba(&s, 200, 330)[3], 0.0); +} + +/// #8389: the warning is only for strokes that lose coverage, and their result keeps its old +/// shape (no `pitch`, no `warnings`). A normal spacing, a tap (a path the first dab already +/// covers) and Spacing turned off (dabs follow the stroke's speed, so there is no pitch) all +/// paint without one. +#[test] +fn strokes_that_keep_their_coverage_do_not_warn() { + let mut s = session(400, 400); + let quiet = |r: &Value| r.get("pitch").is_none() && r.get("warnings").is_none(); + let r = s.execute("paint.stroke", json!({"points": [[200, 40], [200, 360]], "size": 150, "spacing": 0.25})).unwrap(); + assert!(quiet(&r), "{r}"); + let tap = s.execute("paint.stroke", json!({"points": [[100, 100], [130, 100]], "size": 150, "spacing": 5})).unwrap(); + assert!(quiet(&tap), "the first dab covers the whole path: {tap}"); + let timed = s.execute("paint.stroke", json!({"points": [[20, 20], [380, 20]], "size": 10, "spacing": 5, "brush": {"spacingEnabled": false}})).unwrap(); + assert!(quiet(&timed), "{timed}"); +} + +/// #8389: whether the first dab covers the path is judged by that dab's diameter, not the brush +/// size. With the default pressure sizing, a first point at pressure 0.2 makes a `size: 150` dab +/// 30 px wide, so `spacing: 5` steps 150 px and a 50 px path reaches past the dab and still warns. +#[test] +fn a_light_first_point_is_judged_by_its_own_dab_diameter() { + let mut s = session(400, 400); + s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + let r = s.execute("paint.stroke", json!({"points": [[100, 200, 0.2], [150, 200, 0.2]], "size": 150, "spacing": 5, "color": "#ff0000"})).unwrap(); + assert_eq!(r["pitch"].as_f64(), Some(150.0), "{r}"); + let warnings = stroke_warnings(&r); + assert_eq!(warnings.len(), 1, "{r}"); + assert!(warnings[0].contains("30.0 px") && warnings[0].contains("150.0 px apart") && warnings[0].contains("50.0 px path"), "{r}"); +} + #[test] fn mixer_load_fills_the_reservoir_from_the_canvas_and_keeps_the_foreground() { let mut s = session(80, 40); diff --git a/crates/ui-egui/src/canvas/cursor_policy.rs b/crates/ui-egui/src/canvas/cursor_policy.rs index dab58709d57..f5e61808771 100644 --- a/crates/ui-egui/src/canvas/cursor_policy.rs +++ b/crates/ui-egui/src/canvas/cursor_policy.rs @@ -82,21 +82,23 @@ pub(crate) fn alt_samples(tool: Tool, mods: craft::keymap::Mods) -> bool { mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket | Tool::BackgroundEraser | Tool::ColorReplacement) } -/// Whether the Eyedropper is `tool`'s ⌥ stand-in: the tools ⌥ makes sample ([`alt_samples`]), and -/// the Triangle, whose ⌥ press samples where [`shape_alt_samples`] holds (#13364). +/// Whether the Eyedropper can be `tool`'s ⌥ stand-in. pub(crate) fn alt_eyedropper(tool: Tool) -> bool { - alt_samples(tool, Mods::ALT) || tool == Tool::Triangle + alt_samples(tool, Mods::ALT) || shape_alt_sets_fill(tool) } -/// Whether the Triangle tool's press at (x, y) with `mods` samples the colour there as the -/// foreground and the tool's Fill instead of drawing (#13364): ⌥ (⇧⌥ too) held at the press, in -/// Shape mode, with no shape layer active (with one, ⌥ subtracts from it). Path or Pixels mode and -/// a press with nothing to sample (off the image, over transparency) were not measured and keep -/// drawing from the centre; Control+⌥ stays the brush-resize drag, as in [`alt_samples`]. +/// Shape tools whose Alt Eyedropper also updates the tool's Fill. +pub(super) fn shape_alt_sets_fill(tool: Tool) -> bool { + matches!(tool, Tool::Triangle | Tool::CustomShape) +} + +/// Whether an Alt or Shift+Alt press samples the Triangle or Custom Shape foreground and Fill +/// (#13364, #15856). Sampling requires Shape mode, no active shape layer, and a sampleable pixel. +/// Control+Alt is excluded here, as in [`alt_samples`]. pub(crate) fn shape_alt_samples(app: &mut PhotocraftApp, mods: Mods, x: f64, y: f64) -> bool { mods.alt && !mods.ctrl - && app.ui.tool == Tool::Triangle + && shape_alt_sets_fill(app.ui.tool) && app.ui.tool_options.shape_mode == craft::draw::ui::VectorMode::Shape && crate::vector_ui::active_shape_path(app).is_none() && super::sampling::eyedropper_color(app, [x, y]).is_some() @@ -155,3 +157,7 @@ mod paint_bucket_cursor_tests; #[cfg(test)] #[path = "triangle_alt_eyedropper_tests.rs"] mod triangle_alt_eyedropper_tests; + +#[cfg(test)] +#[path = "custom_shape_alt_eyedropper_tests.rs"] +mod custom_shape_alt_eyedropper_tests; diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index b081bdfa3d4..1635f058609 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -368,10 +368,6 @@ fn on_sampler(app: &PhotocraftApp, x: f64, y: f64) -> bool { #[path = "triangle_alt_eyedropper_tests.rs"] mod triangle_alt_eyedropper_tests; -#[cfg(test)] -#[path = "../tools/vector_ui/custom_shape_alt_eyedropper_tests.rs"] -mod custom_shape_alt_eyedropper_tests; - #[cfg(test)] #[path = "../brush_shift_alt_sampler_tests.rs"] mod brush_shift_alt_sampler_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs b/crates/ui-egui/src/canvas/custom_shape_alt_eyedropper_tests.rs similarity index 72% rename from crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs rename to crates/ui-egui/src/canvas/custom_shape_alt_eyedropper_tests.rs index aff6ddfeef5..451d46cdb61 100644 --- a/crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs +++ b/crates/ui-egui/src/canvas/custom_shape_alt_eyedropper_tests.rs @@ -3,15 +3,21 @@ //! only after the drag started still draws from the centre, and with a shape layer active Alt at //! the press does not sample. +use craft::draw::ui::VectorMode; +use craft::keymap::Mods; use egui::Modifiers; +use photocraft_doc::{LayerContent, vector::PathOp}; use serde_json::json; -use super::*; +use super::shape_alt_samples; +use crate::PhotocraftApp; +use crate::canvas::testing::click; use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; /// 800 × 600, white Background, a red (220,30,30) pixel layer at 100,100 to 300,250 (active), /// black foreground, the Custom Shape tool in Shape mode. -fn app() -> PhotocraftApp { +fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); @@ -20,6 +26,7 @@ fn app() -> PhotocraftApp { app.run("select.deselect", json!({})).unwrap(); app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); app.ui.tool = Tool::CustomShape; + app.ui.tool_options.shape_mode = VectorMode::Shape; app.sync_views(); app } @@ -57,7 +64,7 @@ fn alt_click_on_the_red_layer_picks_it_as_foreground_and_fill() { app.ui.tool_options.shape_fill = false; app.ui.tool_options.shape_fill_gradient = Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); let (before, count) = (steps(&app), layers(&app)); - drag(&mut app, [200.0, 175.0], [200.0, 175.0], Modifiers::ALT, Modifiers::ALT); + click(&mut app, [200.0, 175.0], Modifiers::ALT); assert_eq!(foreground(&app), [220, 30, 30], "#DC1E1E"); assert_eq!(tool_fill(&app), [220, 30, 30], "Fill 220,30,30"); assert_eq!(layers(&app), count, "no new layer"); @@ -95,7 +102,7 @@ fn alt_pressed_after_the_drag_started_draws_from_the_centre() { assert_eq!(foreground(&app), [0, 0, 0], "nothing sampled"); assert_eq!(layers(&app), count + 1, "a shape layer"); let st = app.session.active().unwrap(); - let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; // In the 300,250 to 500,350 box round the press, centred on it (a corner drag centres on 450,325). let (x0, y0, x1, y1) = shape.path.control_bounds().unwrap(); assert!(x0 >= 299.5 && y0 >= 249.5 && x1 <= 500.5 && y1 <= 350.5, "{x0},{y0} to {x1},{y1}"); @@ -103,25 +110,31 @@ fn alt_pressed_after_the_drag_started_draws_from_the_centre() { } #[test] -fn a_shape_layer_active_does_not_sample() { +fn alt_drag_with_subtract_selected_edits_the_active_shape_without_sampling() { let mut app = app(); - app.run("shape.create", json!({"rect": [500, 400, 100, 100], "fill": "#3270c0", "stroke": null})).unwrap(); + app.run("shape.create", json!({"rect": [100, 100, 200, 150], "fill": "#3270c0", "stroke": null})).unwrap(); app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); - assert!(!shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0)); - tool_event(&mut app, ToolEvent::Down { x: 200.0, y: 175.0, pressure: 1.0 }, Modifiers::ALT); - assert!(!app.alt_sampling, "Alt at the press is not the Eyedropper"); - assert_eq!(foreground(&app), [0, 0, 0]); + click(&mut app, [200.0, 175.0], Modifiers::ALT); + assert_eq!(foreground(&app), [0, 0, 0], "an active shape prevents sampling"); + app.ui.tool_options.shape_path_op = "subtract".into(); + let count = layers(&app); + drag(&mut app, [150.0, 125.0], [250.0, 225.0], Modifiers::ALT, Modifiers::ALT); + assert_eq!(foreground(&app), [0, 0, 0], "nothing sampled"); + assert_eq!(layers(&app), count, "the component was added to the active shape layer"); + let st = app.session.active().unwrap(); + let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + assert!(shape.path.subpaths.iter().any(|subpath| subpath.op == PathOp::Subtract), "Subtract adds a component to the active shape"); } #[test] fn path_and_pixels_mode_and_ctrl_alt_do_not_sample() { let mut app = app(); - for mode in ["path", "pixels"] { - app.ui.tool_options.shape_mode = mode.into(); - assert!(!shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0), "{mode} mode was not measured"); + const ALT: Mods = Mods { alt: true, ..Mods::NONE }; + for mode in [VectorMode::Path, VectorMode::Pixels] { + app.ui.tool_options.shape_mode = mode; + assert!(!shape_alt_samples(&mut app, ALT, 200.0, 175.0), "{mode:?} mode keeps drawing"); } - app.ui.tool_options.shape_mode = "shape".into(); - assert!(shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0)); - assert!(!shape_alt_samples(&mut app, Modifiers { alt: true, ctrl: true, ..Modifiers::NONE }, 200.0, 175.0), "Ctrl+Alt is the brush resize"); - assert!(!shape_alt_samples(&mut app, Modifiers::NONE, 200.0, 175.0)); + app.ui.tool_options.shape_mode = VectorMode::Shape; + assert!(!shape_alt_samples(&mut app, Mods { ctrl: true, ..ALT }, 200.0, 175.0), "Ctrl+Alt does not sample"); + assert!(!shape_alt_samples(&mut app, Mods::NONE, 200.0, 175.0)); } diff --git a/crates/ui-egui/src/canvas/document_area.rs b/crates/ui-egui/src/canvas/document_area.rs index 79aa49bb3f5..bfc13452476 100644 --- a/crates/ui-egui/src/canvas/document_area.rs +++ b/crates/ui-egui/src/canvas/document_area.rs @@ -4,10 +4,15 @@ use std::cell::RefCell; use craft::behavior::PressPhase; +use craft::behavior::dock::Arrangement; +use craft::ui::bars::{Bar, BarKind}; use craft::ui::canvas::{SplitAt, SplitViews}; -use craft::ui::contract::{Bind, ShowContainer as _}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Elide, Text}; use craft::ui::docking::Arranged; use craft::ui::shell::CanvasPanel; +use craft::ui::style::StyleCx; +use craft::ui::tabs::{Tab, TabPartEvent}; use egui::Rect; use super::document_display::CanvasHost; @@ -34,7 +39,7 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// docked group `i` of `app.ui.document_windows`, showing that group's shown document, in the rect `SplitViews` /// places it in with the dividers at `app.ui.split_at`. `None` with no arrangement or fewer than two docked groups: /// the single canvas fills the area. -pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option> { +pub(super) fn arranged_panes(app: &PhotocraftApp, rect: Rect) -> Option> { let windows = &app.ui.document_windows; let layout = windows.arrangement?; let count = windows.docked.len(); @@ -55,6 +60,46 @@ pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option Option> { + let mut panes = arranged_panes(app, rect)?; + if app.ui.document_windows.arrangement == Some(Arrangement::Tile) { + let heights = tile_bar_heights(app); + for (_, pane) in &mut panes { + *pane = TilePane::new(*pane, heights).canvas; + } + } + Some(panes) +} + +fn tile_bar_heights(app: &PhotocraftApp) -> (f32, f32) { + StyleCx::with_root(app.ctx(), |cx| { + let size = &cx.tokens.size.bar; + let title = if app.session.prefs().workspace.large_tabs { size.title } else { size.tab }; + (title, size.status) + }) +} + +/// Tile chrome takes its own rows so it is outside the tools and drop targets of the canvas. +struct TilePane { + title: Rect, + canvas: Rect, + status: Rect, +} + +impl TilePane { + fn new(pane: Rect, (title, status): (f32, f32)) -> Self { + // With an exceptionally short pane, preserve a canvas before adding either full-height bar. + let top = pane.top() + if pane.height() > title { title } else { 0.0 }; + let bottom = pane.bottom() - if pane.bottom() - top > status { status } else { 0.0 }; + Self { + title: Rect::from_x_y_ranges(pane.x_range(), pane.top()..=top), + canvas: Rect::from_x_y_ranges(pane.x_range(), top..=bottom), + status: Rect::from_x_y_ranges(pane.x_range(), bottom..=pane.bottom()), + } + } +} + /// Tell the GPU canvas which documents are on screen (the arranged panes or the main canvas's, plus the shown /// document of every floating window): they split the display texture budget, and the textures of the others are /// freed first. Only a change of that set (or a document's size) re-splits it, so switching between shown documents @@ -62,7 +107,7 @@ pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option = match arranged_cells(app, app.last_canvas_rect) { + let mut shown: Vec = match arranged_panes(app, app.last_canvas_rect) { Some(cells) => cells.into_iter().map(|(d, _)| d).collect(), None => main_canvas_document(app).into_iter().collect(), }; @@ -151,24 +196,67 @@ fn arranged(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect, active: usiz group.shown = Some(active_id); } } - let Some(cells) = arranged_cells(app, rect) else { return false }; + let Some(panes) = arranged_panes(app, rect) else { return false }; + let heights = (layout == Arrangement::Tile).then(|| tile_bar_heights(app)); let count = app.ui.document_windows.docked.len(); let active_pane = app.ui.document_windows.docked.iter().position(|group| group.shown == Some(active_id)).unwrap_or(0); let shown: Vec> = app.ui.document_windows.docked.iter().map(|group| group.shown.and_then(|id| document_index(app, id))).collect(); // The panes are laid out from the dividers as this pass starts; an edit of them lands after the pass. let mut at = app.ui.split_at.clone(); let out = SplitViews::new(tl!("Documents"), layout, Bind::bound(&mut at)).count(count).active(active_pane).show(ui, |ui, _| { - for &(d, cell) in &cells { + for &(d, pane) in &panes { let view = app.ui.views[d].clone(); - let (v, _) = canvas_view(app, ui, CanvasHost::main(d), cell, view, d == active); + let tile = heights.map(|heights| TilePane::new(pane, heights)); + let canvas = tile.as_ref().map_or(pane, |tile| tile.canvas); + let (v, _) = canvas_view(app, ui, CanvasHost::main(d), canvas, view, d == active); + if let Some(tile) = &tile + && tile.status.height() > 0.0 + { + let id = app.session.documents()[d].doc.id; + let zoom = format!("{}%", super::fmt_zoom(v.zoom * 100.0)); + Bar::new("", BarKind::Status).id_salt(("tile-status", id)).show_at(ui, tile.status, |ui, _| { + Text::new(zoom.clone()).elide(Elide::End).show(ui); + }); + } if d != active { app.ui.views[d] = v; } } }); app.ui.split_at = at; - if let Some(d) = out.output.activated.and_then(|pane| shown.get(pane).copied().flatten()) { + let mut selected = out.output.activated.and_then(|pane| shown.get(pane).copied().flatten()); + let mut closing = Vec::new(); + if let Some(heights) = heights { + // SplitViews places a hit surface above each inactive canvas to handle its first press. + // Title controls are siblings above those surfaces so Close works even on an inactive tile. + for &(d, pane) in &panes { + let title = TilePane::new(pane, heights).title; + if title.height() <= 0.0 { + continue; + } + let doc = &app.session.documents()[d]; + let label = tabs::tab_title_at(app, d, app.ui.views[d].zoom * 100.0); + let mut tab = Tab::new(label).id_salt(("tile-title", doc.doc.id)).selected(d == active); + if app.session.prefs().workspace.large_tabs { + tab = tab.large(); + } + if doc.is_dirty() { + tab = tab.modified(); + } + let out = tab.show_at(ui, title); + if matches!(out.event, Some(TabPartEvent::Close)) { + closing.push(doc.doc.id); + } else if out.response.clicked() { + selected = Some(d); + } + } + } + if let Some(d) = selected { app.session.set_active(d); } + // A clean document can leave the session immediately, so close only after the pane indices were used. + for id in closing { + tabs::close_document(app, ui.ctx(), id); + } true } diff --git a/crates/ui-egui/src/canvas/eyedropper_tool.rs b/crates/ui-egui/src/canvas/eyedropper_tool.rs index be1ff5c906d..301ea49ebe2 100644 --- a/crates/ui-egui/src/canvas/eyedropper_tool.rs +++ b/crates/ui-egui/src/canvas/eyedropper_tool.rs @@ -4,8 +4,8 @@ //! As the Eyedropper tool, a press and each drag sample the foreground (Alt: the background). As //! the Alt stand-in, every sample goes to the foreground, because Alt is the key that called the //! stand-in, and Shift+Alt adds a colour sampler at the clicked pixel instead (#11890). As the -//! Triangle's stand-in, a sample also becomes the tool's solid Fill, and Shift+Alt samples as Alt -//! does (#13364). +//! Triangle or Custom Shape stand-in, a sample also becomes the tool's solid Fill, and Shift+Alt +//! samples as Alt does (#13364, #15856). use craft::behavior::{CancelReason, Cursor, PointerButton}; use craft::color_ui::ui::{EyedropperTool, SampleSize, SampleSource}; @@ -15,11 +15,11 @@ use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolHostResponse, T use craft::ui::primitives::Draw; use serde_json::json; +use super::cursor_policy::shape_alt_sets_fill; use super::document_display::CanvasHost; use super::sampling; use super::tools::{FamilyTool, ToolScope}; use crate::PhotocraftApp; -use crate::state::Tool; /// The gesture's flags, kept in `CanvasTools::eyedropper`. #[derive(Debug, Default)] @@ -37,7 +37,7 @@ pub(crate) struct PcEyedropper<'a> { inner: EyedropperTool<'a>, /// Runs as the Alt stand-in of a painting tool. stand_in: bool, - /// Runs as the Triangle's Alt stand-in: a pick also sets the tool's Fill. + /// Runs as a shape tool's Alt stand-in: a pick also sets the tool's Fill. shape_fill: bool, } @@ -58,20 +58,20 @@ pub(crate) fn drain(_app: &mut PhotocraftApp, _state: &mut EyedropperState, _res impl<'a> PcEyedropper<'a> { fn new(scope: &'a ToolScope<'a>, state: &'a mut EyedropperState, stand_in: bool) -> Self { - let (mut options, foreground, precise, triangle) = scope.with_app(|app| { + let (mut options, foreground, precise, shape_fill) = scope.with_app(|app| { let [r, g, b, _] = app.session.tools.foreground; let precise = app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise; - (app.ui.tool_options.eyedropper, Srgba::rgb(r, g, b), precise, app.ui.tool == Tool::Triangle) + (app.ui.tool_options.eyedropper, Srgba::rgb(r, g, b), precise, shape_alt_sets_fill(app.ui.tool)) }); // Preferences › Cursors › Other Cursors = Precise wants the plain crosshair, so no ring. options.show_ring &= !precise; let sample = move |at: [f64; 2], size: SampleSize, source: SampleSource| { scope.with_app(|app| sampling::pick(app, at, size, source)).map(|c| Srgba::rgb(c[0], c[1], c[2])) }; - PcEyedropper { scope, state, inner: EyedropperTool::new(options, sample).foreground(foreground), stand_in, shape_fill: stand_in && triangle } + PcEyedropper { scope, state, inner: EyedropperTool::new(options, sample).foreground(foreground), stand_in, shape_fill: stand_in && shape_fill } } - /// Writes the newest pick to its swatch; as the Triangle's stand-in, also makes the tool's Fill + /// Writes the newest pick to its swatch; as a shape tool's stand-in, also makes the tool's Fill /// solid, so it follows the foreground (`vector_ui::shapes::tool_paint`). fn apply(&mut self) { let Some(pick) = self.inner.take() else { return }; @@ -86,7 +86,7 @@ impl<'a> PcEyedropper<'a> { }); } - /// Shift+Alt adds a colour sampler: the painting tools' stand-in, not the Triangle's. + /// The painting tools' Shift+Alt stand-in adds a colour sampler. fn shift_adds_samplers(&self) -> bool { self.stand_in && !self.shape_fill } diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 3d3ff11c3d3..2d81c234e29 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -81,6 +81,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e // Previews edit what the command will: a targeted layer mask included (#780). let target = crate::dialogs::params::captured(app, &key); crate::filter_dialog::validate_match_color_destination(app, &key, &target, &fields).ok()?; + crate::filter_dialog::validate_lens_blur_document(app, &key, &target, fields.get("depthMap").and_then(serde_json::Value::as_str)).ok()?; let (cmd, params) = if crate::smart_filter_dialog::owns(&key) { crate::smart_filter_dialog::blend_command(app, &target, &dialog_fields).ok()? } else if crate::smart_filter_dialog::is_target(&target) { diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 6125c242b30..471d3d7ed72 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -84,10 +84,7 @@ pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, out: DocumentT for event in out.events { match event { DocumentTabsEvent::Selected(tab) | DocumentTabsEvent::Picked(tab) | DocumentTabsEvent::Activated(tab) => show_tab(app, tab), - DocumentTabsEvent::CloseRequested(DocTab::Doc(id)) => { - // The guarded close: a document with unsaved changes gets the save prompt. - let _ = crate::menus::invoke(app, ctx, "file.close", json!({"document": id.0})); - } + DocumentTabsEvent::CloseRequested(DocTab::Doc(id)) => close_document(app, ctx, id), DocumentTabsEvent::CloseRequested(DocTab::Opening(job)) => { let _ = crate::jobs_ui::cancel(app, job); } @@ -119,6 +116,13 @@ pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, out: DocumentT menu } +/// The guarded close shared by the tab strip and a tiled document's title. +pub(super) fn close_document(app: &mut PhotocraftApp, ctx: &egui::Context, id: DocId) { + if let Some(index) = document_index(app, id) { + let _ = crate::menus::invoke(app, ctx, "file.close", json!({"document": index})); + } +} + /// A chosen tab: a document tab shows that document, an opening tab its progress. fn show_tab(app: &mut PhotocraftApp, tab: DocTab) { match tab { @@ -172,7 +176,7 @@ fn tab_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, cx: &mut BodyCx<'_>, str }; let count = app.session.documents().len(); let has_path = app.session.documents()[index].path.is_some(); - let items = tab_context_items(id, count, has_path); + let items = tab_context_items(id, index, count, has_path); let mut entries = Vec::with_capacity(items.len() + TAB_MENU_SEPARATORS_AFTER.len()); for (row, (label, _, _, enabled)) in items.iter().enumerate() { entries.push(Entry::new(row, tl!(*label)).enabled(*enabled)); @@ -198,18 +202,19 @@ pub(crate) const TAB_MENU_SEPARATORS_AFTER: [usize; 2] = [4, 6]; pub(crate) type TabMenuItem = (&'static str, &'static str, serde_json::Value, bool); /// All tab actions go through the same guarded commands as the menu bar, including the -/// unsaved-changes prompt. The clicked tab's document `doc` is explicit even when another document is active. +/// unsaved-changes prompt. The clicked tab's document `doc` (at `index` in the session's list now) is explicit even when +/// another document is active: the file commands name it by its index, Move to New Window by its id. /// Order and separators follow the reference application (#11403); see [`TAB_MENU_SEPARATORS_AFTER`]. -pub(crate) fn tab_context_items(doc: DocId, count: usize, has_path: bool) -> [TabMenuItem; 8] { +pub(crate) fn tab_context_items(doc: DocId, index: usize, count: usize, has_path: bool) -> [TabMenuItem; 8] { [ ("Consolidate All to Here", "window.arrange.consolidateAllToTabs", json!({}), count > 1), - ("Close", "file.close", json!({"document": doc.0}), true), + ("Close", "file.close", json!({"document": index}), true), ("Close All", "file.closeAll", json!({}), true), - ("Close Others", "file.closeOthers", json!({"document": doc.0}), count > 1), + ("Close Others", "file.closeOthers", json!({"document": index}), count > 1), ("Move to New Window", "window.arrange.floatInWindow", json!({"document": doc.0}), true), ("New Document…", "file.new", json!({}), true), ("Open Document…", "file.open", json!({}), true), - (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": doc.0}), has_path), + (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": index}), has_path), ] } diff --git a/crates/ui-egui/src/canvas/tabs_tests.rs b/crates/ui-egui/src/canvas/tabs_tests.rs index b36c509fe1d..a1cf6385162 100644 --- a/crates/ui-egui/src/canvas/tabs_tests.rs +++ b/crates/ui-egui/src/canvas/tabs_tests.rs @@ -136,3 +136,100 @@ fn quick_mask_mode_names_the_quick_mask_in_the_tab() { let detail = title(&h); assert!(detail.contains("Layer 1") && detail.contains("RGB") && !detail.contains("Quick Mask"), "{detail}"); } + +#[test] +fn a_tab_close_resolves_the_document_to_its_current_index() { + let mut h = harness(2); + let other = h.state().session.active().unwrap().doc.id; + h.query_all_by_role(Role::Button) + .find(|n| n.accesskit_node().label().is_some_and(|label| label.starts_with("Close ch1-p01.png"))) + .expect("the other document tab's close button") + .click(); + h.run_steps(3); + let docs = h.state().session.documents(); + assert_eq!(docs.len(), 1); + assert_eq!(docs[0].doc.id, other); +} + +fn tiled_app(width: f32) -> Harness<'static, Box> { + let mut h = Harness::builder().with_size(vec2(width, 720.0)).with_pixels_per_point(1.25).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 180, "height": 120, "name": "Edited photograph with a long title.psd", "depth": 16})).unwrap(); + app.run("layer.new.layer", json!({"name": "Retouch"})).unwrap(); + app.run("file.new", json!({"width": 160, "height": 100, "name": "Reference photograph.psd"})).unwrap(); + app + }); + h.run_steps(3); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "window.arrange.tile", json!({})).unwrap(); + h.run_steps(4); + h +} + +fn tiled_control<'a>(h: &'a Harness<'_, Box>, role: Role, label: &str) -> Option> { + let area = h.state().last_canvas_rect; + h.query_all_by_role(role).filter(|n| n.accesskit_node().label().is_some_and(|text| text.contains(label))).find(|n| area.contains(n.rect().center())) +} + +#[test] +fn tiled_document_titles_follow_individual_views() { + for width in [1120.0, 652.0] { + let mut h = tiled_app(width); + let original = h.state().ui.views[1].zoom; + h.state_mut().ui.views[0].zoom = 0.5; + h.state_mut().ui.views[0].clear_pending(); + h.run_steps(3); + let app = h.state(); + let name = &app.session.documents()[0].doc.name; + let title = tiled_control(&h, Role::Tab, name).expect("the edited document's title is inside its tile"); + let label = title.accesskit_node().label().unwrap(); + assert!(label.contains("@ 50% (Retouch, RGB/16)") && label.ends_with(", modified"), "{label}"); + let panes = super::document_area::arranged_panes(app, app.last_canvas_rect).unwrap(); + let cell = panes.iter().find(|(i, _)| *i == 0).unwrap().1; + let canvases = super::arranged_cells(app, app.last_canvas_rect).unwrap(); + let canvas = canvases.iter().find(|(i, _)| *i == 0).unwrap().1; + let close = tiled_control(&h, Role::Button, &format!("Close {name}")).expect("close is available in the tile"); + assert!(cell.contains_rect(title.rect()) && cell.contains_rect(close.rect()), "title and close stay inside the tile at {width} points"); + let zoom = h.query_all_by_label("50%").find(|n| cell.contains_rect(n.rect())).expect("the edited document's tile shows its own zoom"); + assert!(title.rect().bottom() <= canvas.top() && zoom.rect().top() >= canvas.bottom(), "chrome is outside its canvas"); + assert!(matches!(app.drop_to(&h.ctx, Some(title.rect().center())), crate::file_open::DropTo::Window)); + assert_eq!(h.state().ui.views[1].zoom, original, "the other tile keeps its zoom"); + title.click(); + h.run_steps(3); + assert_eq!(h.state().session.active_index(), Some(0)); + } +} + +#[test] +fn tiled_document_close_uses_the_clicked_document_and_save_prompt() { + let mut h = tiled_app(1120.0); + let edited = h.state().session.documents()[0].doc.id; + assert!(h.state().session.documents()[0].is_dirty()); + assert!(!h.state().session.documents()[1].is_dirty()); + assert_eq!(h.state().session.active_index(), Some(1)); + h.state_mut().ui.tool = crate::state::Tool::Brush; + let revisions: Vec<_> = h.state().session.documents().iter().map(|d| d.revision).collect(); + let at = tiled_control(&h, Role::Button, "Close Edited photograph").expect("the inactive tile has its own close button").rect().center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + assert!(h.state().discard.is_some(), "closing edits asks whether to save"); + assert!(h.state().session.documents().iter().map(|d| d.revision).eq(revisions), "the close press produces no brush edit"); + assert_eq!(h.state().session.documents().len(), 2); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().discard.is_none()); + assert_eq!(h.state().session.documents().len(), 2, "Cancel leaves both tiles open"); + tiled_control(&h, Role::Button, "Close Reference photograph").expect("the clean tile has its own close button").click(); + h.run_steps(3); + assert!(h.state().discard.is_none()); + let docs = h.state().session.documents(); + assert_eq!(docs.len(), 1); + assert_eq!(docs[0].doc.id, edited, "the close button removed only the clean document"); + assert!(tiled_control(&h, Role::Tab, "Edited photograph").is_none(), "one document returns to the original single canvas"); +} diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 8e39edf4810..d5670e2df73 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -364,7 +364,7 @@ impl CanvasTool for Preflight<'_, '_> { return ToolAction::Done; } let at = [doc.x, doc.y]; - // The Triangle's ⌥ press that samples is the Eyedropper stand-in's, not a shape (#13364). + // Let the Eyedropper take an Alt press that samples the shape tool's Fill. if self.alt_stand_in && self.scope.with_app(|app| super::cursor_policy::shape_alt_samples(app, pointer.mods, at[0], at[1])) { return ToolAction::Ignored; } diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 12694ba08e7..4654ed7847e 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -31,6 +31,8 @@ const MATCH_COLOR: &str = "image.adjustments.matchColor"; const SCALE_EFFECTS: &str = "layer.layerStyle.scaleEffects"; #[cfg(test)] pub(crate) const MATCH_COLOR_DESTINATION: &str = "__matchColorDestination"; +/// The key of the document id Lens Blur captures at open (see [`validate_lens_blur_document`]). +const LENS_BLUR_DOCUMENT: &str = "lensBlurDocument"; /// The decimals of the Rotate Canvas angle: it keeps hundredths of a degree, so the ruler's /// straightening angle reaches the dialog as 33.69 and not 33.7 (#12035). @@ -576,7 +578,14 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result let spec = photocraft_engine::commands::find(command).ok_or_else(|| format!("{command} has no dialog"))?; let params = params(app, command, spec.params); let fields = fields(app, command, ¶ms); - let captured = if command == MATCH_COLOR { json!(app.session.active().map(|st| (st.doc.id, st.active_layer))) } else { Value::Null }; + let captured = if command == MATCH_COLOR { + json!(app.session.active().map(|st| (st.doc.id, st.active_layer))) + } else if command == rows::LENS_BLUR { + // The Depth Map Source lists this document's alpha channels by index. + json!({ LENS_BLUR_DOCUMENT: app.session.active().map(|st| st.doc.id) }) + } else { + Value::Null + }; let reset = reset_values(¶ms, &fields); // Photoshop titles the Scale Effects… dialog with the longer name (#14996). let title = if command == SCALE_EFFECTS { Label::from(tl!("Scale Layer Effects")) } else { title_of(spec.label) }; @@ -659,6 +668,14 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value { map.insert("matte".into(), color); } } + // Lens Blur's Source menu names an alpha channel `channel:N` (by index: two channels may share a name); the command + // takes the `channel` source and the channel's index. + if command == rows::LENS_BLUR + && let Some(index) = map.get("depthMap").and_then(Value::as_str).and_then(rows::channel_of_choice) + { + map.insert("depthMap".into(), json!("channel")); + map.insert("depthChannel".into(), json!(index)); + } if command == "filter.blur.radialBlur" && let Some([x, y]) = fields.point("center") { @@ -701,11 +718,28 @@ pub(crate) fn validate_match_color_destination(app: &PhotocraftApp, command: &st Ok(()) } -/// The held-OK check of Match Color: the destination captured at open still holds. +/// Lens Blur's Depth Map Source names an alpha channel by its index in the document the dialog opened on (`captured`): +/// if another document became active since (the control channel can switch it under the dialog), that index would pick +/// a channel of the other document, so preview and OK refuse it. The other sources do not name a channel. +/// `depth_map` is the `depthMap` param as [`command_params`] makes it. +pub(crate) fn validate_lens_blur_document(app: &PhotocraftApp, command: &str, captured: &Value, depth_map: Option<&str>) -> Result<(), String> { + if command != rows::LENS_BLUR || depth_map != Some("channel") { + return Ok(()); + } + // Only the dialog `open` made captures its document; a Smart Filter edit captures its own target and is checked there. + let Some(opened) = captured.get(LENS_BLUR_DOCUMENT) else { return Ok(()) }; + let opened = opened.as_u64(); + let active = app.session.active().map(|st| st.doc.id.0); + if opened.is_some() && opened == active { Ok(()) } else { Err("the Lens Blur depth map channel belongs to another document".into()) } +} + +/// The held-OK check: Match Color's destination and Lens Blur's depth channel document captured at open still hold. pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), Label> { let destination = crate::dialogs::params::captured(app, &result.key); let fields = fields_map(&result.fields); validate_match_color_destination(app, &result.key, &destination, &fields).map_err(Label::from)?; + let params = command_params(&result.key, &result.fields); + validate_lens_blur_document(app, &result.key, &destination, params.get("depthMap").and_then(Value::as_str)).map_err(Label::from)?; validate_match_color_source_layer(app, &result.key, &fields).map_err(Label::from) } diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 0d816616e68..99f4179f154 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1865,3 +1865,63 @@ fn indexed_matte_other_shows_the_color_row_and_none_hides_it() { assert_eq!(fields_of(harness.state(), id).text("matte"), Some("none")); assert!(try_set(harness.state_mut(), id, "matteColor", json!([0.0, 0.0, 1.0])).is_err(), "None hides the colour row"); } + +/// An alpha channel chosen as Lens Blur's depth map reaches the command as the `channel` source and its index: the +/// menu's own `channel:N` id was sent as is, and the engine refused it at OK and in the preview. +#[test] +fn lens_blur_alpha_channel_source_runs() { + let mut app = new_app(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + for name in ["Mask", "Depth"] { + app.run("select.all", json!({})).unwrap(); + app.run("select.saveSelection", json!({"name": name})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + let id = open(&mut app, LENS_BLUR).unwrap(); + passes(&mut app, 2); + set(&mut app, id, "depthMap", json!("channel:1")); + passes(&mut app, 2); + let params = command_params(LENS_BLUR, &fields_of(&app, id)); + assert_eq!((¶ms["depthMap"], ¶ms["depthChannel"]), (&json!("channel"), &json!(1)), "{params}"); + app.run(LENS_BLUR, params).expect("the command takes the channel source"); + // The other sources pass through. + set(&mut app, id, "depthMap", json!("transparency")); + let params = command_params(LENS_BLUR, &fields_of(&app, id)); + assert_eq!((¶ms["depthMap"], params.get("depthChannel")), (&json!("transparency"), None)); +} + +/// A Lens Blur depth channel is an index into the document the dialog opened on: when the control channel makes another +/// document active under the open dialog, preview and OK refuse the channel instead of blurring by that document's +/// channel at the same index; back on the first document, OK applies it there. +#[test] +fn lens_blur_refuses_a_depth_channel_after_the_document_changed() { + let mut app = new_app(); + for _ in 0..2 { + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + for name in ["Mask", "Depth"] { + app.run("select.all", json!({})).unwrap(); + app.run("select.saveSelection", json!({"name": name})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + } + let ctx = app.ctx().clone(); + match_color_control(&mut app, &ctx, "ui.window.open", json!({"document": 0})); + let id = open(&mut app, LENS_BLUR).unwrap(); + passes(&mut app, 2); + set(&mut app, id, "depthMap", json!("channel:1")); + passes(&mut app, 2); + let steps: Vec<_> = app.session.documents().iter().map(|st| st.history.past_len()).collect(); + + match_color_control(&mut app, &ctx, "ui.window.open", json!({"document": 1})); + assert!(crate::canvas::ensure_filter_preview(&mut app, 1, &ctx).is_none(), "no preview with the other document's channel"); + assert!(!ok(&mut app, id), "OK is refused and the dialog stays open"); + assert_eq!(app.session.documents().iter().map(|st| st.history.past_len()).collect::>(), steps, "nothing was blurred"); + // Sources that name no channel are not bound to a document. + let opened = crate::dialogs::params::captured(&app, LENS_BLUR); + assert!(validate_lens_blur_document(&app, LENS_BLUR, &opened, Some("transparency")).is_ok()); + + match_color_control(&mut app, &ctx, "ui.window.open", json!({"document": 0})); + assert!(ok(&mut app, id), "on the document it opened on, the channel is accepted"); + assert_eq!(app.session.documents()[0].history.past_len(), steps[0] + 1, "Lens Blur ran on the first document"); + assert_eq!(app.session.documents()[1].history.past_len(), steps[1], "the second document is untouched"); +} diff --git a/crates/ui-egui/src/doc_tab_menu_tests.rs b/crates/ui-egui/src/doc_tab_menu_tests.rs index aa3a8e46da2..b373f1ca48c 100644 --- a/crates/ui-egui/src/doc_tab_menu_tests.rs +++ b/crates/ui-egui/src/doc_tab_menu_tests.rs @@ -6,23 +6,51 @@ use serde_json::json; use crate::canvas::tabs::tab_context_items; use crate::{PhotocraftApp, Services}; -/// The rows name the clicked tab's document by its id, which stays the same when another document closes. +/// The rows name the clicked tab's document: the file commands by its index in the session's list (they take an index), +/// Move to New Window by its id. #[test] fn each_row_names_its_command_and_the_clicked_tabs_document() { - let items = tab_context_items(DocId(7), 3, true); + let items = tab_context_items(DocId(7), 1, 3, true); let menu = crate::menus::menu_rows(&PhotocraftApp::new(photocraft_engine::Session::new(), Services::default())); let want = [ ("Consolidate All to Here", "window.arrange.consolidateAllToTabs", json!({})), - ("Close", "file.close", json!({"document": 7})), + ("Close", "file.close", json!({"document": 1})), ("Close All", "file.closeAll", json!({})), - ("Close Others", "file.closeOthers", json!({"document": 7})), + ("Close Others", "file.closeOthers", json!({"document": 1})), ("Move to New Window", "window.arrange.floatInWindow", json!({"document": 7})), ("New Document…", "file.new", json!({})), ("Open Document…", "file.open", json!({})), - (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": 7})), + (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": 1})), ]; for ((label, id, params, _), (wl, wi, wp)) in items.iter().zip(want) { assert_eq!((*label, *id, params), (wl, wi, &wp)); assert!(menu.iter().any(|row| row.command.id == *id) || photocraft_engine::commands::find(id).is_some(), "{id} is a command"); } } + +/// A document's id is not its place in the list: ids come from a counter shared with layers and other objects, so the +/// menu's Close, Close Others and Reveal in Finder named a document that did not exist and nothing happened. +#[test] +fn the_tab_menu_closes_the_clicked_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + for name in ["A", "B", "C"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + let ctx = app.ctx().clone(); + let names = |app: &PhotocraftApp| app.session.documents().iter().map(|st| st.doc.name.clone()).collect::>(); + assert!(app.session.documents().iter().enumerate().any(|(i, st)| st.doc.id.0 != i as u64), "ids are not indices"); + let run = |app: &mut PhotocraftApp, name: &str, label: &str| { + let index = app.session.documents().iter().position(|st| st.doc.name == name).unwrap(); + let id = app.session.documents()[index].doc.id; + let count = app.session.documents().len(); + let (_, command, params, _) = tab_context_items(id, index, count, false).into_iter().find(|(l, ..)| *l == label).unwrap(); + crate::menus::invoke(app, &ctx, command, params).unwrap(); + }; + // Close on a tab that is not the active one (C is). + run(&mut app, "B", "Close"); + assert_eq!(names(&app), ["A", "C"]); + run(&mut app, "A", "Close Others"); + assert_eq!(names(&app), ["A"]); + run(&mut app, "A", "Close"); + assert!(names(&app).is_empty()); +} diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 6f41518347c..be722c1e9dc 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -460,7 +460,11 @@ impl PhotocraftApp { /// Where a web-build drop at `at` lands (the web build's own drop path until FW-264). Over a /// window or dialog it's not the canvas. On the canvas it carries the document point under `at`. pub(crate) fn drop_to(&self, ctx: &egui::Context, at: Option) -> DropTo { - let uncovered = at.is_some_and(|p| ctx.layer_id_at(p).is_none_or(|l| l.order == egui::Order::Background)); + let uncovered = at.is_some_and(|p| { + ctx.layer_id_at(p).is_none_or(|l| l.order == egui::Order::Background) + && (self.ui.document_windows.arrangement != Some(craft::behavior::dock::Arrangement::Tile) + || crate::canvas::arranged_cells(self, self.last_canvas_rect).is_none_or(|cells| cells.iter().any(|(_, rect)| rect.contains(p)))) + }); match target_at(at, uncovered, self.drop_canvas_rect, self.session.active().is_some()) { DropTo::Canvas { .. } => DropTo::Canvas { at: at.and_then(|p| {